diff --git a/.env.example b/.env.example index 8944f3c8f..f9f0d2b05 100644 --- a/.env.example +++ b/.env.example @@ -103,6 +103,15 @@ IdentityEvents__ClientSecret=learnstack-event-reader-dev-secret # Keep it distinct from every other credential; never pass it to the web or the Seeder. KEYCLOAK_FEDERATION_ADMIN_SECRET=learnstack-federation-admin-dev-secret Federation__ClientSecret=learnstack-federation-admin-dev-secret +# ADR-0107 section 7 confined account-removal client (realm-management/manage-users only; +# it can also create and update users, so treat its secret as the most sensitive machine +# credential). Keycloak imports it as ${KEYCLOAK_ACCOUNT_REMOVAL_SECRET}; realm +# reconciliation verifies an existing secret and never rotates it. The API reads the same +# value as AccountRemoval__ClientSecret; without it account removal stays unconfigured and +# every closure refuses at its last step. Keep it distinct from every other credential +# (the federation admin secret included); never pass it to the web or the Seeder. +KEYCLOAK_ACCOUNT_REMOVAL_SECRET=learnstack-account-removal-dev-secret +AccountRemoval__ClientSecret=learnstack-account-removal-dev-secret # Optional operator egress allow-list for private or non-443 IdP hosts (exact host or # host:port, no wildcard). Empty by default; tenant input can never extend it. # Federation__Egress__AllowedHosts__0=idp.corp.internal:8443 diff --git a/README.md b/README.md index c3bb3aaa8..6c0286784 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) | @@ -138,11 +138,12 @@ ordinary authoring pipeline and verifies completed acts before skipping them on [SeedData](backend/src/LearnStack.Tools.Seeder/SeedData.cs) owns the complete inventory. Both combined entries then await the same bounded development-realm reconciler. Older private files must explicitly add `KEYCLOAK_WEB_CLIENT_SECRET`, -`KEYCLOAK_FEDERATION_ADMIN_SECRET` (with the identical `Federation__ClientSecret`) +`KEYCLOAK_FEDERATION_ADMIN_SECRET` (with the identical `Federation__ClientSecret`), +`KEYCLOAK_ACCOUNT_REMOVAL_SECRET` (with the identical `AccountRemoval__ClientSecret`) and the stable authority/issuer pair described in the realm guide; existing passwords/MFA and provider IDs are preserved. Prepare these secrets before the first `make dev` import, and retain them across reruns; `make dev` does not start -without the federation admin secret. Older files also need +without the federation admin or account removal secrets. Older files also need explicit private permissions after verifying their ownership/type; Makefile creation does not repair existing files. The [realm guide](infra/keycloak/README.md#secret-continuity-and-recovery) owns setup, @@ -151,7 +152,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 733e312a6..8e2df5f74 100644 --- a/backend/openapi/v1.json +++ b/backend/openapi/v1.json @@ -6175,16 +6175,40 @@ "x-version-introduced": "v1" } }, - "/api/v1/identity/federation": { + "/api/v1/identity/data-request-entry/scopes": { "get": { "tags": [ - "Federation" + "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. Paging is forward only: follow pageInfo.nextCursor; there is no previous page.", + "schema": { + "maximum": 20, + "minimum": 1, + "type": "integer", + "format": "int32", + "default": 20 + } + } ], - "description": "Current tenant\u0027s nonsecret federation connection in an orgless context, under Tenant identity.federation.admin. Audit Off: no personal data. One provider readback under the request deadline; a definitive drift or an expired test window is recorded as a MUST apply outcome. No request body or query. No-store.", - "operationId": "GetFederationConnection", "responses": { "200": { - "description": "Current nonsecret connection detail, or a null connection.", + "description": "The subject\u0027s retained groups on the real host, in order.", "headers": { "Cache-Control": { "required": true, @@ -6194,27 +6218,18 @@ ], "type": "string" } - }, - "ETag": { - "description": "The connection revision, present exactly when a live connection exists.", - "schema": { - "maxLength": 21, - "minLength": 3, - "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", - "type": "string" - } } }, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/FederationConnectionResponse" + "$ref": "#/components/schemas/RetainedDataRequestScopePageResponse" } } } }, "400": { - "description": "validation_failed for malformed or noncanonical input, an unexpected body or query, an invalid precondition, or a refused egress address.", + "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, @@ -6235,7 +6250,7 @@ } }, "401": { - "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", + "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, @@ -6265,7 +6280,7 @@ } }, "403": { - "description": "forbidden without current Tenant identity.federation.admin in an orgless context; feature_disabled when the protocol is not entitled.", + "description": "forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed.", "headers": { "Cache-Control": { "required": true, @@ -6286,7 +6301,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or no live connection.", + "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, @@ -6337,7 +6352,7 @@ } }, "413": { - "description": "payload_too_large; federation bodies are at most 16 KiB.", + "description": "payload_too_large; request bodies are at most 4 KiB.", "headers": { "Cache-Control": { "schema": { @@ -6386,7 +6401,7 @@ } }, "500": { - "description": "internal_error without provider, query, identity or submitted-value diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -6407,7 +6422,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable: the provider, egress fetcher or storage could not decide; nothing unconfirmed is reported as applied.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -6430,45 +6445,59 @@ }, "security": [ { - "TenantBearer": [] + "TenantBearer": [], + "NativeSessionSource": [] } ], "x-version-introduced": "v1" } }, - "/api/v1/identity/federation/configuration": { - "put": { + "/api/v1/identity/data-request-entry/requests": { + "get": { "tags": [ - "Federation" + "DataRequestEntry" ], - "description": "ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited.", - "operationId": "ConfigureFederation", + "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": [ { - "name": "If-Match", - "in": "header", - "description": "Absent only to create the tenant\u0027s first live connection; otherwise one canonical strong quoted decimal connection revision. A stale revision or an existing live connection is 409.", + "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": 21, - "minLength": 3, - "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "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/FederationConfigurationInput" - } + }, + { + "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" } }, - "required": true - }, + { + "name": "limit", + "in": "query", + "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, + "type": "integer", + "format": "int32", + "default": 20 + } + } + ], "responses": { "200": { - "description": "Settled operation receipt.", + "description": "Current receipt-safe projection: status and counts, never content.", "headers": { "Cache-Control": { "required": true, @@ -6483,13 +6512,13 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/FederationOperationResponse" + "$ref": "#/components/schemas/OwnDataRequestPage" } } } }, "400": { - "description": "validation_failed for malformed or noncanonical input, an unexpected body or query, an invalid precondition, or a refused egress address.", + "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, @@ -6510,7 +6539,7 @@ } }, "401": { - "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", + "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, @@ -6540,7 +6569,7 @@ } }, "403": { - "description": "forbidden without current Tenant identity.federation.admin in an orgless context; feature_disabled when the protocol is not entitled.", + "description": "forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed.", "headers": { "Cache-Control": { "required": true, @@ -6561,7 +6590,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or no live connection.", + "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, @@ -6597,7 +6626,7 @@ "required": true, "schema": { "enum": [ - "PUT" + "GET" ], "type": "string" } @@ -6612,7 +6641,7 @@ } }, "413": { - "description": "payload_too_large; federation bodies are at most 16 KiB.", + "description": "payload_too_large; request bodies are at most 4 KiB.", "headers": { "Cache-Control": { "schema": { @@ -6661,7 +6690,7 @@ } }, "500": { - "description": "internal_error without provider, query, identity or submitted-value diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -6682,28 +6711,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable: the provider, egress fetcher or storage could not decide; nothing unconfirmed is reported as applied.", - "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 stale revision, a pending operation inside its quiet window or a racing first configuration; business_rule_violation for a lifecycle state the operation does not admit or a changed issuer or entity identifier.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -6726,29 +6734,42 @@ }, "security": [ { - "TenantBearer": [] + "TenantBearer": [], + "NativeSessionSource": [] } ], "x-version-introduced": "v1" } }, - "/api/v1/identity/federation/secret-rotations": { + "/api/v1/identity/data-request-entry/exports": { "post": { "tags": [ - "Federation" + "DataRequestEntry" ], - "description": "ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited.", - "operationId": "RotateFederationSecret", + "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": "If-Match", + "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": "One canonical strong quoted decimal connection revision. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale revision is 409.", + "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": 21, - "minLength": 3, - "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "maxLength": 128, + "minLength": 8, + "pattern": "^[!-~]{8,128}$", "type": "string" } } @@ -6757,15 +6778,15 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/FederationSecretInput" + "$ref": "#/components/schemas/EmptyAdministrationInput" } } }, "required": true }, "responses": { - "200": { - "description": "Settled operation receipt.", + "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, @@ -6775,18 +6796,58 @@ ], "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/FederationOperationResponse" + "$ref": "#/components/schemas/DataRequestAcceptedResponse" } } } }, "400": { - "description": "validation_failed for malformed or noncanonical input, an unexpected body or query, an invalid precondition, or a refused egress address.", + "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 lockey_request_already_active (a request of this kind is still active in the group), lockey_blocked_hold, or lockey_subject_not_admitted (the person\u0027s account is closing or closed: nothing is filed); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", "headers": { "Cache-Control": { "required": true, @@ -6807,7 +6868,7 @@ } }, "401": { - "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", + "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, @@ -6837,7 +6898,7 @@ } }, "403": { - "description": "forbidden without current Tenant identity.federation.admin in an orgless context; feature_disabled when the protocol is not entitled.", + "description": "forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed.", "headers": { "Cache-Control": { "required": true, @@ -6858,7 +6919,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or no live connection.", + "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, @@ -6909,7 +6970,7 @@ } }, "413": { - "description": "payload_too_large; federation bodies are at most 16 KiB.", + "description": "payload_too_large; request bodies are at most 4 KiB.", "headers": { "Cache-Control": { "schema": { @@ -6958,7 +7019,7 @@ } }, "500": { - "description": "internal_error without provider, query, identity or submitted-value diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -6979,28 +7040,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable: the provider, egress fetcher or storage could not decide; nothing unconfirmed is reported as applied.", - "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 stale revision, a pending operation inside its quiet window or a racing first configuration; business_rule_violation for a lifecycle state the operation does not admit or a changed issuer or entity identifier.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -7023,29 +7063,42 @@ }, "security": [ { - "TenantBearer": [] + "TenantBearer": [], + "NativeSessionSource": [] } ], "x-version-introduced": "v1" } }, - "/api/v1/identity/federation/display-name": { - "put": { + "/api/v1/identity/data-request-entry/erasures": { + "post": { "tags": [ - "Federation" + "DataRequestEntry" ], - "description": "ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited.", - "operationId": "RenameFederation", + "description": "The subject files an erasure of their own data in one retained group (ADR-0106 \u00A7 3, \u00A7 9; ADR-0107 \u00A7 5): the path of a Suspended person and of one whose Membership was revoked. The request is scheduled and its job runs once the 24-hour window ends; until then it can be cancelled. Refused when the subject holds no Membership of any status there, while the subject is the tenant\u0027s only eligible tenant-wide administrator (tenant-wide group) or while a hold applies. Strict empty JSON object. MUST audited.", + "operationId": "CreateRetainedDataErasure", "parameters": [ { - "name": "If-Match", + "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": "One canonical strong quoted decimal connection revision. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale revision is 409.", + "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": 21, - "minLength": 3, - "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "maxLength": 128, + "minLength": 8, + "pattern": "^[!-~]{8,128}$", "type": "string" } } @@ -7054,15 +7107,15 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/FederationDisplayNameInput" + "$ref": "#/components/schemas/EmptyAdministrationInput" } } }, "required": true }, "responses": { - "200": { - "description": "Settled operation receipt.", + "202": { + "description": "Accepted: the request\u0027s initial resource, scheduled. Its erasure runs as a background job once its 24-hour cancellable window ends; read the group\u0027s requests for its status.", "headers": { "Cache-Control": { "required": true, @@ -7072,18 +7125,58 @@ ], "type": "string" } - } - }, - "content": { - "application/json": { + }, + "ETag": { + "description": "The request\u0027s version.", + "required": true, "schema": { - "$ref": "#/components/schemas/FederationOperationResponse" - } - } + "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/DataErasureAcceptedResponse" + } + } } }, "400": { - "description": "validation_failed for malformed or noncanonical input, an unexpected body or query, an invalid precondition, or a refused egress address.", + "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 lockey_request_already_active (an erasure is still active in the group), lockey_blocked_last_administrator (the person is the tenant\u0027s only eligible tenant-wide administrator; another must be appointed first), lockey_blocked_hold, or lockey_subject_not_admitted (the person\u0027s account is closing or closed: nothing is filed); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", "headers": { "Cache-Control": { "required": true, @@ -7104,7 +7197,7 @@ } }, "401": { - "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", + "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, @@ -7134,7 +7227,7 @@ } }, "403": { - "description": "forbidden without current Tenant identity.federation.admin in an orgless context; feature_disabled when the protocol is not entitled.", + "description": "forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed.", "headers": { "Cache-Control": { "required": true, @@ -7155,7 +7248,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or no live connection.", + "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, @@ -7191,7 +7284,7 @@ "required": true, "schema": { "enum": [ - "PUT" + "POST" ], "type": "string" } @@ -7206,7 +7299,7 @@ } }, "413": { - "description": "payload_too_large; federation bodies are at most 16 KiB.", + "description": "payload_too_large; request bodies are at most 4 KiB.", "headers": { "Cache-Control": { "schema": { @@ -7255,7 +7348,7 @@ } }, "500": { - "description": "internal_error without provider, query, identity or submitted-value diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -7276,28 +7369,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable: the provider, egress fetcher or storage could not decide; nothing unconfirmed is reported as applied.", - "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 stale revision, a pending operation inside its quiet window or a racing first configuration; business_rule_violation for a lifecycle state the operation does not admit or a changed issuer or entity identifier.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -7320,29 +7392,42 @@ }, "security": [ { - "TenantBearer": [] + "TenantBearer": [], + "NativeSessionSource": [] } ], "x-version-introduced": "v1" } }, - "/api/v1/identity/federation/test-starts": { + "/api/v1/identity/data-request-entry/closures": { "post": { "tags": [ - "Federation" + "DataRequestEntry" ], - "description": "ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited.", - "operationId": "StartFederationTest", + "description": "The subject files the closure of their whole account from one retained group, its originating group (ADR-0106 \u00A7 3, \u00A7 9; ADR-0107 \u00A7 7): the path of a Suspended person and of one whose Membership was revoked. An account closure ends the person\u0027s account in every tenant and organization where they hold a Membership, not only in this group. The request is scheduled with its execution time 24 hours after it is filed and holds the frozen snapshot of the subject\u0027s Memberships of any status in the group. No job is queued: an operator confirms the request with the person and Begins it at or after its execution time, and the person can cancel it until that Begin commits. Once begun it is irreversible: the account stops working at once, the person\u0027s data is erased group by group, and the sign-in account is removed when an operator finalizes the closure. No in-product status remains afterwards; the person can read the receipt only while the account still works. Refused when the subject holds no Membership of any status there, while another closure of the subject is active in the group, or while a hold applies. Strict empty JSON object. MUST audited.", + "operationId": "CreateRetainedAccountClosure", "parameters": [ { - "name": "If-Match", + "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": "One canonical strong quoted decimal connection revision. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale revision is 409.", + "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": 21, - "minLength": 3, - "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "maxLength": 128, + "minLength": 8, + "pattern": "^[!-~]{8,128}$", "type": "string" } } @@ -7358,8 +7443,8 @@ "required": true }, "responses": { - "200": { - "description": "Settled operation receipt.", + "202": { + "description": "Accepted: the request\u0027s initial resource, scheduled. No job runs it: an operator may Begin it from its executeAt, and until that Begin commits it can be cancelled. Read the group\u0027s requests for its status while the account still works.", "headers": { "Cache-Control": { "required": true, @@ -7369,18 +7454,58 @@ ], "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/FederationOperationResponse" + "$ref": "#/components/schemas/AccountClosureAcceptedResponse" } } } }, "400": { - "description": "validation_failed for malformed or noncanonical input, an unexpected body or query, an invalid precondition, or a refused egress address.", + "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 lockey_request_already_active (another closure of the person is still active in the group), lockey_blocked_hold, or lockey_subject_not_admitted (the person\u0027s account is closing or closed: nothing is filed); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", "headers": { "Cache-Control": { "required": true, @@ -7401,7 +7526,7 @@ } }, "401": { - "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", + "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, @@ -7431,7 +7556,7 @@ } }, "403": { - "description": "forbidden without current Tenant identity.federation.admin in an orgless context; feature_disabled when the protocol is not entitled.", + "description": "forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed.", "headers": { "Cache-Control": { "required": true, @@ -7452,7 +7577,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or no live connection.", + "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, @@ -7503,7 +7628,7 @@ } }, "413": { - "description": "payload_too_large; federation bodies are at most 16 KiB.", + "description": "payload_too_large; request bodies are at most 4 KiB.", "headers": { "Cache-Control": { "schema": { @@ -7552,7 +7677,7 @@ } }, "500": { - "description": "internal_error without provider, query, identity or submitted-value diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -7573,28 +7698,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable: the provider, egress fetcher or storage could not decide; nothing unconfirmed is reported as applied.", - "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 stale revision, a pending operation inside its quiet window or a racing first configuration; business_rule_violation for a lifecycle state the operation does not admit or a changed issuer or entity identifier.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -7617,24 +7721,49 @@ }, "security": [ { - "TenantBearer": [] + "TenantBearer": [], + "NativeSessionSource": [] } ], "x-version-introduced": "v1" } }, - "/api/v1/identity/federation/test-results": { + "/api/v1/identity/data-request-entry/cancellations": { "post": { "tags": [ - "Federation" + "DataRequestEntry" ], - "description": "ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited. The access token must also carry the optional federation.test_record client scope, which only the BFF\u0027s federation_test authorization requests; an ordinary sign-in or Studio token is refused with 403 before the body is read.", - "operationId": "RecordFederationTestResult", + "description": "The subject cancels their own request in one retained group: a requested export (requested to cancelled), or a scheduled erasure before its execution time (scheduled to cancelled). Strict JSON object with requestId only. MUST audited. A scheduled closure is cancelled the same way (scheduled to cancelled) until an operator\u0027s Begin commits, also after its execution time; a begun closure is fulfilling and cannot be cancelled.", + "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 connection revision. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale revision is 409.", + "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, @@ -7648,7 +7777,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/FederationTestResultInput" + "$ref": "#/components/schemas/RetainedDataRequestTargetInput" } } }, @@ -7656,7 +7785,7 @@ }, "responses": { "200": { - "description": "Settled operation receipt.", + "description": "Committed receipt, or the retained receipt of a completed exact-key replay.", "headers": { "Cache-Control": { "required": true, @@ -7666,18 +7795,58 @@ ], "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/FederationOperationResponse" + "$ref": "#/components/schemas/AdministrationVersionReceipt" } } } }, "400": { - "description": "validation_failed for malformed or noncanonical input, an unexpected body or query, an invalid precondition, or a refused egress address.", + "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 with errors.$ carrying lockey_data_request_window_ended (an erasure\u0027s cancellable window has ended and it runs now) or lockey_data_request_not_cancellable (the request is no longer one a cancellation admits: it already ended, or an export already started); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state. A closure is never window_ended: its not_cancellable means an operator\u0027s Begin committed, after which the closure is irreversible.", "headers": { "Cache-Control": { "required": true, @@ -7698,7 +7867,7 @@ } }, "401": { - "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", + "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, @@ -7728,7 +7897,7 @@ } }, "403": { - "description": "forbidden without current Tenant identity.federation.admin in an orgless context, or when the access token lacks the federation.test_record scope; feature_disabled when the protocol is not entitled.", + "description": "forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed.", "headers": { "Cache-Control": { "required": true, @@ -7749,7 +7918,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or no live connection.", + "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, @@ -7800,7 +7969,7 @@ } }, "413": { - "description": "payload_too_large; federation bodies are at most 16 KiB.", + "description": "payload_too_large; request bodies are at most 4 KiB.", "headers": { "Cache-Control": { "schema": { @@ -7849,7 +8018,7 @@ } }, "500": { - "description": "internal_error without provider, query, identity or submitted-value diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -7870,28 +8039,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable: the provider, egress fetcher or storage could not decide; nothing unconfirmed is reported as applied.", - "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 stale revision, a pending operation inside its quiet window or a racing first configuration; business_rule_violation for a lifecycle state the operation does not admit or a changed issuer or entity identifier.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -7914,24 +8062,49 @@ }, "security": [ { - "TenantBearer": [] + "TenantBearer": [], + "NativeSessionSource": [] } ], "x-version-introduced": "v1" } }, - "/api/v1/identity/federation/activation": { + "/api/v1/identity/data-request-entry/revocations": { "post": { "tags": [ - "Federation" + "DataRequestEntry" ], - "description": "ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited.", - "operationId": "ActivateFederation", + "description": "The subject revokes an unexpired available artifact of their own request in one retained group, which deletes its chunks at once; the metadata stays as the receipt (ADR-0107 \u00A7 4). If-Match carries the ARTIFACT version: the receipt\u0027s artifact.version, not the request\u0027s. Strict JSON object with requestId only. MUST audited.", + "operationId": "RevokeRetainedDataExport", "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 connection revision. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale revision 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, @@ -7945,7 +8118,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/EmptyAdministrationInput" + "$ref": "#/components/schemas/RetainedDataRequestTargetInput" } } }, @@ -7953,7 +8126,7 @@ }, "responses": { "200": { - "description": "Settled operation receipt.", + "description": "Committed receipt, or the retained receipt of a completed exact-key replay.", "headers": { "Cache-Control": { "required": true, @@ -7963,18 +8136,58 @@ ], "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/FederationOperationResponse" + "$ref": "#/components/schemas/AdministrationVersionReceipt" } } } }, "400": { - "description": "validation_failed for malformed or noncanonical input, an unexpected body or query, an invalid precondition, or a refused egress address.", + "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 artifact 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, @@ -7995,7 +8208,7 @@ } }, "401": { - "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", + "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, @@ -8025,7 +8238,7 @@ } }, "403": { - "description": "forbidden without current Tenant identity.federation.admin in an orgless context; feature_disabled when the protocol is not entitled.", + "description": "forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed.", "headers": { "Cache-Control": { "required": true, @@ -8046,7 +8259,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or no live connection.", + "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, @@ -8097,7 +8310,7 @@ } }, "413": { - "description": "payload_too_large; federation bodies are at most 16 KiB.", + "description": "payload_too_large; request bodies are at most 4 KiB.", "headers": { "Cache-Control": { "schema": { @@ -8146,7 +8359,7 @@ } }, "500": { - "description": "internal_error without provider, query, identity or submitted-value diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -8167,28 +8380,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable: the provider, egress fetcher or storage could not decide; nothing unconfirmed is reported as applied.", - "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 stale revision, a pending operation inside its quiet window or a racing first configuration; business_rule_violation for a lifecycle state the operation does not admit or a changed issuer or entity identifier.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -8211,29 +8403,30 @@ }, "security": [ { - "TenantBearer": [] + "TenantBearer": [], + "NativeSessionSource": [] } ], "x-version-introduced": "v1" } }, - "/api/v1/identity/federation/disablement": { + "/api/v1/identity/data-request-entry/tickets": { "post": { "tags": [ - "Federation" + "DataRequestEntry" ], - "description": "ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited.", - "operationId": "DisableFederation", + "description": "The subject mints a 15-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": "If-Match", - "in": "header", - "description": "One canonical strong quoted decimal connection revision. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale revision is 409.", + "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": 21, - "minLength": 3, - "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "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" } } @@ -8242,7 +8435,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/EmptyAdministrationInput" + "$ref": "#/components/schemas/RetainedDataRequestTargetInput" } } }, @@ -8250,7 +8443,7 @@ }, "responses": { "200": { - "description": "Settled operation receipt.", + "description": "The opaque ticket, returned exactly once and never replayed, with the expiry and the chunks it authorizes.", "headers": { "Cache-Control": { "required": true, @@ -8265,13 +8458,13 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/FederationOperationResponse" + "$ref": "#/components/schemas/DataExportTicketResponse" } } } }, "400": { - "description": "validation_failed for malformed or noncanonical input, an unexpected body or query, an invalid precondition, or a refused egress address.", + "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, @@ -8292,7 +8485,7 @@ } }, "401": { - "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", + "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, @@ -8322,7 +8515,7 @@ } }, "403": { - "description": "forbidden without current Tenant identity.federation.admin in an orgless context; feature_disabled when the protocol is not entitled.", + "description": "forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed.", "headers": { "Cache-Control": { "required": true, @@ -8343,7 +8536,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or no live connection.", + "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 gone (revoked, expired, purged, or sealed under a key the export key ring no longer holds) and only a new export helps; with data_export_ticket_limit, a ticket bound is reached (see the mint\u0027s 409).", "headers": { "Cache-Control": { "required": true, @@ -8394,7 +8587,7 @@ } }, "413": { - "description": "payload_too_large; federation bodies are at most 16 KiB.", + "description": "payload_too_large; request bodies are at most 4 KiB.", "headers": { "Cache-Control": { "schema": { @@ -8443,7 +8636,7 @@ } }, "500": { - "description": "internal_error without provider, query, identity or submitted-value diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -8464,7 +8657,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable: the provider, egress fetcher or storage could not decide; nothing unconfirmed is reported as applied.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -8485,7 +8678,7 @@ } }, "409": { - "description": "concurrency_conflict for a stale revision, a pending operation inside its quiet window or a racing first configuration; business_rule_violation for a lifecycle state the operation does not admit or a changed issuer or entity identifier.", + "description": "business_rule_violation. errors.artifact carries data_export_unavailable when the request has no available, unexpired artifact or the key it was sealed under is no longer in the export key ring: the artifact is gone and only a new export helps. It carries data_export_ticket_limit when a ticket bound is reached: this session already holds 3 unconsumed, unexpired tickets over the artifact (wait until one is consumed by its final chunk or expires, 15 minutes after it was minted; a ticket of an earlier, refreshed credential does not count), or 20 tickets have been minted over the artifact in all, which is final: file a new export.", "headers": { "Cache-Control": { "required": true, @@ -8508,29 +8701,30 @@ }, "security": [ { - "TenantBearer": [] + "TenantBearer": [], + "NativeSessionSource": [] } ], "x-version-introduced": "v1" } }, - "/api/v1/identity/federation/enablement": { + "/api/v1/identity/data-request-entry/chunks": { "post": { "tags": [ - "Federation" + "DataRequestEntry" ], - "description": "ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited.", - "operationId": "EnableFederation", + "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": "If-Match", - "in": "header", - "description": "One canonical strong quoted decimal connection revision. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale revision is 409.", + "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": 21, - "minLength": 3, - "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "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" } } @@ -8539,7 +8733,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/EmptyAdministrationInput" + "$ref": "#/components/schemas/RetainedDataExportChunkInput" } } }, @@ -8547,7 +8741,7 @@ }, "responses": { "200": { - "description": "Settled operation receipt.", + "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, @@ -8562,13 +8756,13 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/FederationOperationResponse" + "$ref": "#/components/schemas/DataExportChunkResponse" } } } }, "400": { - "description": "validation_failed for malformed or noncanonical input, an unexpected body or query, an invalid precondition, or a refused egress address.", + "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, @@ -8589,7 +8783,7 @@ } }, "401": { - "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", + "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, @@ -8619,7 +8813,7 @@ } }, "403": { - "description": "forbidden without current Tenant identity.federation.admin in an orgless context; feature_disabled when the protocol is not entitled.", + "description": "forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed.", "headers": { "Cache-Control": { "required": true, @@ -8640,7 +8834,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or no live connection.", + "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 gone (revoked, expired, purged, or sealed under a key the export key ring no longer holds) and only a new export helps; with data_export_ticket_limit, a ticket bound is reached (see the mint\u0027s 409).", "headers": { "Cache-Control": { "required": true, @@ -8691,7 +8885,7 @@ } }, "413": { - "description": "payload_too_large; federation bodies are at most 16 KiB.", + "description": "payload_too_large; request bodies are at most 4 KiB.", "headers": { "Cache-Control": { "schema": { @@ -8740,7 +8934,7 @@ } }, "500": { - "description": "internal_error without provider, query, identity or submitted-value diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -8761,28 +8955,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable: the provider, egress fetcher or storage could not decide; nothing unconfirmed is reported as applied.", - "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 stale revision, a pending operation inside its quiet window or a racing first configuration; business_rule_violation for a lifecycle state the operation does not admit or a changed issuer or entity identifier.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -8805,29 +8978,30 @@ }, "security": [ { - "TenantBearer": [] + "TenantBearer": [], + "NativeSessionSource": [] } ], "x-version-introduced": "v1" } }, - "/api/v1/identity/federation/deletion": { + "/api/v1/identity/me/data-requests/exports": { "post": { "tags": [ - "Federation" + "OwnDataRequests" ], - "description": "ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited.", - "operationId": "DeleteFederation", + "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. When it completes, it revokes the subject\u0027s previous available artifact in the group, whoever filed that one. Strict empty JSON object. MUST audited.", + "operationId": "CreateOwnDataExport", "parameters": [ { - "name": "If-Match", + "name": "Idempotency-Key", "in": "header", - "description": "One canonical strong quoted decimal connection revision. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale revision is 409.", + "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": 21, - "minLength": 3, - "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "maxLength": 128, + "minLength": 8, + "pattern": "^[!-~]{8,128}$", "type": "string" } } @@ -8843,8 +9017,8 @@ "required": true }, "responses": { - "200": { - "description": "Settled operation receipt.", + "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, @@ -8854,18 +9028,66 @@ ], "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/FederationOperationResponse" + "$ref": "#/components/schemas/DataRequestAcceptedResponse" } } } }, "400": { - "description": "validation_failed for malformed or noncanonical input, an unexpected body or query, an invalid precondition, or a refused egress address.", + "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 lockey_request_already_active (a request of this kind is still active in the group), lockey_blocked_hold, or lockey_subject_not_admitted (the person\u0027s account is closing or closed: nothing is filed); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", "headers": { "Cache-Control": { "required": true, @@ -8916,7 +9138,7 @@ } }, "403": { - "description": "forbidden without current Tenant identity.federation.admin in an orgless context; feature_disabled when the protocol is not entitled.", + "description": "forbidden when the request carries no live session the ticket can bind.", "headers": { "Cache-Control": { "required": true, @@ -8937,7 +9159,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or no live connection.", + "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, @@ -8988,7 +9210,7 @@ } }, "413": { - "description": "payload_too_large; federation bodies are at most 16 KiB.", + "description": "payload_too_large; request bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -9037,7 +9259,7 @@ } }, "500": { - "description": "internal_error without provider, query, identity or submitted-value diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -9058,28 +9280,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable: the provider, egress fetcher or storage could not decide; nothing unconfirmed is reported as applied.", - "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 stale revision, a pending operation inside its quiet window or a racing first configuration; business_rule_violation for a lifecycle state the operation does not admit or a changed issuer or entity identifier.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -9108,23 +9309,23 @@ "x-version-introduced": "v1" } }, - "/api/v1/identity/federation/resumption": { + "/api/v1/identity/me/data-requests/erasures": { "post": { "tags": [ - "Federation" + "OwnDataRequests" ], - "description": "ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited.", - "operationId": "ResumeFederationOperation", + "description": "The subject files an erasure of their own data in the session\u0027s group (ADR-0106 \u00A7 3; ADR-0107 \u00A7 5). Requires an Active Membership in exactly that group; no permission key. The request is scheduled, holds the frozen snapshot of the subject\u0027s Memberships of any status in the group, and its job is submitted on the same transaction, due when the 24-hour cancellable window ends. The job then revokes the subject\u0027s export artifacts in the group, removes the Membership\u0027s role assignments, clears its profile, leaves it as a Revoked tombstone and revokes the pending invitations the subject issued there; the request then awaits the operator\u0027s privileged step. Refused while the subject is the tenant\u0027s only eligible tenant-wide administrator (tenant-wide group) or while a hold applies. Strict empty JSON object. MUST audited.", + "operationId": "CreateOwnDataErasure", "parameters": [ { - "name": "If-Match", + "name": "Idempotency-Key", "in": "header", - "description": "One canonical strong quoted decimal connection revision. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale revision is 409.", + "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": 21, - "minLength": 3, - "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "maxLength": 128, + "minLength": 8, + "pattern": "^[!-~]{8,128}$", "type": "string" } } @@ -9140,8 +9341,8 @@ "required": true }, "responses": { - "200": { - "description": "Settled operation receipt.", + "202": { + "description": "Accepted: the request\u0027s initial resource, scheduled. Its erasure runs as a background job once its 24-hour cancellable window ends; read the Location for its status.", "headers": { "Cache-Control": { "required": true, @@ -9151,18 +9352,66 @@ ], "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/FederationOperationResponse" + "$ref": "#/components/schemas/DataErasureAcceptedResponse" } } } }, "400": { - "description": "validation_failed for malformed or noncanonical input, an unexpected body or query, an invalid precondition, or a refused egress address.", + "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 lockey_request_already_active (an erasure is still active in the group), lockey_blocked_last_administrator (the person is the tenant\u0027s only eligible tenant-wide administrator; another must be appointed first), lockey_blocked_hold, or lockey_subject_not_admitted (the person\u0027s account is closing or closed: nothing is filed); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", "headers": { "Cache-Control": { "required": true, @@ -9213,7 +9462,7 @@ } }, "403": { - "description": "forbidden without current Tenant identity.federation.admin in an orgless context; feature_disabled when the protocol is not entitled.", + "description": "forbidden when the request carries no live session the ticket can bind.", "headers": { "Cache-Control": { "required": true, @@ -9234,7 +9483,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or no live connection.", + "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, @@ -9285,7 +9534,7 @@ } }, "413": { - "description": "payload_too_large; federation bodies are at most 16 KiB.", + "description": "payload_too_large; request bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -9334,7 +9583,7 @@ } }, "500": { - "description": "internal_error without provider, query, identity or submitted-value diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -9355,28 +9604,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable: the provider, egress fetcher or storage could not decide; nothing unconfirmed is reported as applied.", - "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 stale revision, a pending operation inside its quiet window or a racing first configuration; business_rule_violation for a lifecycle state the operation does not admit or a changed issuer or entity identifier.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -9405,26 +9633,40 @@ "x-version-introduced": "v1" } }, - "/api/v1/identity/invitation-entry/inspections": { + "/api/v1/identity/me/data-requests/closures": { "post": { "tags": [ - "InvitationEntry" + "OwnDataRequests" + ], + "description": "The subject files the closure of their whole account from the session\u0027s group, its originating group (ADR-0106 \u00A7 3; ADR-0107 \u00A7 7). Only the person files one; no administrator can file, read or cancel a closure. Requires an Active Membership in exactly that group; no permission key. An account closure ends the person\u0027s account in every tenant and organization where they hold a Membership, not only in this group. The request is scheduled with its execution time 24 hours after it is filed and holds the frozen snapshot of the subject\u0027s Memberships of any status in the group. No job is queued: an operator confirms the request with the person and Begins it at or after its execution time, and the person can cancel it until that Begin commits. Once begun it is irreversible: the account stops working at once, the person\u0027s data is erased group by group, and the sign-in account is removed when an operator finalizes the closure. No in-product status remains afterwards; the person can read the receipt only while the account still works. Refused while another closure of the subject is active in the group or while a hold applies. Strict empty JSON object. MUST audited.", + "operationId": "CreateOwnAccountClosure", + "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" + } + } ], - "description": "Exact native recipient entry. Strict UTF-8 application/json object, at most 8 KiB, with invitationId and code only. Unknown, repeated and missing fields, query, generic Idempotency-Key and irrelevant conditional headers refuse. Current stock-validated token, installed binding, trusted native source and real host are independently required; no caller scope selectors. No-store and no session/grant publication. Pending inspection and first acceptance each observe current verified provider email. Accepted acceptance preflight selects the Off original-result read before Pending-only If-Match, provider I/O or mutation intents. Unknown commit outcomes require explicit original-result reconciliation; never automatically retry.", - "operationId": "InspectInvitation", "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/InvitationEntryInput" + "$ref": "#/components/schemas/EmptyAdministrationInput" } } }, "required": true }, "responses": { - "200": { - "description": "Successful current projection or retained committed receipt.", + "202": { + "description": "Accepted: the request\u0027s initial resource, scheduled. No job runs it: an operator may Begin it from its executeAt, and until that Begin commits it can be cancelled. Read the Location for its status while the account still works.", "headers": { "Cache-Control": { "required": true, @@ -9436,6 +9678,7 @@ } }, "ETag": { + "description": "The request\u0027s version.", "required": true, "schema": { "maxLength": 21, @@ -9443,18 +9686,56 @@ "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/InvitationInspectionResponse" + "$ref": "#/components/schemas/AccountClosureAcceptedResponse" } } } }, "400": { - "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "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 lockey_request_already_active (another closure of the person is still active in the group), lockey_blocked_hold, or lockey_subject_not_admitted (the person\u0027s account is closing or closed: nothing is filed); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", "headers": { "Cache-Control": { "required": true, @@ -9475,7 +9756,7 @@ } }, "401": { - "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -9505,7 +9786,7 @@ } }, "403": { - "description": "forbidden for live coverage without current operation or target disclosure capability.", + "description": "forbidden when the request carries no live session the ticket can bind.", "headers": { "Cache-Control": { "required": true, @@ -9526,7 +9807,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "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, @@ -9577,10 +9858,9 @@ } }, "413": { - "description": "payload_too_large; entry body maximum is 8 KiB.", + "description": "payload_too_large; request bodies are at most 16 KiB.", "headers": { "Cache-Control": { - "required": true, "schema": { "enum": [ "no-store" @@ -9627,7 +9907,7 @@ } }, "500": { - "description": "internal_error without provider, query, identity or submitted-value diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -9648,28 +9928,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", - "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 changed Pending generation/version/effect classification, a Suspended exact membership, or a lost acceptance race. Explicit original-result recovery is separate.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -9692,46 +9951,46 @@ }, "security": [ { - "TenantBearer": [], - "NativeSessionSource": [] + "TenantBearer": [] } ], "x-version-introduced": "v1" } }, - "/api/v1/identity/invitation-entry/acceptances": { - "post": { + "/api/v1/identity/me/data-requests": { + "get": { "tags": [ - "InvitationEntry" + "OwnDataRequests" ], - "description": "Exact native recipient entry. Strict UTF-8 application/json object, at most 8 KiB, with invitationId and code only. Unknown, repeated and missing fields, query, generic Idempotency-Key and irrelevant conditional headers refuse. Current stock-validated token, installed binding, trusted native source and real host are independently required; no caller scope selectors. No-store and no session/grant publication. Pending inspection and first acceptance each observe current verified provider email. Accepted acceptance preflight selects the Off original-result read before Pending-only If-Match, provider I/O or mutation intents. Unknown commit outcomes require explicit original-result reconciliation; never automatically retry.", - "operationId": "AcceptInvitation", + "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": "If-Match", - "in": "header", - "description": "Required for Pending acceptance only: one canonical strong quoted decimal observed version. Accepted preflight ignores this Pending precondition and selects original-result recovery. Inspection/result reject If-Match. No body version.", + "name": "cursor", + "in": "query", + "description": "Opaque canonical current-actor/group/operation-bound cursor. Unknown, repeated, blank and oversized values refuse.", "schema": { - "maxLength": 21, - "minLength": 3, - "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "maxLength": 1024, + "minLength": 1, "type": "string" } + }, + { + "name": "limit", + "in": "query", + "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, + "type": "integer", + "format": "int32", + "default": 20 + } } ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InvitationEntryInput" - } - } - }, - "required": true - }, "responses": { "200": { - "description": "Successful current projection or retained committed receipt.", + "description": "Current receipt-safe projection: status and counts, never content.", "headers": { "Cache-Control": { "required": true, @@ -9741,27 +10000,18 @@ ], "type": "string" } - }, - "ETag": { - "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/InvitationAcceptanceResponse" + "$ref": "#/components/schemas/OwnDataRequestPage" } } } }, "400": { - "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "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, @@ -9782,7 +10032,7 @@ } }, "401": { - "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -9812,7 +10062,7 @@ } }, "403": { - "description": "forbidden for live coverage without current operation or target disclosure capability.", + "description": "forbidden when the request carries no live session the ticket can bind.", "headers": { "Cache-Control": { "required": true, @@ -9833,7 +10083,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "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, @@ -9869,7 +10119,7 @@ "required": true, "schema": { "enum": [ - "POST" + "GET" ], "type": "string" } @@ -9884,10 +10134,9 @@ } }, "413": { - "description": "payload_too_large; entry body maximum is 8 KiB.", + "description": "payload_too_large; request bodies are at most 16 KiB.", "headers": { "Cache-Control": { - "required": true, "schema": { "enum": [ "no-store" @@ -9934,7 +10183,7 @@ } }, "500": { - "description": "internal_error without provider, query, identity or submitted-value diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -9955,28 +10204,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", - "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 changed Pending generation/version/effect classification, a Suspended exact membership, or a lost acceptance race. Explicit original-result recovery is separate.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -9999,33 +10227,35 @@ }, "security": [ { - "TenantBearer": [], - "NativeSessionSource": [] + "TenantBearer": [] } ], "x-version-introduced": "v1" } }, - "/api/v1/identity/invitation-entry/results": { - "post": { + "/api/v1/identity/me/data-requests/{id}": { + "get": { "tags": [ - "InvitationEntry" + "OwnDataRequests" ], - "description": "Exact native recipient entry. Strict UTF-8 application/json object, at most 8 KiB, with invitationId and code only. Unknown, repeated and missing fields, query, generic Idempotency-Key and irrelevant conditional headers refuse. Current stock-validated token, installed binding, trusted native source and real host are independently required; no caller scope selectors. No-store and no session/grant publication. Pending inspection and first acceptance each observe current verified provider email. Accepted acceptance preflight selects the Off original-result read before Pending-only If-Match, provider I/O or mutation intents. Unknown commit outcomes require explicit original-result reconciliation; never automatically retry.", - "operationId": "GetOwnInvitationResult", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/InvitationEntryInput" - } + "description": "The subject\u0027s own request receipt: identity, kind, origin, status, timestamps, the recorded refusal or failure code, the closed retained-reference kinds with their counts (the list is partial: a kind absent from it is not counted, which is not zero) 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" } - }, - "required": true - }, + } + ], "responses": { "200": { - "description": "Successful current projection or retained committed receipt.", + "description": "Current receipt-safe projection: status and counts, never content.", "headers": { "Cache-Control": { "required": true, @@ -10037,6 +10267,7 @@ } }, "ETag": { + "description": "The request\u0027s version.", "required": true, "schema": { "maxLength": 21, @@ -10049,13 +10280,13 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/InvitationAcceptanceResponse" + "$ref": "#/components/schemas/OwnDataRequestResponse" } } } }, "400": { - "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "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, @@ -10076,7 +10307,7 @@ } }, "401": { - "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -10106,7 +10337,7 @@ } }, "403": { - "description": "forbidden for live coverage without current operation or target disclosure capability.", + "description": "forbidden when the request carries no live session the ticket can bind.", "headers": { "Cache-Control": { "required": true, @@ -10127,7 +10358,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "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, @@ -10163,7 +10394,7 @@ "required": true, "schema": { "enum": [ - "POST" + "GET" ], "type": "string" } @@ -10178,10 +10409,9 @@ } }, "413": { - "description": "payload_too_large; entry body maximum is 8 KiB.", + "description": "payload_too_large; request bodies are at most 16 KiB.", "headers": { "Cache-Control": { - "required": true, "schema": { "enum": [ "no-store" @@ -10228,7 +10458,7 @@ } }, "500": { - "description": "internal_error without provider, query, identity or submitted-value diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -10249,28 +10479,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", - "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 changed Pending generation/version/effect classification, a Suspended exact membership, or a lost acceptance race. Explicit original-result recovery is separate.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -10293,47 +10502,69 @@ }, "security": [ { - "TenantBearer": [], - "NativeSessionSource": [] + "TenantBearer": [] } ], "x-version-introduced": "v1" } }, - "/api/v1/identity/invitations": { - "get": { + "/api/v1/identity/me/data-requests/{id}/cancellations": { + "post": { "tags": [ - "Invitations" + "OwnDataRequests" ], - "description": "Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization.", - "operationId": "ListInvitations", + "description": "The subject cancels a requested export (requested to cancelled) or a scheduled erasure before its execution time (scheduled to cancelled). A request already fulfilling finishes. Strict empty JSON object. MUST audited. A scheduled closure is cancelled the same way (scheduled to cancelled) until an operator\u0027s Begin commits, also after its execution time; a begun closure is fulfilling and cannot be cancelled.", + "operationId": "CancelOwnDataRequest", "parameters": [ { - "name": "cursor", - "in": "query", - "description": "Opaque canonical current-actor/scope/operation-bound cursor. Unknown, repeated, blank and oversized values refuse.", + "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": { - "maxLength": 1024, - "minLength": 1, + "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": "limit", - "in": "query", - "description": "Canonical positive ASCII decimal Int32, default 20, accepted values above 100 clamp to 100. Signs, leading zeros and repeats refuse.", + "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": { - "maximum": 2147483647, - "minimum": 1, - "type": "integer", - "format": "int32", - "default": 20 + "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": "Successful current projection or retained committed receipt.", + "description": "Committed receipt, or the retained receipt of a completed exact-key replay.", "headers": { "Cache-Control": { "required": true, @@ -10343,18 +10574,58 @@ ], "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/InvitationPage" + "$ref": "#/components/schemas/AdministrationVersionReceipt" } } } }, "400": { - "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "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 with errors.$ carrying lockey_data_request_window_ended (an erasure\u0027s cancellable window has ended and it runs now) or lockey_data_request_not_cancellable (the request is no longer one a cancellation admits: it already ended, or an export already started); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state. A closure is never window_ended: its not_cancellable means an operator\u0027s Begin committed, after which the closure is irreversible.", "headers": { "Cache-Control": { "required": true, @@ -10375,7 +10646,7 @@ } }, "401": { - "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -10405,7 +10676,7 @@ } }, "403": { - "description": "forbidden for live coverage without current operation or target disclosure capability.", + "description": "forbidden when the request carries no live session the ticket can bind.", "headers": { "Cache-Control": { "required": true, @@ -10426,7 +10697,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "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, @@ -10462,7 +10733,7 @@ "required": true, "schema": { "enum": [ - "GET, POST" + "POST" ], "type": "string" } @@ -10477,7 +10748,7 @@ } }, "413": { - "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "description": "payload_too_large; request bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -10526,7 +10797,7 @@ } }, "500": { - "description": "internal_error without provider, query, identity or submitted-value diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -10547,7 +10818,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -10574,14 +10845,27 @@ } ], "x-version-introduced": "v1" - }, + } + }, + "/api/v1/identity/me/data-requests/{id}/artifact/revocations": { "post": { "tags": [ - "Invitations" + "OwnDataRequests" ], - "description": "Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried.", - "operationId": "CreateInvitation", + "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", @@ -10593,21 +10877,33 @@ "pattern": "^[!-~]{8,128}$", "type": "string" } + }, + { + "name": "If-Match", + "in": "header", + "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, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" + } } ], "requestBody": { "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/InvitationCreateInput" + "$ref": "#/components/schemas/EmptyAdministrationInput" } } }, "required": true }, "responses": { - "201": { - "description": "Committed creation receipt.", + "200": { + "description": "Committed receipt, or the retained receipt of a completed exact-key replay.", "headers": { "Cache-Control": { "required": true, @@ -10619,6 +10915,7 @@ } }, "ETag": { + "description": "The artifact\u0027s version after the revocation (artifact.version), not the request\u0027s.", "required": true, "schema": { "maxLength": 21, @@ -10628,21 +10925,13 @@ } }, "Idempotency-Replayed": { - "description": "Present only after fresh original-target disclosure audit on a replay.", + "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 newly created original resource.", - "required": true, - "schema": { - "pattern": "^/api/v1/identity/invitations/[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": { @@ -10654,7 +10943,7 @@ } }, "400": { - "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "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, @@ -10675,7 +10964,7 @@ } }, "409": { - "description": "concurrency_conflict for a valid stale version; business_rule_violation for refused lifecycle/last-admin/last-organization rules; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", + "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, @@ -10696,7 +10985,7 @@ } }, "401": { - "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -10726,7 +11015,7 @@ } }, "403": { - "description": "forbidden for live coverage without current operation or target disclosure capability.", + "description": "forbidden when the request carries no live session the ticket can bind.", "headers": { "Cache-Control": { "required": true, @@ -10747,7 +11036,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "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, @@ -10783,7 +11072,7 @@ "required": true, "schema": { "enum": [ - "GET, POST" + "POST" ], "type": "string" } @@ -10798,7 +11087,7 @@ } }, "413": { - "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "description": "payload_too_large; request bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -10847,7 +11136,7 @@ } }, "500": { - "description": "internal_error without provider, query, identity or submitted-value diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -10868,7 +11157,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -10897,18 +11186,18 @@ "x-version-introduced": "v1" } }, - "/api/v1/identity/invitations/{id}": { - "get": { + "/api/v1/identity/me/data-requests/{id}/artifact/tickets": { + "post": { "tags": [ - "Invitations" + "OwnDataExportTickets" ], - "description": "Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization.", - "operationId": "GetInvitation", + "description": "The subject mints a 15-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 nonreserved RFC UUIDv7. Another scope never supplies target authority.", + "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}$", @@ -10917,9 +11206,19 @@ } } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmptyAdministrationInput" + } + } + }, + "required": true + }, "responses": { "200": { - "description": "Successful current projection or retained committed receipt.", + "description": "The opaque ticket, returned exactly once and never replayed, with the expiry and the chunks it authorizes.", "headers": { "Cache-Control": { "required": true, @@ -10929,27 +11228,18 @@ ], "type": "string" } - }, - "ETag": { - "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/InvitationResponse" + "$ref": "#/components/schemas/DataExportTicketResponse" } } } }, "400": { - "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "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, @@ -10970,7 +11260,7 @@ } }, "401": { - "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -11000,7 +11290,7 @@ } }, "403": { - "description": "forbidden for live coverage without current operation or target disclosure capability.", + "description": "forbidden when the request carries no live session the ticket can bind.", "headers": { "Cache-Control": { "required": true, @@ -11021,7 +11311,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "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 gone (revoked, expired, purged, or sealed under a key the export key ring no longer holds) and only a new export helps; with data_export_ticket_limit, a ticket bound is reached (see the mint\u0027s 409).", "headers": { "Cache-Control": { "required": true, @@ -11057,7 +11347,7 @@ "required": true, "schema": { "enum": [ - "GET" + "POST" ], "type": "string" } @@ -11072,7 +11362,7 @@ } }, "413": { - "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "description": "payload_too_large; request bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -11121,7 +11411,7 @@ } }, "500": { - "description": "internal_error without provider, query, identity or submitted-value diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -11142,7 +11432,28 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", + "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 or the key it was sealed under is no longer in the export key ring: the artifact is gone and only a new export helps. It carries data_export_ticket_limit when a ticket bound is reached: this session already holds 3 unconsumed, unexpired tickets over the artifact (wait until one is consumed by its final chunk or expires, 15 minutes after it was minted; a ticket of an earlier, refreshed credential does not count), or 20 tickets have been minted over the artifact in all, which is final: file a new export.", "headers": { "Cache-Control": { "required": true, @@ -11171,55 +11482,31 @@ "x-version-introduced": "v1" } }, - "/api/v1/identity/invitations/{id}/revocations": { + "/api/v1/identity/me/data-requests/{id}/artifact/chunks": { "post": { "tags": [ - "Invitations" + "OwnDataExportChunks" ], - "description": "Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried.", - "operationId": "RevokeInvitation", + "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 nonreserved RFC UUIDv7. Another scope never supplies target authority.", + "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 aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version.", - "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" + "$ref": "#/components/schemas/DataExportChunkInput" } } }, @@ -11227,7 +11514,7 @@ }, "responses": { "200": { - "description": "Successful current projection or retained committed receipt.", + "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, @@ -11237,57 +11524,18 @@ ], "type": "string" } - }, - "ETag": { - "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-target disclosure audit on a replay.", - "schema": { - "enum": [ - "true" - ], - "type": "string" - } } }, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AdministrationVersionReceipt" + "$ref": "#/components/schemas/DataExportChunkResponse" } } } }, "400": { - "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", - "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 refused lifecycle/last-admin/last-organization rules; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", + "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, @@ -11308,7 +11556,7 @@ } }, "401": { - "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -11338,7 +11586,7 @@ } }, "403": { - "description": "forbidden for live coverage without current operation or target disclosure capability.", + "description": "forbidden when the request carries no live session the ticket can bind.", "headers": { "Cache-Control": { "required": true, @@ -11359,7 +11607,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "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 gone (revoked, expired, purged, or sealed under a key the export key ring no longer holds) and only a new export helps; with data_export_ticket_limit, a ticket bound is reached (see the mint\u0027s 409).", "headers": { "Cache-Control": { "required": true, @@ -11410,7 +11658,7 @@ } }, "413": { - "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "description": "payload_too_large; request bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -11459,7 +11707,7 @@ } }, "500": { - "description": "internal_error without provider, query, identity or submitted-value diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -11480,7 +11728,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -11509,25 +11757,14 @@ "x-version-introduced": "v1" } }, - "/api/v1/identity/invitations/{id}/reissues": { + "/api/v1/identity/data-requests/exports": { "post": { "tags": [ - "Invitations" + "DataRequests" ], - "description": "Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried.", - "operationId": "ReissueInvitation", + "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. Refused while the person holds a readable artifact in the group, of any origin, because the new export would revoke it. The administrator sees status and counts only and never receives the bundle. Strict JSON object with membershipId only. MUST audited.", + "operationId": "CreateDataExportForSubject", "parameters": [ - { - "name": "id", - "in": "path", - "description": "Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority.", - "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", @@ -11539,33 +11776,21 @@ "pattern": "^[!-~]{8,128}$", "type": "string" } - }, - { - "name": "If-Match", - "in": "header", - "description": "One canonical strong quoted decimal aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version.", - "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" + "$ref": "#/components/schemas/DataExportForSubjectInput" } } }, "required": true }, "responses": { - "200": { - "description": "Successful current projection or retained committed receipt.", + "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, @@ -11577,6 +11802,7 @@ } }, "ETag": { + "description": "The request\u0027s version.", "required": true, "schema": { "maxLength": 21, @@ -11586,25 +11812,33 @@ } }, "Idempotency-Replayed": { - "description": "Present only after fresh original-target disclosure audit on a replay.", + "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/AdministrationVersionReceipt" + "$ref": "#/components/schemas/DataRequestAcceptedResponse" } } } }, "400": { - "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "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, @@ -11625,7 +11859,7 @@ } }, "409": { - "description": "concurrency_conflict for a valid stale version; business_rule_violation for refused lifecycle/last-admin/last-organization rules; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", + "description": "business_rule_violation: errors.$ carries lockey_request_already_active (a request of this kind is still active in the group), lockey_blocked_hold, lockey_subject_export_available (the person holds a readable export artifact in the group, of any origin, which this export would revoke: it can be filed once that artifact is revoked or has expired), or lockey_subject_not_admitted (the person\u0027s account is closing or closed: nothing is filed); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", "headers": { "Cache-Control": { "required": true, @@ -11646,7 +11880,7 @@ } }, "401": { - "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -11676,7 +11910,7 @@ } }, "403": { - "description": "forbidden for live coverage without current operation or target disclosure capability.", + "description": "forbidden without current identity.membership.admin covering the context\u0027s group.", "headers": { "Cache-Control": { "required": true, @@ -11697,7 +11931,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "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, @@ -11748,7 +11982,7 @@ } }, "413": { - "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "description": "payload_too_large; request bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -11797,7 +12031,7 @@ } }, "500": { - "description": "internal_error without provider, query, identity or submitted-value diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -11818,7 +12052,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -11847,16 +12081,40 @@ "x-version-introduced": "v1" } }, - "/api/v1/identity/invitable-roles": { - "get": { + "/api/v1/identity/data-requests/erasures": { + "post": { "tags": [ - "InvitableRoles" + "DataRequests" ], - "description": "Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization.", - "operationId": "ListInvitableRoles", + "description": "An administrator holding identity.membership.admin over the group files an erasure for the person who held the named Membership in the group, only once that Membership is Revoked: an Active or Suspended member is revoked first, by the separately audited administration act (ADR-0106 \u00A7 3). Never for themselves. The request is scheduled and runs when its 24-hour window ends; the administrator who filed it may cancel it until then. Status and counts only. Strict JSON object with membershipId only. MUST audited.", + "operationId": "CreateDataErasureForSubject", + "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": { - "200": { - "description": "Successful current projection or retained committed receipt.", + "202": { + "description": "Accepted: the request\u0027s initial resource, scheduled. Its erasure runs as a background job once its 24-hour cancellable window ends; read the Location for its status.", "headers": { "Cache-Control": { "required": true, @@ -11866,18 +12124,66 @@ ], "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/InvitableRoleDirectory" + "$ref": "#/components/schemas/DataErasureAcceptedResponse" } } } }, "400": { - "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "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 lockey_request_already_active (an erasure is still active in the group), lockey_blocked_last_administrator (the person is the tenant\u0027s only eligible tenant-wide administrator; another must be appointed first), lockey_blocked_hold, lockey_subject_membership_current (the person still holds an Active or Suspended Membership in the group: revoke it first), or lockey_subject_not_admitted (the person\u0027s account is closing or closed: nothing is filed); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", "headers": { "Cache-Control": { "required": true, @@ -11898,7 +12204,7 @@ } }, "401": { - "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -11928,7 +12234,7 @@ } }, "403": { - "description": "forbidden for live coverage without current operation or target disclosure capability.", + "description": "forbidden without current identity.membership.admin covering the context\u0027s group.", "headers": { "Cache-Control": { "required": true, @@ -11949,7 +12255,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "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, @@ -11985,7 +12291,7 @@ "required": true, "schema": { "enum": [ - "GET" + "POST" ], "type": "string" } @@ -12000,7 +12306,7 @@ } }, "413": { - "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "description": "payload_too_large; request bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -12049,7 +12355,7 @@ } }, "500": { - "description": "internal_error without provider, query, identity or submitted-value diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -12070,7 +12376,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -12099,35 +12405,41 @@ "x-version-introduced": "v1" } }, - "/api/v1/identity/memberships/{id}/custom-fields": { + "/api/v1/identity/data-requests": { "get": { "tags": [ - "MembershipCustomFields" + "DataRequests" ], - "description": "Fresh exact scoped projection. No body; only the declared query keys. No-store. Own consent history remains available through retained scope without an Active Membership; it never authorizes a grant or profile write.", - "operationId": "GetMembershipCustomFields", + "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": "id", - "in": "path", - "required": true, + "name": "cursor", + "in": "query", + "description": "Opaque canonical current-actor/group/operation-bound cursor. Unknown, repeated, blank and oversized values refuse.", "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" + "maxLength": 1024, + "minLength": 1, + "type": "string" } - } - ], - "responses": { - "200": { - "description": "Authorized current projection or minimal committed receipt.", + }, + { + "name": "limit", + "in": "query", + "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, + "type": "integer", + "format": "int32", + "default": 20 + } + } + ], + "responses": { + "200": { + "description": "Current receipt-safe projection: status and counts, never content.", "headers": { - "ETag": { - "required": true, - "schema": { - "type": "string" - } - }, "Cache-Control": { "required": true, "schema": { @@ -12141,13 +12453,13 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/MembershipCustomFieldsResponse" + "$ref": "#/components/schemas/DataRequestPage" } } } }, "400": { - "description": "validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input.", + "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, @@ -12168,7 +12480,7 @@ } }, "401": { - "description": "unauthorized: invalid credentials.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -12198,7 +12510,7 @@ } }, "403": { - "description": "forbidden: no current operation authority.", + "description": "forbidden without current identity.membership.admin covering the context\u0027s group.", "headers": { "Cache-Control": { "required": true, @@ -12219,7 +12531,7 @@ } }, "404": { - "description": "not_found: foreign, missing or noncovered exact scope/target.", + "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, @@ -12240,7 +12552,7 @@ } }, "405": { - "description": "method_not_allowed after earlier admission gates.", + "description": "method_not_allowed after earlier host, credential and scope gates.", "headers": { "Cache-Control": { "required": true, @@ -12255,7 +12567,7 @@ "required": true, "schema": { "enum": [ - "GET, PATCH" + "GET" ], "type": "string" } @@ -12270,7 +12582,7 @@ } }, "413": { - "description": "payload_too_large: input over the outer byte bound.", + "description": "payload_too_large; request bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -12290,7 +12602,7 @@ } }, "429": { - "description": "rate_limited by existing admission.", + "description": "rate_limited by the existing visitor/subject admission.", "headers": { "Cache-Control": { "required": true, @@ -12319,7 +12631,7 @@ } }, "500": { - "description": "internal_error with payload-free diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -12340,7 +12652,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no unconfirmed success.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -12367,79 +12679,48 @@ } ], "x-version-introduced": "v1" - }, - "patch": { + } + }, + "/api/v1/identity/data-requests/{id}": { + "get": { "tags": [ - "MembershipCustomFields" + "DataRequests" ], - "description": "Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions.", - "operationId": "SetMembershipCustomFields", + "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" } - }, - { - "name": "Idempotency-Key", - "in": "header", - "required": true, - "schema": { - "maxLength": 128, - "minLength": 8, - "pattern": "^[!-~]{8,128}$", - "type": "string" - } - }, - { - "name": "If-Match", - "in": "header", - "required": true, - "schema": { - "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", - "type": "string" - } } ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/MembershipCustomFieldPatch" - } - } - }, - "required": true - }, "responses": { "200": { - "description": "Authorized current projection or minimal committed receipt.", + "description": "Current receipt-safe projection: status and counts, never content.", "headers": { - "ETag": { + "Cache-Control": { "required": true, - "schema": { - "type": "string" - } - }, - "Idempotency-Replayed": { "schema": { "enum": [ - "true" + "no-store" ], "type": "string" } }, - "Cache-Control": { + "ETag": { + "description": "The request\u0027s version.", "required": true, "schema": { - "enum": [ - "no-store" - ], + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", "type": "string" } } @@ -12447,34 +12728,13 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CustomFieldReceiptResponse" + "$ref": "#/components/schemas/DataRequestResponse" } } } }, "400": { - "description": "validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input.", - "headers": { - "Cache-Control": { - "required": true, - "schema": { - "enum": [ - "no-store" - ], - "type": "string" - } - } - }, - "content": { - "application/problem\u002Bjson": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, - "409": { - "description": "concurrency_conflict, business_rule_violation, limit_exceeded, request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable; no automatic retry.", + "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, @@ -12495,7 +12755,7 @@ } }, "401": { - "description": "unauthorized: invalid credentials.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -12525,7 +12785,7 @@ } }, "403": { - "description": "forbidden: no current operation authority.", + "description": "forbidden without current identity.membership.admin covering the context\u0027s group.", "headers": { "Cache-Control": { "required": true, @@ -12546,7 +12806,7 @@ } }, "404": { - "description": "not_found: foreign, missing or noncovered exact scope/target.", + "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, @@ -12567,7 +12827,7 @@ } }, "405": { - "description": "method_not_allowed after earlier admission gates.", + "description": "method_not_allowed after earlier host, credential and scope gates.", "headers": { "Cache-Control": { "required": true, @@ -12582,7 +12842,7 @@ "required": true, "schema": { "enum": [ - "GET, PATCH" + "GET" ], "type": "string" } @@ -12597,7 +12857,7 @@ } }, "413": { - "description": "payload_too_large: input over the outer byte bound.", + "description": "payload_too_large; request bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -12617,7 +12877,7 @@ } }, "429": { - "description": "rate_limited by existing admission.", + "description": "rate_limited by the existing visitor/subject admission.", "headers": { "Cache-Control": { "required": true, @@ -12646,7 +12906,7 @@ } }, "500": { - "description": "internal_error with payload-free diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -12667,7 +12927,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no unconfirmed success.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -12696,23 +12956,104 @@ "x-version-introduced": "v1" } }, - "/api/v1/identity/me/custom-fields": { - "get": { + "/api/v1/identity/data-requests/{id}/cancellations": { + "post": { "tags": [ - "MembershipCustomFields" + "DataRequests" ], - "description": "Fresh exact scoped projection. No body; only the declared query keys. No-store. Own consent history remains available through retained scope without an Active Membership; it never authorizes a grant or profile write.", - "operationId": "GetOwnMembershipCustomFields", + "description": "The administrator who filed a request cancels it: an export while it is still requested, an erasure before its execution time. 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": "Authorized current projection or minimal committed receipt.", + "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": { @@ -12724,15 +13065,15 @@ } }, "content": { - "application/json": { + "application/problem\u002Bjson": { "schema": { - "$ref": "#/components/schemas/MembershipCustomFieldsResponse" + "$ref": "#/components/schemas/ProblemDetails" } } } }, - "400": { - "description": "validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input.", + "409": { + "description": "concurrency_conflict for a valid stale version; business_rule_violation with errors.$ carrying lockey_data_request_window_ended (an erasure\u0027s cancellable window has ended and it runs now) or lockey_data_request_not_cancellable (the request is no longer one a cancellation admits: it already ended, or an export already started); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", "headers": { "Cache-Control": { "required": true, @@ -12753,7 +13094,7 @@ } }, "401": { - "description": "unauthorized: invalid credentials.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -12783,7 +13124,7 @@ } }, "403": { - "description": "forbidden: no current operation authority.", + "description": "forbidden without current identity.membership.admin covering the context\u0027s group.", "headers": { "Cache-Control": { "required": true, @@ -12804,7 +13145,7 @@ } }, "404": { - "description": "not_found: foreign, missing or noncovered exact scope/target.", + "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, @@ -12825,7 +13166,7 @@ } }, "405": { - "description": "method_not_allowed after earlier admission gates.", + "description": "method_not_allowed after earlier host, credential and scope gates.", "headers": { "Cache-Control": { "required": true, @@ -12840,7 +13181,7 @@ "required": true, "schema": { "enum": [ - "GET, PATCH" + "POST" ], "type": "string" } @@ -12855,7 +13196,7 @@ } }, "413": { - "description": "payload_too_large: input over the outer byte bound.", + "description": "payload_too_large; request bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -12875,7 +13216,7 @@ } }, "429": { - "description": "rate_limited by existing admission.", + "description": "rate_limited by the existing visitor/subject admission.", "headers": { "Cache-Control": { "required": true, @@ -12904,7 +13245,7 @@ } }, "500": { - "description": "internal_error with payload-free diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -12925,7 +13266,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no unconfirmed success.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -12952,17 +13293,31 @@ } ], "x-version-introduced": "v1" - }, - "patch": { + } + }, + "/api/v1/identity/data-requests/{id}/artifact/revocations": { + "post": { "tags": [ - "MembershipCustomFields" + "DataRequests" ], - "description": "Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions.", - "operationId": "SetOwnMembershipCustomFields", + "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, @@ -12974,8 +13329,11 @@ { "name": "If-Match", "in": "header", + "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, + "minLength": 3, "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", "type": "string" } @@ -12985,7 +13343,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/MembershipCustomFieldPatch" + "$ref": "#/components/schemas/EmptyAdministrationInput" } } }, @@ -12993,27 +13351,32 @@ }, "responses": { "200": { - "description": "Authorized current projection or minimal committed receipt.", + "description": "Committed receipt, or the retained receipt of a completed exact-key replay.", "headers": { - "ETag": { + "Cache-Control": { "required": true, "schema": { + "enum": [ + "no-store" + ], "type": "string" } }, - "Idempotency-Replayed": { + "ETag": { + "description": "The artifact\u0027s version after the revocation (artifact.version), not the request\u0027s.", + "required": true, "schema": { - "enum": [ - "true" - ], + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", "type": "string" } }, - "Cache-Control": { - "required": true, + "Idempotency-Replayed": { + "description": "Present only after fresh original-request disclosure on a replay.", "schema": { "enum": [ - "no-store" + "true" ], "type": "string" } @@ -13022,13 +13385,13 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CustomFieldReceiptResponse" + "$ref": "#/components/schemas/AdministrationVersionReceipt" } } } }, "400": { - "description": "validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input.", + "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, @@ -13049,7 +13412,7 @@ } }, "409": { - "description": "concurrency_conflict, business_rule_violation, limit_exceeded, request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable; no automatic retry.", + "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, @@ -13070,7 +13433,7 @@ } }, "401": { - "description": "unauthorized: invalid credentials.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -13100,7 +13463,7 @@ } }, "403": { - "description": "forbidden: no current operation authority.", + "description": "forbidden without current identity.membership.admin covering the context\u0027s group.", "headers": { "Cache-Control": { "required": true, @@ -13121,7 +13484,7 @@ } }, "404": { - "description": "not_found: foreign, missing or noncovered exact scope/target.", + "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, @@ -13142,7 +13505,7 @@ } }, "405": { - "description": "method_not_allowed after earlier admission gates.", + "description": "method_not_allowed after earlier host, credential and scope gates.", "headers": { "Cache-Control": { "required": true, @@ -13157,7 +13520,7 @@ "required": true, "schema": { "enum": [ - "GET, PATCH" + "POST" ], "type": "string" } @@ -13172,7 +13535,7 @@ } }, "413": { - "description": "payload_too_large: input over the outer byte bound.", + "description": "payload_too_large; request bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -13192,7 +13555,7 @@ } }, "429": { - "description": "rate_limited by existing admission.", + "description": "rate_limited by the existing visitor/subject admission.", "headers": { "Cache-Control": { "required": true, @@ -13221,7 +13584,7 @@ } }, "500": { - "description": "internal_error with payload-free diagnostics.", + "description": "internal_error without provider, query, identity, ticket or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -13242,7 +13605,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no unconfirmed success.", + "description": "dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant\u0027s identity fence behind another person\u0027s running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header).", "headers": { "Cache-Control": { "required": true, @@ -13271,40 +13634,16 @@ "x-version-introduced": "v1" } }, - "/api/v1/identity/memberships": { + "/api/v1/identity/federation": { "get": { "tags": [ - "Memberships" - ], - "description": "Tenant administrative membership directory requiring current Tenant identity.membership.admin. Rechecks live membership, lifecycle and capability for every page; accepts HostAndClaim, confirmed ClaimAndMembership (including a legacy platform host), or independently verified HostAndNativeSessionScope on a real Tenant/Organization host. Returns only membership/user/organization identifiers, status, contextual displayName and preferredLocale. Active/Suspended undeleted memberships only, ordered by membership UUID. No search, sorting, editing, provider data, grants or global profile. No-store; the MUST ReadSensitive audit row commits before any result is disclosed. The closed native listMemberships caller retains the same live page authority and MUST ReadSensitive audit; native transport grants no additional authority.", - "operationId": "ListMemberships", - "parameters": [ - { - "name": "cursor", - "in": "query", - "description": "Opaque canonical continuation bound to the actor, tenant, organization and operation; obtain it from pageInfo.nextCursor. Every page reauthorizes.", - "schema": { - "maxLength": 1024, - "minLength": 1, - "type": "string" - } - }, - { - "name": "limit", - "in": "query", - "description": "Positive page size, default 20; values above 100 are clamped to 100. Repeated, empty or unknown query parameters are refused.", - "schema": { - "maximum": 2147483647, - "minimum": 1, - "type": "integer", - "format": "int32", - "default": 20 - } - } + "Federation" ], + "description": "Current tenant\u0027s nonsecret federation connection in an orgless context, under Tenant identity.federation.admin. Audit Off: no personal data. One provider readback under the request deadline; a definitive drift or an expired test window is recorded as a MUST apply outcome. No request body or query. No-store.", + "operationId": "GetFederationConnection", "responses": { "200": { - "description": "OK", + "description": "Current nonsecret connection detail, or a null connection.", "headers": { "Cache-Control": { "required": true, @@ -13314,18 +13653,27 @@ ], "type": "string" } + }, + "ETag": { + "description": "The connection revision, present exactly when a live connection exists.", + "schema": { + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" + } } }, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PageOfMembershipDirectoryItem" + "$ref": "#/components/schemas/FederationConnectionResponse" } } } }, "400": { - "description": "validation_failed for noncanonical/replayed/oversized cursors, invalid limit or unknown/repeated/empty query parameters; malformed assertion headers are also refused.", + "description": "validation_failed for malformed or noncanonical input, an unexpected body or query, an invalid precondition, or a refused egress address.", "headers": { "Cache-Control": { "required": true, @@ -13346,7 +13694,7 @@ } }, "401": { - "description": "unauthorized for present invalid or undecidable credentials on known hosts, including existing-binding failure; bare Bearer challenge without provider details.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -13376,7 +13724,7 @@ } }, "403": { - "description": "forbidden for confirmed coverage without the current Tenant administrative capability; no directory lookup or disclosure.", + "description": "forbidden without current Tenant identity.federation.admin in an orgless context; feature_disabled when the protocol is not entitled.", "headers": { "Cache-Control": { "required": true, @@ -13397,7 +13745,7 @@ } }, "404": { - "description": "not_found for absent credentials, noncoverage or untrusted scope; tenant_mismatch for host/claim or header disagreement. Assertions do not select authority.", + "description": "not_found for missing credentials, noncoverage or no live connection.", "headers": { "Cache-Control": { "required": true, @@ -13418,7 +13766,7 @@ } }, "405": { - "description": "method_not_allowed from routing after earlier credential, resolution and surface gates; GET only.", + "description": "method_not_allowed after earlier host, credential and scope gates.", "headers": { "Cache-Control": { "required": true, @@ -13448,7 +13796,7 @@ } }, "413": { - "description": "payload_too_large from the existing decoded body bound; outer Kestrel framing refusals may omit application policy.", + "description": "payload_too_large; federation bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -13468,7 +13816,7 @@ } }, "429": { - "description": "rate_limited from visitor/subject admission or subject-registry capacity.", + "description": "rate_limited by the existing visitor/subject admission.", "headers": { "Cache-Control": { "required": true, @@ -13497,7 +13845,7 @@ } }, "500": { - "description": "internal_error for unexpected failures, without exception/query details.", + "description": "internal_error without provider, query, identity or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -13518,7 +13866,7 @@ } }, "503": { - "description": "dependency_unavailable for live membership/lifecycle storage, auxiliary admission or sticky subject-registry cleanup fault; audit_unavailable when the mandatory sensitive-read row cannot commit. No membership payload is disclosed.", + "description": "dependency_unavailable or audit_unavailable: the provider, egress fetcher or storage could not decide; nothing unconfirmed is reported as applied.", "headers": { "Cache-Control": { "required": true, @@ -13528,14 +13876,6 @@ ], "type": "string" } - }, - "Retry-After": { - "description": "Suggested dependency retry delay in seconds; not a recovery guarantee.", - "required": true, - "schema": { - "minimum": 0, - "type": "integer" - } } }, "content": { @@ -13555,29 +13895,39 @@ "x-version-introduced": "v1" } }, - "/api/v1/identity/memberships/{id}": { - "get": { + "/api/v1/identity/federation/configuration": { + "put": { "tags": [ - "Memberships" + "Federation" ], - "description": "Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization.", - "operationId": "GetMembershipDetail", + "description": "ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited.", + "operationId": "ConfigureFederation", "parameters": [ { - "name": "id", - "in": "path", - "description": "Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority.", - "required": true, + "name": "If-Match", + "in": "header", + "description": "Absent only to create the tenant\u0027s first live connection; otherwise one canonical strong quoted decimal connection revision. A stale revision or an existing live connection is 409.", "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" + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" } } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FederationConfigurationInput" + } + } + }, + "required": true + }, "responses": { "200": { - "description": "Successful current projection or retained committed receipt.", + "description": "Settled operation receipt.", "headers": { "Cache-Control": { "required": true, @@ -13587,27 +13937,18 @@ ], "type": "string" } - }, - "ETag": { - "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/MembershipDetailResponse" + "$ref": "#/components/schemas/FederationOperationResponse" } } } }, "400": { - "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "description": "validation_failed for malformed or noncanonical input, an unexpected body or query, an invalid precondition, or a refused egress address.", "headers": { "Cache-Control": { "required": true, @@ -13628,7 +13969,7 @@ } }, "401": { - "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -13658,7 +13999,7 @@ } }, "403": { - "description": "forbidden for live coverage without current operation or target disclosure capability.", + "description": "forbidden without current Tenant identity.federation.admin in an orgless context; feature_disabled when the protocol is not entitled.", "headers": { "Cache-Control": { "required": true, @@ -13679,7 +14020,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "description": "not_found for missing credentials, noncoverage or no live connection.", "headers": { "Cache-Control": { "required": true, @@ -13715,7 +14056,7 @@ "required": true, "schema": { "enum": [ - "GET" + "PUT" ], "type": "string" } @@ -13730,7 +14071,7 @@ } }, "413": { - "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "description": "payload_too_large; federation bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -13800,7 +14141,28 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "description": "dependency_unavailable or audit_unavailable: the provider, egress fetcher or storage could not decide; nothing unconfirmed is reported as applied.", + "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 stale revision, a pending operation inside its quiet window or a racing first configuration; business_rule_violation for a lifecycle state the operation does not admit or a changed issuer or entity identifier.", "headers": { "Cache-Control": { "required": true, @@ -13829,41 +14191,18 @@ "x-version-introduced": "v1" } }, - "/api/v1/identity/memberships/{id}/profile": { - "put": { + "/api/v1/identity/federation/secret-rotations": { + "post": { "tags": [ - "Memberships" + "Federation" ], - "description": "Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried.", - "operationId": "SetMembershipProfile", + "description": "ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited.", + "operationId": "RotateFederationSecret", "parameters": [ - { - "name": "id", - "in": "path", - "description": "Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority.", - "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 aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version.", + "description": "One canonical strong quoted decimal connection revision. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale revision is 409.", "required": true, "schema": { "maxLength": 21, @@ -13877,7 +14216,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/MembershipProfileInput" + "$ref": "#/components/schemas/FederationSecretInput" } } }, @@ -13885,7 +14224,7 @@ }, "responses": { "200": { - "description": "Successful current projection or retained committed receipt.", + "description": "Settled operation receipt.", "headers": { "Cache-Control": { "required": true, @@ -13895,36 +14234,18 @@ ], "type": "string" } - }, - "ETag": { - "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-target disclosure audit on a replay.", - "schema": { - "enum": [ - "true" - ], - "type": "string" - } } }, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AdministrationVersionReceipt" + "$ref": "#/components/schemas/FederationOperationResponse" } } } }, "400": { - "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "description": "validation_failed for malformed or noncanonical input, an unexpected body or query, an invalid precondition, or a refused egress address.", "headers": { "Cache-Control": { "required": true, @@ -13944,29 +14265,8 @@ } } }, - "409": { - "description": "concurrency_conflict for a valid stale version; business_rule_violation for refused lifecycle/last-admin/last-organization rules; 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.", + "401": { + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -13996,7 +14296,7 @@ } }, "403": { - "description": "forbidden for live coverage without current operation or target disclosure capability.", + "description": "forbidden without current Tenant identity.federation.admin in an orgless context; feature_disabled when the protocol is not entitled.", "headers": { "Cache-Control": { "required": true, @@ -14017,7 +14317,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "description": "not_found for missing credentials, noncoverage or no live connection.", "headers": { "Cache-Control": { "required": true, @@ -14053,7 +14353,7 @@ "required": true, "schema": { "enum": [ - "PUT" + "POST" ], "type": "string" } @@ -14068,7 +14368,7 @@ } }, "413": { - "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "description": "payload_too_large; federation bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -14138,7 +14438,28 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "description": "dependency_unavailable or audit_unavailable: the provider, egress fetcher or storage could not decide; nothing unconfirmed is reported as applied.", + "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 stale revision, a pending operation inside its quiet window or a racing first configuration; business_rule_violation for a lifecycle state the operation does not admit or a changed issuer or entity identifier.", "headers": { "Cache-Control": { "required": true, @@ -14167,41 +14488,18 @@ "x-version-introduced": "v1" } }, - "/api/v1/identity/memberships/{id}/role-assignments": { + "/api/v1/identity/federation/display-name": { "put": { "tags": [ - "Memberships" + "Federation" ], - "description": "Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried.", - "operationId": "ReplaceMembershipRoleAssignments", + "description": "ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited.", + "operationId": "RenameFederation", "parameters": [ - { - "name": "id", - "in": "path", - "description": "Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority.", - "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 aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version.", + "description": "One canonical strong quoted decimal connection revision. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale revision is 409.", "required": true, "schema": { "maxLength": 21, @@ -14215,7 +14513,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/MembershipRolesInput" + "$ref": "#/components/schemas/FederationDisplayNameInput" } } }, @@ -14223,7 +14521,7 @@ }, "responses": { "200": { - "description": "Successful current projection or retained committed receipt.", + "description": "Settled operation receipt.", "headers": { "Cache-Control": { "required": true, @@ -14233,57 +14531,18 @@ ], "type": "string" } - }, - "ETag": { - "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-target disclosure audit on a replay.", - "schema": { - "enum": [ - "true" - ], - "type": "string" - } } }, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AdministrationVersionReceipt" + "$ref": "#/components/schemas/FederationOperationResponse" } } } }, "400": { - "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", - "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 refused lifecycle/last-admin/last-organization rules; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", + "description": "validation_failed for malformed or noncanonical input, an unexpected body or query, an invalid precondition, or a refused egress address.", "headers": { "Cache-Control": { "required": true, @@ -14304,7 +14563,7 @@ } }, "401": { - "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -14334,7 +14593,7 @@ } }, "403": { - "description": "forbidden for live coverage without current operation or target disclosure capability.", + "description": "forbidden without current Tenant identity.federation.admin in an orgless context; feature_disabled when the protocol is not entitled.", "headers": { "Cache-Control": { "required": true, @@ -14355,7 +14614,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "description": "not_found for missing credentials, noncoverage or no live connection.", "headers": { "Cache-Control": { "required": true, @@ -14406,7 +14665,7 @@ } }, "413": { - "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "description": "payload_too_large; federation bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -14476,7 +14735,28 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "description": "dependency_unavailable or audit_unavailable: the provider, egress fetcher or storage could not decide; nothing unconfirmed is reported as applied.", + "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 stale revision, a pending operation inside its quiet window or a racing first configuration; business_rule_violation for a lifecycle state the operation does not admit or a changed issuer or entity identifier.", "headers": { "Cache-Control": { "required": true, @@ -14505,41 +14785,18 @@ "x-version-introduced": "v1" } }, - "/api/v1/identity/memberships/{id}/status": { - "put": { + "/api/v1/identity/federation/test-starts": { + "post": { "tags": [ - "Memberships" + "Federation" ], - "description": "Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried.", - "operationId": "ChangeMembershipStatus", + "description": "ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited.", + "operationId": "StartFederationTest", "parameters": [ - { - "name": "id", - "in": "path", - "description": "Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority.", - "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 aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version.", + "description": "One canonical strong quoted decimal connection revision. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale revision is 409.", "required": true, "schema": { "maxLength": 21, @@ -14553,7 +14810,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/MembershipStatusInput" + "$ref": "#/components/schemas/EmptyAdministrationInput" } } }, @@ -14561,7 +14818,7 @@ }, "responses": { "200": { - "description": "Successful current projection or retained committed receipt.", + "description": "Settled operation receipt.", "headers": { "Cache-Control": { "required": true, @@ -14571,57 +14828,18 @@ ], "type": "string" } - }, - "ETag": { - "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-target disclosure audit on a replay.", - "schema": { - "enum": [ - "true" - ], - "type": "string" - } } }, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AdministrationVersionReceipt" + "$ref": "#/components/schemas/FederationOperationResponse" } } } }, "400": { - "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", - "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 refused lifecycle/last-admin/last-organization rules; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", + "description": "validation_failed for malformed or noncanonical input, an unexpected body or query, an invalid precondition, or a refused egress address.", "headers": { "Cache-Control": { "required": true, @@ -14642,7 +14860,7 @@ } }, "401": { - "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -14672,7 +14890,7 @@ } }, "403": { - "description": "forbidden for live coverage without current operation or target disclosure capability.", + "description": "forbidden without current Tenant identity.federation.admin in an orgless context; feature_disabled when the protocol is not entitled.", "headers": { "Cache-Control": { "required": true, @@ -14693,7 +14911,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "description": "not_found for missing credentials, noncoverage or no live connection.", "headers": { "Cache-Control": { "required": true, @@ -14729,7 +14947,7 @@ "required": true, "schema": { "enum": [ - "PUT" + "POST" ], "type": "string" } @@ -14744,7 +14962,7 @@ } }, "413": { - "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "description": "payload_too_large; federation bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -14814,7 +15032,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "description": "dependency_unavailable or audit_unavailable: the provider, egress fetcher or storage could not decide; nothing unconfirmed is reported as applied.", "headers": { "Cache-Control": { "required": true, @@ -14833,7 +15051,28 @@ } } } - } + }, + "409": { + "description": "concurrency_conflict for a stale revision, a pending operation inside its quiet window or a racing first configuration; business_rule_violation for a lifecycle state the operation does not admit or a changed issuer or entity identifier.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } }, "security": [ { @@ -14843,31 +15082,24 @@ "x-version-introduced": "v1" } }, - "/api/v1/identity/session-scope/admissions": { + "/api/v1/identity/federation/test-results": { "post": { "tags": [ - "NativeSessionAdmission" + "Federation" ], - "description": "Explicit initial selection or scope switch only. Requires a current native source, real host ceiling and live stored-actor membership/lifecycle. The central MUST security event names the admitted Membership and commits before an association witness is returned. This proves API admission, never cookie delivery. Ordinary refresh uses Off self/AccountSite reads and does not invoke this POST. No query or Idempotency-Key; empty JSON object only.", - "operationId": "AdmitNativeSessionScope", + "description": "ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited. The access token must also carry the optional federation.test_record client scope, which only the BFF\u0027s federation_test authorization requests; an ordinary sign-in or Studio token is refused with 403 before the body is read.", + "operationId": "RecordFederationTestResult", "parameters": [ { - "name": "X-LearnStack-Native-Tenant-Id", + "name": "If-Match", "in": "header", - "description": "Canonical lower-case nonempty tenant UUID candidate, verified against the real host and live membership.", + "description": "One canonical strong quoted decimal connection revision. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale revision is 409.", "required": true, "schema": { - "type": "string", - "format": "uuid" - } - }, - { - "name": "X-LearnStack-Native-Organization-Id", - "in": "header", - "description": "Optional canonical lower-case nonempty organization UUID candidate. Provider scope and legacy assertions, when present, must agree exactly.", - "schema": { - "type": "string", - "format": "uuid" + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" } } ], @@ -14875,9 +15107,7 @@ "content": { "application/json": { "schema": { - "maxProperties": 0, - "type": "object", - "additionalProperties": false + "$ref": "#/components/schemas/FederationTestResultInput" } } }, @@ -14885,7 +15115,7 @@ }, "responses": { "200": { - "description": "Successful bounded projection.", + "description": "Settled operation receipt.", "headers": { "Cache-Control": { "required": true, @@ -14900,13 +15130,13 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/NativeSessionScopeAdmission" + "$ref": "#/components/schemas/FederationOperationResponse" } } } }, "400": { - "description": "validation_failed for malformed or repeated native selectors/assertions, unexpected query/body or Idempotency-Key.", + "description": "validation_failed for malformed or noncanonical input, an unexpected body or query, an invalid precondition, or a refused egress address.", "headers": { "Cache-Control": { "required": true, @@ -14927,7 +15157,7 @@ } }, "401": { - "description": "unauthorized for invalid/expired native source, undecidable bearer or terminal/conflicting self binding; bare Bearer challenge.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -14956,8 +15186,29 @@ } } }, + "403": { + "description": "forbidden without current Tenant identity.federation.admin in an orgless context, or when the access token lacks the federation.test_record scope; feature_disabled when the protocol is not entitled.", + "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 missing native source/credentials, unknown/platform host, noncoverage or host/scope disagreement.", + "description": "not_found for missing credentials, noncoverage or no live connection.", "headers": { "Cache-Control": { "required": true, @@ -14978,7 +15229,7 @@ } }, "405": { - "description": "method_not_allowed after earlier host, credential and native-source gates.", + "description": "method_not_allowed after earlier host, credential and scope gates.", "headers": { "Cache-Control": { "required": true, @@ -15008,7 +15259,7 @@ } }, "413": { - "description": "payload_too_large from the existing decoded body bound; outer Kestrel refusals may omit application headers.", + "description": "payload_too_large; federation bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -15028,7 +15279,7 @@ } }, "429": { - "description": "rate_limited from visitor/subject admission; bootstrap can also exhaust the shared authority creation-attempt windows.", + "description": "rate_limited by the existing visitor/subject admission.", "headers": { "Cache-Control": { "required": true, @@ -15057,7 +15308,7 @@ } }, "500": { - "description": "internal_error without provider, query or credential details.", + "description": "internal_error without provider, query, identity or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -15078,7 +15329,28 @@ } }, "503": { - "description": "dependency_unavailable for binding/lifecycle/audit storage, unknown COMMIT, permanent creation capacity or cleanup fault. No association/result payload is disclosed.", + "description": "dependency_unavailable or audit_unavailable: the provider, egress fetcher or storage could not decide; nothing unconfirmed is reported as applied.", + "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 stale revision, a pending operation inside its quiet window or a racing first configuration; business_rule_violation for a lifecycle state the operation does not admit or a changed issuer or entity identifier.", "headers": { "Cache-Control": { "required": true, @@ -15101,47 +15373,46 @@ }, "security": [ { - "TenantBearer": [], - "NativeSessionSource": [] + "TenantBearer": [] } ], "x-version-introduced": "v1" } }, - "/api/v1/identity/organization-memberships": { - "get": { + "/api/v1/identity/federation/activation": { + "post": { "tags": [ - "OrganizationMemberships" + "Federation" ], - "description": "Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization.", - "operationId": "ListOrganizationMemberships", + "description": "ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited.", + "operationId": "ActivateFederation", "parameters": [ { - "name": "cursor", - "in": "query", - "description": "Opaque canonical current-actor/scope/operation-bound cursor. Unknown, repeated, blank and oversized values refuse.", + "name": "If-Match", + "in": "header", + "description": "One canonical strong quoted decimal connection revision. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale revision is 409.", + "required": true, "schema": { - "maxLength": 1024, - "minLength": 1, + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", "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 - } } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmptyAdministrationInput" + } + } + }, + "required": true + }, "responses": { "200": { - "description": "OK", + "description": "Settled operation receipt.", "headers": { "Cache-Control": { "required": true, @@ -15156,13 +15427,13 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/PageOfMembershipDirectoryItem" + "$ref": "#/components/schemas/FederationOperationResponse" } } } }, "400": { - "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "description": "validation_failed for malformed or noncanonical input, an unexpected body or query, an invalid precondition, or a refused egress address.", "headers": { "Cache-Control": { "required": true, @@ -15183,7 +15454,7 @@ } }, "401": { - "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -15213,7 +15484,7 @@ } }, "403": { - "description": "forbidden for live coverage without current operation or target disclosure capability.", + "description": "forbidden without current Tenant identity.federation.admin in an orgless context; feature_disabled when the protocol is not entitled.", "headers": { "Cache-Control": { "required": true, @@ -15234,7 +15505,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "description": "not_found for missing credentials, noncoverage or no live connection.", "headers": { "Cache-Control": { "required": true, @@ -15270,7 +15541,7 @@ "required": true, "schema": { "enum": [ - "GET" + "POST" ], "type": "string" } @@ -15285,7 +15556,7 @@ } }, "413": { - "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "description": "payload_too_large; federation bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -15355,7 +15626,28 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "description": "dependency_unavailable or audit_unavailable: the provider, egress fetcher or storage could not decide; nothing unconfirmed is reported as applied.", + "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 stale revision, a pending operation inside its quiet window or a racing first configuration; business_rule_violation for a lifecycle state the operation does not admit or a changed issuer or entity identifier.", "headers": { "Cache-Control": { "required": true, @@ -15384,16 +15676,40 @@ "x-version-introduced": "v1" } }, - "/api/v1/identity/me/profile": { - "get": { + "/api/v1/identity/federation/disablement": { + "post": { "tags": [ - "OwnMembership" + "Federation" ], - "description": "Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization.", - "operationId": "GetOwnMembershipProfile", + "description": "ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited.", + "operationId": "DisableFederation", + "parameters": [ + { + "name": "If-Match", + "in": "header", + "description": "One canonical strong quoted decimal connection revision. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale revision 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": "Successful current projection or retained committed receipt.", + "description": "Settled operation receipt.", "headers": { "Cache-Control": { "required": true, @@ -15403,27 +15719,18 @@ ], "type": "string" } - }, - "ETag": { - "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/OwnMembershipProfileResponse" + "$ref": "#/components/schemas/FederationOperationResponse" } } } }, "400": { - "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "description": "validation_failed for malformed or noncanonical input, an unexpected body or query, an invalid precondition, or a refused egress address.", "headers": { "Cache-Control": { "required": true, @@ -15444,7 +15751,7 @@ } }, "401": { - "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -15474,7 +15781,7 @@ } }, "403": { - "description": "forbidden for live coverage without current operation or target disclosure capability.", + "description": "forbidden without current Tenant identity.federation.admin in an orgless context; feature_disabled when the protocol is not entitled.", "headers": { "Cache-Control": { "required": true, @@ -15495,7 +15802,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "description": "not_found for missing credentials, noncoverage or no live connection.", "headers": { "Cache-Control": { "required": true, @@ -15531,7 +15838,7 @@ "required": true, "schema": { "enum": [ - "GET, PUT" + "POST" ], "type": "string" } @@ -15546,7 +15853,7 @@ } }, "413": { - "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "description": "payload_too_large; federation bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -15616,7 +15923,28 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "description": "dependency_unavailable or audit_unavailable: the provider, egress fetcher or storage could not decide; nothing unconfirmed is reported as applied.", + "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 stale revision, a pending operation inside its quiet window or a racing first configuration; business_rule_violation for a lifecycle state the operation does not admit or a changed issuer or entity identifier.", "headers": { "Cache-Control": { "required": true, @@ -15643,30 +15971,20 @@ } ], "x-version-introduced": "v1" - }, - "put": { + } + }, + "/api/v1/identity/federation/enablement": { + "post": { "tags": [ - "OwnMembership" + "Federation" ], - "description": "Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried.", - "operationId": "SetOwnMembershipProfile", + "description": "ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited.", + "operationId": "EnableFederation", "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" - } - }, { "name": "If-Match", "in": "header", - "description": "One canonical strong quoted decimal aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version.", + "description": "One canonical strong quoted decimal connection revision. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale revision is 409.", "required": true, "schema": { "maxLength": 21, @@ -15680,7 +15998,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/MembershipProfileInput" + "$ref": "#/components/schemas/EmptyAdministrationInput" } } }, @@ -15688,7 +16006,7 @@ }, "responses": { "200": { - "description": "Successful current projection or retained committed receipt.", + "description": "Settled operation receipt.", "headers": { "Cache-Control": { "required": true, @@ -15698,57 +16016,18 @@ ], "type": "string" } - }, - "ETag": { - "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-target disclosure audit on a replay.", - "schema": { - "enum": [ - "true" - ], - "type": "string" - } } }, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AdministrationVersionReceipt" + "$ref": "#/components/schemas/FederationOperationResponse" } } } }, "400": { - "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", - "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 refused lifecycle/last-admin/last-organization rules; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", + "description": "validation_failed for malformed or noncanonical input, an unexpected body or query, an invalid precondition, or a refused egress address.", "headers": { "Cache-Control": { "required": true, @@ -15769,7 +16048,7 @@ } }, "401": { - "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -15799,7 +16078,7 @@ } }, "403": { - "description": "forbidden for live coverage without current operation or target disclosure capability.", + "description": "forbidden without current Tenant identity.federation.admin in an orgless context; feature_disabled when the protocol is not entitled.", "headers": { "Cache-Control": { "required": true, @@ -15820,7 +16099,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "description": "not_found for missing credentials, noncoverage or no live connection.", "headers": { "Cache-Control": { "required": true, @@ -15856,7 +16135,7 @@ "required": true, "schema": { "enum": [ - "GET, PUT" + "POST" ], "type": "string" } @@ -15871,7 +16150,7 @@ } }, "413": { - "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "description": "payload_too_large; federation bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -15941,7 +16220,28 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "description": "dependency_unavailable or audit_unavailable: the provider, egress fetcher or storage could not decide; nothing unconfirmed is reported as applied.", + "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 stale revision, a pending operation inside its quiet window or a racing first configuration; business_rule_violation for a lifecycle state the operation does not admit or a changed issuer or entity identifier.", "headers": { "Cache-Control": { "required": true, @@ -15970,40 +16270,40 @@ "x-version-introduced": "v1" } }, - "/api/v1/identity/me/contexts": { - "get": { + "/api/v1/identity/federation/deletion": { + "post": { "tags": [ - "OwnMembership" + "Federation" ], - "description": "Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization.", - "operationId": "ListOwnMembershipContexts", + "description": "ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited.", + "operationId": "DeleteFederation", "parameters": [ { - "name": "cursor", - "in": "query", - "description": "Opaque canonical current-actor/scope/operation-bound cursor. Unknown, repeated, blank and oversized values refuse.", + "name": "If-Match", + "in": "header", + "description": "One canonical strong quoted decimal connection revision. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale revision is 409.", + "required": true, "schema": { - "maxLength": 1024, - "minLength": 1, + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", "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 - } } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/EmptyAdministrationInput" + } + } + }, + "required": true + }, "responses": { "200": { - "description": "Successful current projection or retained committed receipt.", + "description": "Settled operation receipt.", "headers": { "Cache-Control": { "required": true, @@ -16018,13 +16318,13 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/OwnMembershipContextPage" + "$ref": "#/components/schemas/FederationOperationResponse" } } } }, "400": { - "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "description": "validation_failed for malformed or noncanonical input, an unexpected body or query, an invalid precondition, or a refused egress address.", "headers": { "Cache-Control": { "required": true, @@ -16045,7 +16345,7 @@ } }, "401": { - "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -16075,7 +16375,7 @@ } }, "403": { - "description": "forbidden for live coverage without current operation or target disclosure capability.", + "description": "forbidden without current Tenant identity.federation.admin in an orgless context; feature_disabled when the protocol is not entitled.", "headers": { "Cache-Control": { "required": true, @@ -16096,7 +16396,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "description": "not_found for missing credentials, noncoverage or no live connection.", "headers": { "Cache-Control": { "required": true, @@ -16132,7 +16432,7 @@ "required": true, "schema": { "enum": [ - "GET" + "POST" ], "type": "string" } @@ -16147,7 +16447,7 @@ } }, "413": { - "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "description": "payload_too_large; federation bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -16217,7 +16517,28 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "description": "dependency_unavailable or audit_unavailable: the provider, egress fetcher or storage could not decide; nothing unconfirmed is reported as applied.", + "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 stale revision, a pending operation inside its quiet window or a racing first configuration; business_rule_violation for a lifecycle state the operation does not admit or a changed issuer or entity identifier.", "headers": { "Cache-Control": { "required": true, @@ -16246,16 +16567,40 @@ "x-version-introduced": "v1" } }, - "/api/v1/identity/me/capabilities": { - "get": { + "/api/v1/identity/federation/resumption": { + "post": { "tags": [ - "OwnMembership" + "Federation" ], - "description": "Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization.", - "operationId": "GetOwnCapabilities", + "description": "ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited.", + "operationId": "ResumeFederationOperation", + "parameters": [ + { + "name": "If-Match", + "in": "header", + "description": "One canonical strong quoted decimal connection revision. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale revision 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": "Successful current projection or retained committed receipt.", + "description": "Settled operation receipt.", "headers": { "Cache-Control": { "required": true, @@ -16270,13 +16615,13 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/OwnCapabilitiesDto" + "$ref": "#/components/schemas/FederationOperationResponse" } } } }, "400": { - "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "description": "validation_failed for malformed or noncanonical input, an unexpected body or query, an invalid precondition, or a refused egress address.", "headers": { "Cache-Control": { "required": true, @@ -16297,7 +16642,7 @@ } }, "401": { - "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", + "description": "unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -16327,7 +16672,7 @@ } }, "403": { - "description": "forbidden for live coverage without current operation or target disclosure capability.", + "description": "forbidden without current Tenant identity.federation.admin in an orgless context; feature_disabled when the protocol is not entitled.", "headers": { "Cache-Control": { "required": true, @@ -16348,7 +16693,7 @@ } }, "404": { - "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "description": "not_found for missing credentials, noncoverage or no live connection.", "headers": { "Cache-Control": { "required": true, @@ -16384,7 +16729,7 @@ "required": true, "schema": { "enum": [ - "GET" + "POST" ], "type": "string" } @@ -16399,7 +16744,7 @@ } }, "413": { - "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "description": "payload_too_large; federation bodies are at most 16 KiB.", "headers": { "Cache-Control": { "schema": { @@ -16469,7 +16814,28 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "description": "dependency_unavailable or audit_unavailable: the provider, egress fetcher or storage could not decide; nothing unconfirmed is reported as applied.", + "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 stale revision, a pending operation inside its quiet window or a racing first configuration; business_rule_violation for a lifecycle state the operation does not admit or a changed issuer or entity identifier.", "headers": { "Cache-Control": { "required": true, @@ -16498,25 +16864,23 @@ "x-version-introduced": "v1" } }, - "/api/v1/identity/permissions": { - "get": { + "/api/v1/identity/invitation-entry/inspections": { + "post": { "tags": [ - "Permissions" + "InvitationEntry" ], - "description": "Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization.", - "operationId": "GetPermissionRegistry", - "parameters": [ - { - "name": "sourceReleaseVersion", - "in": "query", - "description": "Current source release, default1. Source1 returns v2; source2 returns v3; source3 returns v4; no automatic adoption/grant.", - "schema": { - "maximum": 3, - "minimum": 1, - "type": "integer" + "description": "Exact native recipient entry. Strict UTF-8 application/json object, at most 8 KiB, with invitationId and code only. Unknown, repeated and missing fields, query, generic Idempotency-Key and irrelevant conditional headers refuse. Current stock-validated token, installed binding, trusted native source and real host are independently required; no caller scope selectors. No-store and no session/grant publication. Pending inspection and first acceptance each observe current verified provider email. Accepted acceptance preflight selects the Off original-result read before Pending-only If-Match, provider I/O or mutation intents. Unknown commit outcomes require explicit original-result reconciliation; never automatically retry.", + "operationId": "InspectInvitation", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvitationEntryInput" + } } - } - ], + }, + "required": true + }, "responses": { "200": { "description": "Successful current projection or retained committed receipt.", @@ -16529,12 +16893,21 @@ ], "type": "string" } + }, + "ETag": { + "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/PermissionRegistryResponse" + "$ref": "#/components/schemas/InvitationInspectionResponse" } } } @@ -16648,7 +17021,7 @@ "required": true, "schema": { "enum": [ - "GET" + "POST" ], "type": "string" } @@ -16663,9 +17036,10 @@ } }, "413": { - "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "description": "payload_too_large; entry body maximum is 8 KiB.", "headers": { "Cache-Control": { + "required": true, "schema": { "enum": [ "no-store" @@ -16752,23 +17126,68 @@ } } } + }, + "409": { + "description": "concurrency_conflict for changed Pending generation/version/effect classification, a Suspended exact membership, or a lost acceptance race. Explicit original-result recovery is separate.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } } }, "security": [ { - "TenantBearer": [] + "TenantBearer": [], + "NativeSessionSource": [] } ], "x-version-introduced": "v1" } }, - "/api/v1/identity/roles": { - "get": { + "/api/v1/identity/invitation-entry/acceptances": { + "post": { "tags": [ - "Roles" + "InvitationEntry" ], - "description": "Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization.", - "operationId": "ListRoles", + "description": "Exact native recipient entry. Strict UTF-8 application/json object, at most 8 KiB, with invitationId and code only. Unknown, repeated and missing fields, query, generic Idempotency-Key and irrelevant conditional headers refuse. Current stock-validated token, installed binding, trusted native source and real host are independently required; no caller scope selectors. No-store and no session/grant publication. Pending inspection and first acceptance each observe current verified provider email. Accepted acceptance preflight selects the Off original-result read before Pending-only If-Match, provider I/O or mutation intents. Unknown commit outcomes require explicit original-result reconciliation; never automatically retry.", + "operationId": "AcceptInvitation", + "parameters": [ + { + "name": "If-Match", + "in": "header", + "description": "Required for Pending acceptance only: one canonical strong quoted decimal observed version. Accepted preflight ignores this Pending precondition and selects original-result recovery. Inspection/result reject If-Match. No body version.", + "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/InvitationEntryInput" + } + } + }, + "required": true + }, "responses": { "200": { "description": "Successful current projection or retained committed receipt.", @@ -16781,12 +17200,21 @@ ], "type": "string" } + }, + "ETag": { + "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/RoleDirectoryResponse" + "$ref": "#/components/schemas/InvitationAcceptanceResponse" } } } @@ -16900,7 +17328,7 @@ "required": true, "schema": { "enum": [ - "GET" + "POST" ], "type": "string" } @@ -16915,9 +17343,10 @@ } }, "413": { - "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "description": "payload_too_large; entry body maximum is 8 KiB.", "headers": { "Cache-Control": { + "required": true, "schema": { "enum": [ "no-store" @@ -17004,36 +17433,55 @@ } } } + }, + "409": { + "description": "concurrency_conflict for changed Pending generation/version/effect classification, a Suspended exact membership, or a lost acceptance race. Explicit original-result recovery is separate.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } } }, "security": [ { - "TenantBearer": [] + "TenantBearer": [], + "NativeSessionSource": [] } ], "x-version-introduced": "v1" } }, - "/api/v1/identity/roles/{id}": { - "get": { + "/api/v1/identity/invitation-entry/results": { + "post": { "tags": [ - "Roles" + "InvitationEntry" ], - "description": "Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization.", - "operationId": "GetRoleDetail", - "parameters": [ - { - "name": "id", - "in": "path", - "description": "Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority.", - "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" + "description": "Exact native recipient entry. Strict UTF-8 application/json object, at most 8 KiB, with invitationId and code only. Unknown, repeated and missing fields, query, generic Idempotency-Key and irrelevant conditional headers refuse. Current stock-validated token, installed binding, trusted native source and real host are independently required; no caller scope selectors. No-store and no session/grant publication. Pending inspection and first acceptance each observe current verified provider email. Accepted acceptance preflight selects the Off original-result read before Pending-only If-Match, provider I/O or mutation intents. Unknown commit outcomes require explicit original-result reconciliation; never automatically retry.", + "operationId": "GetOwnInvitationResult", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/InvitationEntryInput" + } } - } - ], + }, + "required": true + }, "responses": { "200": { "description": "Successful current projection or retained committed receipt.", @@ -17060,7 +17508,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/RoleDetailResponse" + "$ref": "#/components/schemas/InvitationAcceptanceResponse" } } } @@ -17174,7 +17622,7 @@ "required": true, "schema": { "enum": [ - "GET" + "POST" ], "type": "string" } @@ -17189,9 +17637,10 @@ } }, "413": { - "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "description": "payload_too_large; entry body maximum is 8 KiB.", "headers": { "Cache-Control": { + "required": true, "schema": { "enum": [ "no-store" @@ -17278,70 +17727,69 @@ } } } + }, + "409": { + "description": "concurrency_conflict for changed Pending generation/version/effect classification, a Suspended exact membership, or a lost acceptance race. Explicit original-result recovery is separate.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } } }, "security": [ { - "TenantBearer": [] + "TenantBearer": [], + "NativeSessionSource": [] } ], "x-version-introduced": "v1" } }, - "/api/v1/identity/roles/{id}/grants": { - "put": { + "/api/v1/identity/invitations": { + "get": { "tags": [ - "Roles" + "Invitations" ], - "description": "Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried.", - "operationId": "ChangeRoleGrants", + "description": "Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization.", + "operationId": "ListInvitations", "parameters": [ { - "name": "id", - "in": "path", - "description": "Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority.", - "required": true, + "name": "cursor", + "in": "query", + "description": "Opaque canonical current-actor/scope/operation-bound cursor. Unknown, repeated, blank and oversized values refuse.", "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}$", + "maxLength": 1024, + "minLength": 1, "type": "string" } }, { - "name": "If-Match", - "in": "header", - "description": "One canonical strong quoted decimal aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version.", - "required": true, + "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": { - "maxLength": 21, - "minLength": 3, - "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", - "type": "string" + "maximum": 2147483647, + "minimum": 1, + "type": "integer", + "format": "int32", + "default": 20 } } ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/RoleGrantsInput" - } - } - }, - "required": true - }, "responses": { "200": { "description": "Successful current projection or retained committed receipt.", @@ -17354,30 +17802,12 @@ ], "type": "string" } - }, - "ETag": { - "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-target disclosure audit on a replay.", - "schema": { - "enum": [ - "true" - ], - "type": "string" - } } }, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AdministrationVersionReceipt" + "$ref": "#/components/schemas/InvitationPage" } } } @@ -17403,27 +17833,6 @@ } } }, - "409": { - "description": "concurrency_conflict for a valid stale version; business_rule_violation for refused lifecycle/last-admin/last-organization rules; 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": { @@ -17512,7 +17921,7 @@ "required": true, "schema": { "enum": [ - "PUT" + "GET, POST" ], "type": "string" } @@ -17624,27 +18033,14 @@ } ], "x-version-introduced": "v1" - } - }, - "/api/v1/identity/roles/{id}/manifest-adoptions": { + }, "post": { "tags": [ - "Roles" + "Invitations" ], "description": "Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried.", - "operationId": "AdoptRoleGrantManifest", + "operationId": "CreateInvitation", "parameters": [ - { - "name": "id", - "in": "path", - "description": "Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority.", - "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", @@ -17656,33 +18052,21 @@ "pattern": "^[!-~]{8,128}$", "type": "string" } - }, - { - "name": "If-Match", - "in": "header", - "description": "One canonical strong quoted decimal aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version.", - "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/RoleManifestInput" + "$ref": "#/components/schemas/InvitationCreateInput" } } }, "required": true }, "responses": { - "200": { - "description": "Successful current projection or retained committed receipt.", + "201": { + "description": "Committed creation receipt.", "headers": { "Cache-Control": { "required": true, @@ -17710,6 +18094,14 @@ ], "type": "string" } + }, + "Location": { + "description": "Exact same-API relative location of the newly created original resource.", + "required": true, + "schema": { + "pattern": "^/api/v1/identity/invitations/[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": { @@ -17850,7 +18242,7 @@ "required": true, "schema": { "enum": [ - "POST" + "GET, POST" ], "type": "string" } @@ -17964,38 +18356,29 @@ "x-version-introduced": "v1" } }, - "/api/v1/customization/custom-field-definitions": { + "/api/v1/identity/invitations/{id}": { "get": { "tags": [ - "CustomFieldDefinitions" + "Invitations" ], - "description": "Fresh exact scoped projection. No body; only the declared query keys. No-store. Own consent history remains available through retained scope without an Active Membership; it never authorizes a grant or profile write.", - "operationId": "ListCustomFieldDefinitions", + "description": "Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization.", + "operationId": "GetInvitation", "parameters": [ { - "name": "cursor", - "in": "query", - "schema": { - "maxLength": 256, - "type": "string" - } - }, - { - "name": "status", - "in": "query", + "name": "id", + "in": "path", + "description": "Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority.", + "required": true, "schema": { - "enum": [ - "Draft", - "Active", - "Deprecated" - ], - "type": "string" + "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": "Authorized current projection or minimal committed receipt.", + "description": "Successful current projection or retained committed receipt.", "headers": { "Cache-Control": { "required": true, @@ -18005,18 +18388,27 @@ ], "type": "string" } + }, + "ETag": { + "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/CustomFieldDefinitionPageResponse" + "$ref": "#/components/schemas/InvitationResponse" } } } }, "400": { - "description": "validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input.", + "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", "headers": { "Cache-Control": { "required": true, @@ -18037,7 +18429,7 @@ } }, "401": { - "description": "unauthorized: invalid credentials.", + "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -18067,7 +18459,7 @@ } }, "403": { - "description": "forbidden: no current operation authority.", + "description": "forbidden for live coverage without current operation or target disclosure capability.", "headers": { "Cache-Control": { "required": true, @@ -18088,7 +18480,7 @@ } }, "404": { - "description": "not_found: foreign, missing or noncovered exact scope/target.", + "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", "headers": { "Cache-Control": { "required": true, @@ -18109,7 +18501,7 @@ } }, "405": { - "description": "method_not_allowed after earlier admission gates.", + "description": "method_not_allowed after earlier host, credential and scope gates.", "headers": { "Cache-Control": { "required": true, @@ -18124,7 +18516,7 @@ "required": true, "schema": { "enum": [ - "GET, POST" + "GET" ], "type": "string" } @@ -18139,7 +18531,7 @@ } }, "413": { - "description": "payload_too_large: input over the outer byte bound.", + "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", "headers": { "Cache-Control": { "schema": { @@ -18159,7 +18551,7 @@ } }, "429": { - "description": "rate_limited by existing admission.", + "description": "rate_limited by the existing visitor/subject admission.", "headers": { "Cache-Control": { "required": true, @@ -18188,7 +18580,7 @@ } }, "500": { - "description": "internal_error with payload-free diagnostics.", + "description": "internal_error without provider, query, identity or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -18209,7 +18601,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no unconfirmed success.", + "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", "headers": { "Cache-Control": { "required": true, @@ -18236,17 +18628,31 @@ } ], "x-version-introduced": "v1" - }, + } + }, + "/api/v1/identity/invitations/{id}/revocations": { "post": { "tags": [ - "CustomFieldDefinitions" + "Invitations" ], - "description": "Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions.", - "operationId": "RegisterCustomFieldDefinition", + "description": "Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried.", + "operationId": "RevokeInvitation", "parameters": [ + { + "name": "id", + "in": "path", + "description": "Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority.", + "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, @@ -18254,48 +18660,57 @@ "pattern": "^[!-~]{8,128}$", "type": "string" } + }, + { + "name": "If-Match", + "in": "header", + "description": "One canonical strong quoted decimal aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version.", + "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/CustomFieldDefinitionInput" + "$ref": "#/components/schemas/EmptyAdministrationInput" } } }, "required": true }, "responses": { - "201": { - "description": "Authorized current projection or minimal committed receipt.", + "200": { + "description": "Successful current projection or retained committed receipt.", "headers": { - "ETag": { + "Cache-Control": { "required": true, - "schema": { - "type": "string" - } - }, - "Idempotency-Replayed": { "schema": { "enum": [ - "true" + "no-store" ], "type": "string" } }, - "Location": { + "ETag": { "required": true, "schema": { - "maxLength": 128, + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", "type": "string" } }, - "Cache-Control": { - "required": true, + "Idempotency-Replayed": { + "description": "Present only after fresh original-target disclosure audit on a replay.", "schema": { "enum": [ - "no-store" + "true" ], "type": "string" } @@ -18304,13 +18719,13 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CustomFieldReceiptResponse" + "$ref": "#/components/schemas/AdministrationVersionReceipt" } } } }, "400": { - "description": "validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input.", + "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", "headers": { "Cache-Control": { "required": true, @@ -18331,7 +18746,7 @@ } }, "409": { - "description": "concurrency_conflict, business_rule_violation, limit_exceeded, request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable; no automatic retry.", + "description": "concurrency_conflict for a valid stale version; business_rule_violation for refused lifecycle/last-admin/last-organization rules; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", "headers": { "Cache-Control": { "required": true, @@ -18352,7 +18767,7 @@ } }, "401": { - "description": "unauthorized: invalid credentials.", + "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -18382,7 +18797,7 @@ } }, "403": { - "description": "forbidden: no current operation authority.", + "description": "forbidden for live coverage without current operation or target disclosure capability.", "headers": { "Cache-Control": { "required": true, @@ -18403,7 +18818,7 @@ } }, "404": { - "description": "not_found: foreign, missing or noncovered exact scope/target.", + "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", "headers": { "Cache-Control": { "required": true, @@ -18424,7 +18839,7 @@ } }, "405": { - "description": "method_not_allowed after earlier admission gates.", + "description": "method_not_allowed after earlier host, credential and scope gates.", "headers": { "Cache-Control": { "required": true, @@ -18439,7 +18854,7 @@ "required": true, "schema": { "enum": [ - "GET, POST" + "POST" ], "type": "string" } @@ -18454,7 +18869,7 @@ } }, "413": { - "description": "payload_too_large: input over the outer byte bound.", + "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", "headers": { "Cache-Control": { "schema": { @@ -18474,7 +18889,7 @@ } }, "429": { - "description": "rate_limited by existing admission.", + "description": "rate_limited by the existing visitor/subject admission.", "headers": { "Cache-Control": { "required": true, @@ -18503,7 +18918,7 @@ } }, "500": { - "description": "internal_error with payload-free diagnostics.", + "description": "internal_error without provider, query, identity or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -18524,7 +18939,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no unconfirmed success.", + "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", "headers": { "Cache-Control": { "required": true, @@ -18553,35 +18968,103 @@ "x-version-introduced": "v1" } }, - "/api/v1/customization/custom-field-definitions/{id}": { - "get": { + "/api/v1/identity/invitations/{id}/reissues": { + "post": { "tags": [ - "CustomFieldDefinitions" + "Invitations" ], - "description": "Fresh exact scoped projection. No body; only the declared query keys. No-store. Own consent history remains available through retained scope without an Active Membership; it never authorizes a grant or profile write.", - "operationId": "GetCustomFieldDefinition", + "description": "Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried.", + "operationId": "ReissueInvitation", "parameters": [ { "name": "id", "in": "path", + "description": "Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority.", "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 aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version.", + "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": "Authorized current projection or minimal committed receipt.", + "description": "Successful current projection or retained committed receipt.", "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, "ETag": { "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-target disclosure audit on a replay.", + "schema": { + "enum": [ + "true" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AdministrationVersionReceipt" + } + } + } + }, + "400": { + "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "headers": { "Cache-Control": { "required": true, "schema": { @@ -18593,15 +19076,15 @@ } }, "content": { - "application/json": { + "application/problem\u002Bjson": { "schema": { - "$ref": "#/components/schemas/CustomFieldDefinitionResponse" + "$ref": "#/components/schemas/ProblemDetails" } } } }, - "400": { - "description": "validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input.", + "409": { + "description": "concurrency_conflict for a valid stale version; business_rule_violation for refused lifecycle/last-admin/last-organization rules; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", "headers": { "Cache-Control": { "required": true, @@ -18622,7 +19105,7 @@ } }, "401": { - "description": "unauthorized: invalid credentials.", + "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -18652,7 +19135,7 @@ } }, "403": { - "description": "forbidden: no current operation authority.", + "description": "forbidden for live coverage without current operation or target disclosure capability.", "headers": { "Cache-Control": { "required": true, @@ -18673,7 +19156,7 @@ } }, "404": { - "description": "not_found: foreign, missing or noncovered exact scope/target.", + "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", "headers": { "Cache-Control": { "required": true, @@ -18694,7 +19177,7 @@ } }, "405": { - "description": "method_not_allowed after earlier admission gates.", + "description": "method_not_allowed after earlier host, credential and scope gates.", "headers": { "Cache-Control": { "required": true, @@ -18709,7 +19192,7 @@ "required": true, "schema": { "enum": [ - "GET, PUT" + "POST" ], "type": "string" } @@ -18724,7 +19207,7 @@ } }, "413": { - "description": "payload_too_large: input over the outer byte bound.", + "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", "headers": { "Cache-Control": { "schema": { @@ -18744,7 +19227,7 @@ } }, "429": { - "description": "rate_limited by existing admission.", + "description": "rate_limited by the existing visitor/subject admission.", "headers": { "Cache-Control": { "required": true, @@ -18773,7 +19256,7 @@ } }, "500": { - "description": "internal_error with payload-free diagnostics.", + "description": "internal_error without provider, query, identity or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -18794,7 +19277,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no unconfirmed success.", + "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", "headers": { "Cache-Control": { "required": true, @@ -18821,73 +19304,19 @@ } ], "x-version-introduced": "v1" - }, - "put": { + } + }, + "/api/v1/identity/invitable-roles": { + "get": { "tags": [ - "CustomFieldDefinitions" - ], - "description": "Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions.", - "operationId": "ReviseCustomFieldDefinitionDraft", - "parameters": [ - { - "name": "id", - "in": "path", - "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", - "required": true, - "schema": { - "maxLength": 128, - "minLength": 8, - "pattern": "^[!-~]{8,128}$", - "type": "string" - } - }, - { - "name": "If-Match", - "in": "header", - "required": true, - "schema": { - "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", - "type": "string" - } - } + "InvitableRoles" ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CustomFieldDefinitionInput" - } - } - }, - "required": true - }, + "description": "Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization.", + "operationId": "ListInvitableRoles", "responses": { "200": { - "description": "Authorized current projection or minimal committed receipt.", + "description": "Successful current projection or retained committed receipt.", "headers": { - "ETag": { - "required": true, - "schema": { - "type": "string" - } - }, - "Idempotency-Replayed": { - "schema": { - "enum": [ - "true" - ], - "type": "string" - } - }, "Cache-Control": { "required": true, "schema": { @@ -18901,34 +19330,13 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CustomFieldReceiptResponse" + "$ref": "#/components/schemas/InvitableRoleDirectory" } } } }, "400": { - "description": "validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input.", - "headers": { - "Cache-Control": { - "required": true, - "schema": { - "enum": [ - "no-store" - ], - "type": "string" - } - } - }, - "content": { - "application/problem\u002Bjson": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, - "409": { - "description": "concurrency_conflict, business_rule_violation, limit_exceeded, request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable; no automatic retry.", + "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", "headers": { "Cache-Control": { "required": true, @@ -18949,7 +19357,7 @@ } }, "401": { - "description": "unauthorized: invalid credentials.", + "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -18979,7 +19387,7 @@ } }, "403": { - "description": "forbidden: no current operation authority.", + "description": "forbidden for live coverage without current operation or target disclosure capability.", "headers": { "Cache-Control": { "required": true, @@ -19000,7 +19408,7 @@ } }, "404": { - "description": "not_found: foreign, missing or noncovered exact scope/target.", + "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", "headers": { "Cache-Control": { "required": true, @@ -19021,7 +19429,7 @@ } }, "405": { - "description": "method_not_allowed after earlier admission gates.", + "description": "method_not_allowed after earlier host, credential and scope gates.", "headers": { "Cache-Control": { "required": true, @@ -19036,7 +19444,7 @@ "required": true, "schema": { "enum": [ - "GET, PUT" + "GET" ], "type": "string" } @@ -19051,7 +19459,7 @@ } }, "413": { - "description": "payload_too_large: input over the outer byte bound.", + "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", "headers": { "Cache-Control": { "schema": { @@ -19071,7 +19479,7 @@ } }, "429": { - "description": "rate_limited by existing admission.", + "description": "rate_limited by the existing visitor/subject admission.", "headers": { "Cache-Control": { "required": true, @@ -19100,7 +19508,7 @@ } }, "500": { - "description": "internal_error with payload-free diagnostics.", + "description": "internal_error without provider, query, identity or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -19121,7 +19529,7 @@ } }, "503": { - "description": "dependency_unavailable or audit_unavailable; no unconfirmed success.", + "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", "headers": { "Cache-Control": { "required": true, @@ -19150,13 +19558,13 @@ "x-version-introduced": "v1" } }, - "/api/v1/customization/custom-field-definitions/{id}/revisions": { + "/api/v1/identity/memberships/{id}/custom-fields": { "get": { "tags": [ - "CustomFieldDefinitions" + "MembershipCustomFields" ], "description": "Fresh exact scoped projection. No body; only the declared query keys. No-store. Own consent history remains available through retained scope without an Active Membership; it never authorizes a grant or profile write.", - "operationId": "ListCustomFieldDefinitionRevisions", + "operationId": "GetMembershipCustomFields", "parameters": [ { "name": "id", @@ -19167,20 +19575,18 @@ "type": "string", "format": "uuid" } - }, - { - "name": "cursor", - "in": "query", - "schema": { - "maxLength": 256, - "type": "string" - } } ], "responses": { "200": { "description": "Authorized current projection or minimal committed receipt.", "headers": { + "ETag": { + "required": true, + "schema": { + "type": "string" + } + }, "Cache-Control": { "required": true, "schema": { @@ -19194,7 +19600,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CustomFieldDefinitionPageResponse" + "$ref": "#/components/schemas/MembershipCustomFieldsResponse" } } } @@ -19308,7 +19714,7 @@ "required": true, "schema": { "enum": [ - "GET" + "GET, PATCH" ], "type": "string" } @@ -19420,15 +19826,13 @@ } ], "x-version-introduced": "v1" - } - }, - "/api/v1/customization/custom-field-definitions/{id}/publication": { - "post": { + }, + "patch": { "tags": [ - "CustomFieldDefinitions" + "MembershipCustomFields" ], "description": "Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions.", - "operationId": "PublishCustomFieldDefinition", + "operationId": "SetMembershipCustomFields", "parameters": [ { "name": "id", @@ -19465,7 +19869,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CustomFieldPublicationInput" + "$ref": "#/components/schemas/MembershipCustomFieldPatch" } } }, @@ -19637,7 +20041,7 @@ "required": true, "schema": { "enum": [ - "POST" + "GET, PATCH" ], "type": "string" } @@ -19751,55 +20155,13 @@ "x-version-introduced": "v1" } }, - "/api/v1/customization/custom-field-definitions/{id}/retirement": { - "post": { + "/api/v1/identity/me/custom-fields": { + "get": { "tags": [ - "CustomFieldDefinitions" - ], - "description": "Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions.", - "operationId": "RetireCustomFieldDefinition", - "parameters": [ - { - "name": "id", - "in": "path", - "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", - "required": true, - "schema": { - "maxLength": 128, - "minLength": 8, - "pattern": "^[!-~]{8,128}$", - "type": "string" - } - }, - { - "name": "If-Match", - "in": "header", - "required": true, - "schema": { - "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", - "type": "string" - } - } + "MembershipCustomFields" ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/EmptyAdministrationInput" - } - } - }, - "required": true - }, + "description": "Fresh exact scoped projection. No body; only the declared query keys. No-store. Own consent history remains available through retained scope without an Active Membership; it never authorizes a grant or profile write.", + "operationId": "GetOwnMembershipCustomFields", "responses": { "200": { "description": "Authorized current projection or minimal committed receipt.", @@ -19810,14 +20172,6 @@ "type": "string" } }, - "Idempotency-Replayed": { - "schema": { - "enum": [ - "true" - ], - "type": "string" - } - }, "Cache-Control": { "required": true, "schema": { @@ -19831,7 +20185,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CustomFieldReceiptResponse" + "$ref": "#/components/schemas/MembershipCustomFieldsResponse" } } } @@ -19857,27 +20211,6 @@ } } }, - "409": { - "description": "concurrency_conflict, business_rule_violation, limit_exceeded, request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable; no automatic retry.", - "headers": { - "Cache-Control": { - "required": true, - "schema": { - "enum": [ - "no-store" - ], - "type": "string" - } - } - }, - "content": { - "application/problem\u002Bjson": { - "schema": { - "$ref": "#/components/schemas/ProblemDetails" - } - } - } - }, "401": { "description": "unauthorized: invalid credentials.", "headers": { @@ -19966,7 +20299,7 @@ "required": true, "schema": { "enum": [ - "POST" + "GET, PATCH" ], "type": "string" } @@ -20078,26 +20411,14 @@ } ], "x-version-introduced": "v1" - } - }, - "/api/v1/customization/custom-field-definitions/{id}/discard": { - "post": { + }, + "patch": { "tags": [ - "CustomFieldDefinitions" + "MembershipCustomFields" ], "description": "Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions.", - "operationId": "DiscardCustomFieldDefinitionDraft", + "operationId": "SetOwnMembershipCustomFields", "parameters": [ - { - "name": "id", - "in": "path", - "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", @@ -20123,7 +20444,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/EmptyAdministrationInput" + "$ref": "#/components/schemas/MembershipCustomFieldPatch" } } }, @@ -20295,7 +20616,7 @@ "required": true, "schema": { "enum": [ - "POST" + "GET, PATCH" ], "type": "string" } @@ -20409,13 +20730,37 @@ "x-version-introduced": "v1" } }, - "/api/v1/account/site": { + "/api/v1/identity/memberships": { "get": { "tags": [ - "Account" + "Memberships" + ], + "description": "Tenant administrative membership directory requiring current Tenant identity.membership.admin. Rechecks live membership, lifecycle and capability for every page; accepts HostAndClaim, confirmed ClaimAndMembership (including a legacy platform host), or independently verified HostAndNativeSessionScope on a real Tenant/Organization host. Returns only membership/user/organization identifiers, status, contextual displayName and preferredLocale. Active/Suspended undeleted memberships only, ordered by membership UUID. No search, sorting, editing, provider data, grants or global profile. No-store; the MUST ReadSensitive audit row commits before any result is disclosed. The closed native listMemberships caller retains the same live page authority and MUST ReadSensitive audit; native transport grants no additional authority.", + "operationId": "ListMemberships", + "parameters": [ + { + "name": "cursor", + "in": "query", + "description": "Opaque canonical continuation bound to the actor, tenant, organization and operation; obtain it from pageInfo.nextCursor. Every page reauthorizes.", + "schema": { + "maxLength": 1024, + "minLength": 1, + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "Positive page size, default 20; values above 100 are clamped to 100. Repeated, empty or unknown query parameters are refused.", + "schema": { + "maximum": 2147483647, + "minimum": 1, + "type": "integer", + "format": "int32", + "default": 20 + } + } ], - "description": "Authenticated host-backed read through the physical read-only pipeline. Returns only the validated actor UUID, resolved tenant/organization UUIDs and existing public site projection. Accepts no query parameters or client-selected identifiers. No response caching or validators.", - "operationId": "GetAccountSite", "responses": { "200": { "description": "OK", @@ -20433,13 +20778,13 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AccountSite" + "$ref": "#/components/schemas/PageOfMembershipDirectoryItem" } } } }, "400": { - "description": "validation_failed; no query parameters are accepted, and malformed or repeated assertion headers are refused.", + "description": "validation_failed for noncanonical/replayed/oversized cursors, invalid limit or unknown/repeated/empty query parameters; malformed assertion headers are also refused.", "headers": { "Cache-Control": { "required": true, @@ -20460,7 +20805,7 @@ } }, "401": { - "description": "unauthorized; present invalid or undecidable credentials on a known host. Bare Bearer challenge; no credential or provider details.", + "description": "unauthorized for present invalid or undecidable credentials on known hosts, including existing-binding failure; bare Bearer challenge without provider details.", "headers": { "Cache-Control": { "required": true, @@ -20489,8 +20834,29 @@ } } }, + "403": { + "description": "forbidden for confirmed coverage without the current Tenant administrative capability; no directory lookup or disclosure.", + "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 absent credentials, unknown hosts, membership refusals or missing host-backed authority; tenant_mismatch for authenticated host/claim or header disagreement, without disclosure.", + "description": "not_found for absent credentials, noncoverage or untrusted scope; tenant_mismatch for host/claim or header disagreement. Assertions do not select authority.", "headers": { "Cache-Control": { "required": true, @@ -20511,7 +20877,7 @@ } }, "405": { - "description": "method_not_allowed from routing after credential and host-backed authority admission; this operation admits GET only. Absent credentials remain masked as 404.", + "description": "method_not_allowed from routing after earlier credential, resolution and surface gates; GET only.", "headers": { "Cache-Control": { "required": true, @@ -20541,7 +20907,7 @@ } }, "413": { - "description": "payload_too_large; the decoded body bound precedes host classification and authentication. Kestrel framing/backstop refusals may occur outside the application response policy and omit these headers/body.", + "description": "payload_too_large from the existing decoded body bound; outer Kestrel framing refusals may omit application policy.", "headers": { "Cache-Control": { "schema": { @@ -20561,7 +20927,7 @@ } }, "429": { - "description": "rate_limited from early visitor/peer admission, validated-subject quota or subject-registry capacity.", + "description": "rate_limited from visitor/subject admission or subject-registry capacity.", "headers": { "Cache-Control": { "required": true, @@ -20590,7 +20956,7 @@ } }, "500": { - "description": "internal_error from unexpected failures; no exception or query details.", + "description": "internal_error for unexpected failures, without exception/query details.", "headers": { "Cache-Control": { "required": true, @@ -20611,7 +20977,7 @@ } }, "503": { - "description": "dependency_unavailable from live authorization storage, invalid public configuration or sticky subject-registry cleanup fault; refused audit writes preserve the original refusal.", + "description": "dependency_unavailable for live membership/lifecycle storage, auxiliary admission or sticky subject-registry cleanup fault; audit_unavailable when the mandatory sensitive-read row cannot commit. No membership payload is disclosed.", "headers": { "Cache-Control": { "required": true, @@ -20648,16 +21014,29 @@ "x-version-introduced": "v1" } }, - "/api/v1/identity/self": { + "/api/v1/identity/memberships/{id}": { "get": { "tags": [ - "Identity" + "Memberships" + ], + "description": "Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization.", + "operationId": "GetMembershipDetail", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority.", + "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" + } + } ], - "description": "Off self-only binding read. Missing is distinct from Active; Closing/Closed/conflicting bindings return 401 and never look missing. federationAlias is the host tenant\u0027s Active, entitled federation alias or null, read through the one host-only read-only setter; an undecidable read is 503 and never null. It is a provider hint for the BFF host binding, not authority. No request body, query or assertion/scope selectors.", - "operationId": "GetIdentitySelf", "responses": { - "400": { - "description": "validation_failed for malformed or repeated native selectors/assertions, unexpected query/body or Idempotency-Key.", + "200": { + "description": "Successful current projection or retained committed receipt.", "headers": { "Cache-Control": { "required": true, @@ -20667,18 +21046,78 @@ ], "type": "string" } + }, + "ETag": { + "required": true, + "schema": { + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" + } } }, "content": { - "application/problem\u002Bjson": { + "application/json": { "schema": { - "$ref": "#/components/schemas/ProblemDetails" + "$ref": "#/components/schemas/MembershipDetailResponse" } } } }, - "401": { - "description": "unauthorized for invalid/expired native source, undecidable bearer or terminal/conflicting self binding; bare Bearer challenge.", + "400": { + "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "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 for live coverage without current operation or target disclosure capability.", "headers": { "Cache-Control": { "required": true, @@ -20688,15 +21127,6 @@ ], "type": "string" } - }, - "WWW-Authenticate": { - "required": true, - "schema": { - "enum": [ - "Bearer" - ], - "type": "string" - } } }, "content": { @@ -20708,7 +21138,7 @@ } }, "404": { - "description": "not_found for missing native source/credentials, unknown/platform host, noncoverage or host/scope disagreement.", + "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", "headers": { "Cache-Control": { "required": true, @@ -20729,7 +21159,7 @@ } }, "405": { - "description": "method_not_allowed after earlier host, credential and native-source gates.", + "description": "method_not_allowed after earlier host, credential and scope gates.", "headers": { "Cache-Control": { "required": true, @@ -20759,7 +21189,7 @@ } }, "413": { - "description": "payload_too_large from the existing decoded body bound; outer Kestrel refusals may omit application headers.", + "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", "headers": { "Cache-Control": { "schema": { @@ -20779,7 +21209,7 @@ } }, "429": { - "description": "rate_limited from visitor/subject admission; bootstrap can also exhaust the shared authority creation-attempt windows.", + "description": "rate_limited by the existing visitor/subject admission.", "headers": { "Cache-Control": { "required": true, @@ -20808,7 +21238,7 @@ } }, "500": { - "description": "internal_error without provider, query or credential details.", + "description": "internal_error without provider, query, identity or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -20829,7 +21259,7 @@ } }, "503": { - "description": "dependency_unavailable for binding/lifecycle/audit storage, unknown COMMIT, permanent creation capacity or cleanup fault. No association/result payload is disclosed.", + "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", "headers": { "Cache-Control": { "required": true, @@ -20848,60 +21278,73 @@ } } } - }, - "200": { - "description": "Successful bounded projection.", - "headers": { - "Cache-Control": { - "required": true, - "schema": { - "enum": [ - "no-store" - ], - "type": "string" - } - } - }, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/IdentitySelfState" - } - } - } } }, "security": [ { - "TenantBearer": [], - "NativeSessionSource": [] + "TenantBearer": [] } ], "x-version-introduced": "v1" } }, - "/api/v1/identity/self/bootstrap": { - "post": { + "/api/v1/identity/memberships/{id}/profile": { + "put": { "tags": [ - "Identity" + "Memberships" + ], + "description": "Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried.", + "operationId": "SetMembershipProfile", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority.", + "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 aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version.", + "required": true, + "schema": { + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" + } + } ], - "description": "Opt-in tenantless natural-key convergent create. New binding returns 201, existing/racing winner returns 200; unknown COMMIT returns 503 and a deliberate retry resolves the actual stored binding. Real creation alone writes the central MUST event. No membership, scoped session or browser cookie is created. Idempotency-Key and scope/assertion selectors are refused. Empty JSON object only, at most 512 bytes.", - "operationId": "BootstrapIdentitySelf", "requestBody": { "content": { "application/json": { "schema": { - "maxProperties": 0, - "type": "object", - "additionalProperties": false + "$ref": "#/components/schemas/MembershipProfileInput" } } }, "required": true }, "responses": { - "400": { - "description": "validation_failed for malformed or repeated native selectors/assertions, unexpected query/body or Idempotency-Key.", + "200": { + "description": "Successful current projection or retained committed receipt.", "headers": { "Cache-Control": { "required": true, @@ -20911,18 +21354,36 @@ ], "type": "string" } + }, + "ETag": { + "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-target disclosure audit on a replay.", + "schema": { + "enum": [ + "true" + ], + "type": "string" + } } }, "content": { - "application/problem\u002Bjson": { + "application/json": { "schema": { - "$ref": "#/components/schemas/ProblemDetails" + "$ref": "#/components/schemas/AdministrationVersionReceipt" } } } }, - "401": { - "description": "unauthorized for invalid/expired native source, undecidable bearer or terminal/conflicting self binding; bare Bearer challenge.", + "400": { + "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", "headers": { "Cache-Control": { "required": true, @@ -20932,15 +21393,6 @@ ], "type": "string" } - }, - "WWW-Authenticate": { - "required": true, - "schema": { - "enum": [ - "Bearer" - ], - "type": "string" - } } }, "content": { @@ -20951,8 +21403,8 @@ } } }, - "404": { - "description": "not_found for missing native source/credentials, unknown/platform host, noncoverage or host/scope disagreement.", + "409": { + "description": "concurrency_conflict for a valid stale version; business_rule_violation for refused lifecycle/last-admin/last-organization rules; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", "headers": { "Cache-Control": { "required": true, @@ -20972,8 +21424,8 @@ } } }, - "405": { - "description": "method_not_allowed after earlier host, credential and native-source gates.", + "401": { + "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -20984,11 +21436,11 @@ "type": "string" } }, - "Allow": { + "WWW-Authenticate": { "required": true, "schema": { "enum": [ - "POST" + "Bearer" ], "type": "string" } @@ -21002,10 +21454,11 @@ } } }, - "413": { - "description": "payload_too_large from the existing decoded body bound; outer Kestrel refusals may omit application headers.", + "403": { + "description": "forbidden for live coverage without current operation or target disclosure capability.", "headers": { "Cache-Control": { + "required": true, "schema": { "enum": [ "no-store" @@ -21022,8 +21475,8 @@ } } }, - "429": { - "description": "rate_limited from visitor/subject admission; bootstrap can also exhaust the shared authority creation-attempt windows.", + "404": { + "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", "headers": { "Cache-Control": { "required": true, @@ -21033,14 +21486,6 @@ ], "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": { @@ -21051,8 +21496,8 @@ } } }, - "500": { - "description": "internal_error without provider, query or credential details.", + "405": { + "description": "method_not_allowed after earlier host, credential and scope gates.", "headers": { "Cache-Control": { "required": true, @@ -21062,6 +21507,15 @@ ], "type": "string" } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "PUT" + ], + "type": "string" + } } }, "content": { @@ -21072,11 +21526,10 @@ } } }, - "503": { - "description": "dependency_unavailable for binding/lifecycle/audit storage, unknown COMMIT, permanent creation capacity or cleanup fault. No association/result payload is disclosed.", + "413": { + "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", "headers": { "Cache-Control": { - "required": true, "schema": { "enum": [ "no-store" @@ -21093,8 +21546,8 @@ } } }, - "403": { - "description": "forbidden; creation is disabled for a genuinely missing binding. Existing bindings remain readable.", + "429": { + "description": "rate_limited by the existing visitor/subject admission.", "headers": { "Cache-Control": { "required": true, @@ -21104,6 +21557,14 @@ ], "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": { @@ -21114,8 +21575,8 @@ } } }, - "200": { - "description": "Successful bounded projection.", + "500": { + "description": "internal_error without provider, query, identity or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -21128,15 +21589,15 @@ } }, "content": { - "application/json": { + "application/problem\u002Bjson": { "schema": { - "$ref": "#/components/schemas/IdentitySelfActive" + "$ref": "#/components/schemas/ProblemDetails" } } } }, - "201": { - "description": "New actor binding and central MUST audit committed; no tenant session.", + "503": { + "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", "headers": { "Cache-Control": { "required": true, @@ -21146,21 +21607,12 @@ ], "type": "string" } - }, - "Location": { - "required": true, + } + }, + "content": { + "application/problem\u002Bjson": { "schema": { - "enum": [ - "/api/v1/identity/self" - ], - "type": "string" - } - } - }, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/IdentitySelfActive" + "$ref": "#/components/schemas/ProblemDetails" } } } @@ -21168,47 +21620,129 @@ }, "security": [ { - "TenantBearer": [], - "NativeSessionSource": [] + "TenantBearer": [] } ], "x-version-introduced": "v1" } }, - "/api/v1/identity/self/contexts": { - "get": { + "/api/v1/identity/memberships/{id}/role-assignments": { + "put": { "tags": [ - "Identity" + "Memberships" ], - "description": "Off self-only navigation read. Returns only Active self membership scopes with live tenant/organization labels and configured HTTPS entry origins. No profiles, role grants or arbitrary actor selection. Forward-only subject-bound seek cursor, not authority or a snapshot. No request body or assertion/scope selectors.", - "operationId": "ListIdentitySelfContexts", + "description": "Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried.", + "operationId": "ReplaceMembershipRoleAssignments", "parameters": [ { - "name": "cursor", - "in": "query", - "description": "Canonical base64url authority/digest-bound forward seek cursor. Foreign/malformed values are refused; no previous-page cursor.", + "name": "id", + "in": "path", + "description": "Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority.", + "required": true, "schema": { - "maxLength": 1024, - "minLength": 1, + "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": "limit", - "in": "query", - "description": "Canonical positive ASCII decimal Int32 (1\u20132147483647), default 20; accepted values above 100 clamp to 100. Leading zeros, repeats, signs, overflow and unknown query keys are refused.", + "name": "If-Match", + "in": "header", + "description": "One canonical strong quoted decimal aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version.", + "required": true, "schema": { - "maximum": 2147483647, - "minimum": 1, - "type": "integer", - "format": "int32", - "default": 20 + "maxLength": 21, + "minLength": 3, + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" } } ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MembershipRolesInput" + } + } + }, + "required": true + }, "responses": { + "200": { + "description": "Successful current projection or retained committed receipt.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "ETag": { + "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-target disclosure audit on a replay.", + "schema": { + "enum": [ + "true" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AdministrationVersionReceipt" + } + } + } + }, "400": { - "description": "validation_failed for malformed or repeated native selectors/assertions, unexpected query/body or Idempotency-Key.", + "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "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 refused lifecycle/last-admin/last-organization rules; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", "headers": { "Cache-Control": { "required": true, @@ -21229,7 +21763,7 @@ } }, "401": { - "description": "unauthorized for invalid/expired native source, undecidable bearer or terminal/conflicting self binding; bare Bearer challenge.", + "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", "headers": { "Cache-Control": { "required": true, @@ -21258,8 +21792,29 @@ } } }, + "403": { + "description": "forbidden for live coverage without current operation or target disclosure capability.", + "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 missing native source/credentials, unknown/platform host, noncoverage or host/scope disagreement.", + "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", "headers": { "Cache-Control": { "required": true, @@ -21280,7 +21835,7 @@ } }, "405": { - "description": "method_not_allowed after earlier host, credential and native-source gates.", + "description": "method_not_allowed after earlier host, credential and scope gates.", "headers": { "Cache-Control": { "required": true, @@ -21295,7 +21850,7 @@ "required": true, "schema": { "enum": [ - "GET" + "PUT" ], "type": "string" } @@ -21310,7 +21865,7 @@ } }, "413": { - "description": "payload_too_large from the existing decoded body bound; outer Kestrel refusals may omit application headers.", + "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", "headers": { "Cache-Control": { "schema": { @@ -21330,7 +21885,7 @@ } }, "429": { - "description": "rate_limited from visitor/subject admission; bootstrap can also exhaust the shared authority creation-attempt windows.", + "description": "rate_limited by the existing visitor/subject admission.", "headers": { "Cache-Control": { "required": true, @@ -21359,7 +21914,7 @@ } }, "500": { - "description": "internal_error without provider, query or credential details.", + "description": "internal_error without provider, query, identity or submitted-value diagnostics.", "headers": { "Cache-Control": { "required": true, @@ -21380,7 +21935,7 @@ } }, "503": { - "description": "dependency_unavailable for binding/lifecycle/audit storage, unknown COMMIT, permanent creation capacity or cleanup fault. No association/result payload is disclosed.", + "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", "headers": { "Cache-Control": { "required": true, @@ -21399,9 +21954,73 @@ } } } + } + }, + "security": [ + { + "TenantBearer": [] + } + ], + "x-version-introduced": "v1" + } + }, + "/api/v1/identity/memberships/{id}/status": { + "put": { + "tags": [ + "Memberships" + ], + "description": "Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried.", + "operationId": "ChangeMembershipStatus", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority.", + "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 aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version.", + "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/MembershipStatusInput" + } + } }, + "required": true + }, + "responses": { "200": { - "description": "Successful bounded projection.", + "description": "Successful current projection or retained committed receipt.", "headers": { "Cache-Control": { "required": true, @@ -21411,336 +22030,7212 @@ ], "type": "string" } + }, + "ETag": { + "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-target disclosure audit on a replay.", + "schema": { + "enum": [ + "true" + ], + "type": "string" + } } }, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SelfContextPage" + "$ref": "#/components/schemas/AdministrationVersionReceipt" } } } - } - }, - "security": [ - { - "TenantBearer": [], - "NativeSessionSource": [] - } - ], - "x-version-introduced": "v1" - } - } - }, - "components": { - "schemas": { - "AccountSite": { - "required": [ - "actorId", - "tenantId", - "organizationId", - "site" - ], - "type": "object", - "properties": { - "actorId": { - "$ref": "#/components/schemas/UserId" - }, - "tenantId": { - "$ref": "#/components/schemas/TenantId" }, - "organizationId": { - "oneOf": [ - { - "type": "null" - }, - { - "$ref": "#/components/schemas/OrganizationId" + "400": { + "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } } - ] + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } }, - "site": { - "$ref": "#/components/schemas/PublicSite" - } - } - }, - "AdministrationGrantResponse": { - "oneOf": [ - { - "required": [ - "scope", - "key" - ], - "type": "object", - "properties": { - "scope": { - "enum": [ - "Tenant" - ], - "type": "string" - }, - "key": { - "enum": [ - "customization.custom_field.admin" - ], - "type": "string" + "409": { + "description": "concurrency_conflict for a valid stale version; business_rule_violation for refused lifecycle/last-admin/last-organization rules; 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" + } } }, - "additionalProperties": false + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } }, - { - "required": [ - "scope", - "key" - ], - "type": "object", - "properties": { - "scope": { - "enum": [ - "Tenant" - ], - "type": "string" + "401": { + "description": "unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } }, - "key": { - "enum": [ - "identity.federation.admin" - ], - "type": "string" + "WWW-Authenticate": { + "required": true, + "schema": { + "enum": [ + "Bearer" + ], + "type": "string" + } } }, - "additionalProperties": false + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } }, - { - "required": [ - "scope", - "key" - ], - "type": "object", - "properties": { - "scope": { - "enum": [ - "Tenant" - ], - "type": "string" - }, - "key": { - "enum": [ - "identity.membership.admin" - ], - "type": "string" + "403": { + "description": "forbidden for live coverage without current operation or target disclosure capability.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } } }, - "additionalProperties": false + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } }, - { - "required": [ - "scope", - "key" - ], - "type": "object", - "properties": { - "scope": { - "enum": [ - "Tenant" - ], - "type": "string" - }, - "key": { - "enum": [ - "identity.membership_profile.write" - ], - "type": "string" + "404": { + "description": "not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } } }, - "additionalProperties": false + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } }, - { - "required": [ - "scope", - "key" - ], - "type": "object", - "properties": { - "scope": { - "enum": [ - "Tenant" - ], - "type": "string" + "405": { + "description": "method_not_allowed after earlier host, credential and scope gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } }, - "key": { - "enum": [ - "identity.role.admin" - ], - "type": "string" + "Allow": { + "required": true, + "schema": { + "enum": [ + "PUT" + ], + "type": "string" + } } }, - "additionalProperties": false - }, - { - "required": [ - "scope", - "key" - ], - "type": "object", - "properties": { - "scope": { - "enum": [ - "Tenant" - ], - "type": "string" - }, - "key": { - "enum": [ - "tenancy.locale.write" - ], - "type": "string" + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } } - }, - "additionalProperties": false + } }, - { - "required": [ - "scope", - "key" - ], - "type": "object", - "properties": { - "scope": { - "enum": [ - "Tenant" - ], - "type": "string" - }, - "key": { - "enum": [ - "tenancy.organization.admin" - ], - "type": "string" + "413": { + "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } } }, - "additionalProperties": false + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } }, - { - "required": [ - "scope", - "key" - ], - "type": "object", - "properties": { - "scope": { - "enum": [ - "Tenant" - ], - "type": "string" + "429": { + "description": "rate_limited by the existing visitor/subject admission.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } }, - "key": { - "enum": [ - "tenancy.setting.write" - ], - "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" + } } }, - "additionalProperties": false + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } }, - { - "required": [ - "scope", - "key" - ], - "type": "object", - "properties": { - "scope": { - "enum": [ - "Organization" - ], - "type": "string" - }, - "key": { - "enum": [ - "identity.membership.admin" - ], - "type": "string" + "500": { + "description": "internal_error without provider, query, identity or submitted-value diagnostics.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } } }, - "additionalProperties": false + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } }, - { - "required": [ - "scope", - "key" - ], - "type": "object", - "properties": { - "scope": { - "enum": [ - "Organization" - ], - "type": "string" - }, - "key": { - "enum": [ - "identity.membership_profile.write" - ], - "type": "string" + "503": { + "description": "dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } } }, - "additionalProperties": false - } - ] - }, - "AdministrationVersionReceipt": { - "required": [ - "version" - ], - "type": "object", - "properties": { - "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." + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } } }, - "additionalProperties": false - }, - "ConsentDetailsResponse": { - "required": [ - "evidenceId", - "sequence", - "isGranted", - "membershipId", - "definitionId", - "definitionVersion", - "purposeKey", - "noticeLocale", - "noticeHash", - "noticeText", - "labels" + "security": [ + { + "TenantBearer": [] + } ], - "type": "object", - "properties": { - "evidenceId": { - "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" - }, - "sequence": { - "maxLength": 19, - "pattern": "^(0|[1-9][0-9]{0,18})$", - "type": "string" - }, - "isGranted": { - "type": "boolean" - }, - "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" + "x-version-introduced": "v1" + } + }, + "/api/v1/identity/session-scope/admissions": { + "post": { + "tags": [ + "NativeSessionAdmission" + ], + "description": "Explicit initial selection or scope switch only. Requires a current native source, real host ceiling and live stored-actor membership/lifecycle. The central MUST security event names the admitted Membership and commits before an association witness is returned. This proves API admission, never cookie delivery. Ordinary refresh uses Off self/AccountSite reads and does not invoke this POST. No query or Idempotency-Key; empty JSON object only.", + "operationId": "AdmitNativeSessionScope", + "parameters": [ + { + "name": "X-LearnStack-Native-Tenant-Id", + "in": "header", + "description": "Canonical lower-case nonempty tenant UUID candidate, verified against the real host and live membership.", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } }, - "definitionId": { - "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", + { + "name": "X-LearnStack-Native-Organization-Id", + "in": "header", + "description": "Optional canonical lower-case nonempty organization UUID candidate. Provider scope and legacy assertions, when present, must agree exactly.", + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "maxProperties": 0, + "type": "object", + "additionalProperties": false + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful bounded projection.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/NativeSessionScopeAdmission" + } + } + } + }, + "400": { + "description": "validation_failed for malformed or repeated native selectors/assertions, unexpected query/body or Idempotency-Key.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized for invalid/expired native source, undecidable bearer or terminal/conflicting self binding; 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" + } + } + } + }, + "404": { + "description": "not_found for missing native source/credentials, unknown/platform host, noncoverage or host/scope disagreement.", + "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 native-source 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 from the existing decoded body bound; outer Kestrel refusals may omit application headers.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited from visitor/subject admission; bootstrap can also exhaust the shared authority creation-attempt windows.", + "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 or credential details.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable for binding/lifecycle/audit storage, unknown COMMIT, permanent creation capacity or cleanup fault. No association/result payload is disclosed.", + "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/organization-memberships": { + "get": { + "tags": [ + "OrganizationMemberships" + ], + "description": "Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization.", + "operationId": "ListOrganizationMemberships", + "parameters": [ + { + "name": "cursor", + "in": "query", + "description": "Opaque canonical current-actor/scope/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": "OK", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PageOfMembershipDirectoryItem" + } + } + } + }, + "400": { + "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "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 for live coverage without current operation or target disclosure capability.", + "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 missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "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; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "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 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; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "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/profile": { + "get": { + "tags": [ + "OwnMembership" + ], + "description": "Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization.", + "operationId": "GetOwnMembershipProfile", + "responses": { + "200": { + "description": "Successful current projection or retained committed receipt.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "ETag": { + "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/OwnMembershipProfileResponse" + } + } + } + }, + "400": { + "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "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 for live coverage without current operation or target disclosure capability.", + "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 missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "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, PUT" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "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 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; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "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" + }, + "put": { + "tags": [ + "OwnMembership" + ], + "description": "Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried.", + "operationId": "SetOwnMembershipProfile", + "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" + } + }, + { + "name": "If-Match", + "in": "header", + "description": "One canonical strong quoted decimal aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version.", + "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/MembershipProfileInput" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful current projection or retained committed receipt.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "ETag": { + "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-target disclosure audit on a replay.", + "schema": { + "enum": [ + "true" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AdministrationVersionReceipt" + } + } + } + }, + "400": { + "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "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 refused lifecycle/last-admin/last-organization rules; 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 for live coverage without current operation or target disclosure capability.", + "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 missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "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, PUT" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "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 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; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "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/contexts": { + "get": { + "tags": [ + "OwnMembership" + ], + "description": "Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization.", + "operationId": "ListOwnMembershipContexts", + "parameters": [ + { + "name": "cursor", + "in": "query", + "description": "Opaque canonical current-actor/scope/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": "Successful current projection or retained committed receipt.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OwnMembershipContextPage" + } + } + } + }, + "400": { + "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "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 for live coverage without current operation or target disclosure capability.", + "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 missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "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; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "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 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; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "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/capabilities": { + "get": { + "tags": [ + "OwnMembership" + ], + "description": "Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization.", + "operationId": "GetOwnCapabilities", + "responses": { + "200": { + "description": "Successful current projection or retained committed receipt.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OwnCapabilitiesDto" + } + } + } + }, + "400": { + "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "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 for live coverage without current operation or target disclosure capability.", + "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 missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "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; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "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 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; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "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/permissions": { + "get": { + "tags": [ + "Permissions" + ], + "description": "Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization.", + "operationId": "GetPermissionRegistry", + "parameters": [ + { + "name": "sourceReleaseVersion", + "in": "query", + "description": "Current source release, default1. Source1 returns v2; source2 returns v3; source3 returns v4; no automatic adoption/grant.", + "schema": { + "maximum": 3, + "minimum": 1, + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "Successful current projection or retained committed receipt.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PermissionRegistryResponse" + } + } + } + }, + "400": { + "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "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 for live coverage without current operation or target disclosure capability.", + "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 missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "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; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "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 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; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "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/roles": { + "get": { + "tags": [ + "Roles" + ], + "description": "Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization.", + "operationId": "ListRoles", + "responses": { + "200": { + "description": "Successful current projection or retained committed receipt.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RoleDirectoryResponse" + } + } + } + }, + "400": { + "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "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 for live coverage without current operation or target disclosure capability.", + "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 missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "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; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "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 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; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "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/roles/{id}": { + "get": { + "tags": [ + "Roles" + ], + "description": "Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization.", + "operationId": "GetRoleDetail", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority.", + "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": "Successful current projection or retained committed receipt.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "ETag": { + "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/RoleDetailResponse" + } + } + } + }, + "400": { + "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "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 for live coverage without current operation or target disclosure capability.", + "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 missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "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; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "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 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; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "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/roles/{id}/grants": { + "put": { + "tags": [ + "Roles" + ], + "description": "Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried.", + "operationId": "ChangeRoleGrants", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority.", + "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 aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version.", + "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/RoleGrantsInput" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful current projection or retained committed receipt.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "ETag": { + "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-target disclosure audit on a replay.", + "schema": { + "enum": [ + "true" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AdministrationVersionReceipt" + } + } + } + }, + "400": { + "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "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 refused lifecycle/last-admin/last-organization rules; 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 for live coverage without current operation or target disclosure capability.", + "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 missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "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": [ + "PUT" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "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 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; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "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/roles/{id}/manifest-adoptions": { + "post": { + "tags": [ + "Roles" + ], + "description": "Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried.", + "operationId": "AdoptRoleGrantManifest", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority.", + "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 aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version.", + "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/RoleManifestInput" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful current projection or retained committed receipt.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "ETag": { + "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-target disclosure audit on a replay.", + "schema": { + "enum": [ + "true" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AdministrationVersionReceipt" + } + } + } + }, + "400": { + "description": "validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition.", + "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 refused lifecycle/last-admin/last-organization rules; 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 for live coverage without current operation or target disclosure capability.", + "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 missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement.", + "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; administration bodies are at most 16 KiB, including undeclared/chunked bodies.", + "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 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; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit.", + "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/customization/custom-field-definitions": { + "get": { + "tags": [ + "CustomFieldDefinitions" + ], + "description": "Fresh exact scoped projection. No body; only the declared query keys. No-store. Own consent history remains available through retained scope without an Active Membership; it never authorizes a grant or profile write.", + "operationId": "ListCustomFieldDefinitions", + "parameters": [ + { + "name": "cursor", + "in": "query", + "schema": { + "maxLength": 256, + "type": "string" + } + }, + { + "name": "status", + "in": "query", + "schema": { + "enum": [ + "Draft", + "Active", + "Deprecated" + ], + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Authorized current projection or minimal committed receipt.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CustomFieldDefinitionPageResponse" + } + } + } + }, + "400": { + "description": "validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized: invalid credentials.", + "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: no current operation authority.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found: foreign, missing or noncovered exact scope/target.", + "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 admission gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "GET, POST" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large: input over the outer byte bound.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by existing 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 with payload-free 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; no unconfirmed success.", + "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" + }, + "post": { + "tags": [ + "CustomFieldDefinitions" + ], + "description": "Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions.", + "operationId": "RegisterCustomFieldDefinition", + "parameters": [ + { + "name": "Idempotency-Key", + "in": "header", + "required": true, + "schema": { + "maxLength": 128, + "minLength": 8, + "pattern": "^[!-~]{8,128}$", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CustomFieldDefinitionInput" + } + } + }, + "required": true + }, + "responses": { + "201": { + "description": "Authorized current projection or minimal committed receipt.", + "headers": { + "ETag": { + "required": true, + "schema": { + "type": "string" + } + }, + "Idempotency-Replayed": { + "schema": { + "enum": [ + "true" + ], + "type": "string" + } + }, + "Location": { + "required": true, + "schema": { + "maxLength": 128, + "type": "string" + } + }, + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CustomFieldReceiptResponse" + } + } + } + }, + "400": { + "description": "validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "409": { + "description": "concurrency_conflict, business_rule_violation, limit_exceeded, request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable; no automatic retry.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized: invalid credentials.", + "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: no current operation authority.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found: foreign, missing or noncovered exact scope/target.", + "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 admission gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "GET, POST" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large: input over the outer byte bound.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by existing 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 with payload-free 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; no unconfirmed success.", + "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/customization/custom-field-definitions/{id}": { + "get": { + "tags": [ + "CustomFieldDefinitions" + ], + "description": "Fresh exact scoped projection. No body; only the declared query keys. No-store. Own consent history remains available through retained scope without an Active Membership; it never authorizes a grant or profile write.", + "operationId": "GetCustomFieldDefinition", + "parameters": [ + { + "name": "id", + "in": "path", + "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": "Authorized current projection or minimal committed receipt.", + "headers": { + "ETag": { + "required": true, + "schema": { + "type": "string" + } + }, + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CustomFieldDefinitionResponse" + } + } + } + }, + "400": { + "description": "validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized: invalid credentials.", + "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: no current operation authority.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found: foreign, missing or noncovered exact scope/target.", + "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 admission gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "GET, PUT" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large: input over the outer byte bound.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by existing 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 with payload-free 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; no unconfirmed success.", + "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" + }, + "put": { + "tags": [ + "CustomFieldDefinitions" + ], + "description": "Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions.", + "operationId": "ReviseCustomFieldDefinitionDraft", + "parameters": [ + { + "name": "id", + "in": "path", + "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", + "required": true, + "schema": { + "maxLength": 128, + "minLength": 8, + "pattern": "^[!-~]{8,128}$", + "type": "string" + } + }, + { + "name": "If-Match", + "in": "header", + "required": true, + "schema": { + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CustomFieldDefinitionInput" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Authorized current projection or minimal committed receipt.", + "headers": { + "ETag": { + "required": true, + "schema": { + "type": "string" + } + }, + "Idempotency-Replayed": { + "schema": { + "enum": [ + "true" + ], + "type": "string" + } + }, + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CustomFieldReceiptResponse" + } + } + } + }, + "400": { + "description": "validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "409": { + "description": "concurrency_conflict, business_rule_violation, limit_exceeded, request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable; no automatic retry.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized: invalid credentials.", + "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: no current operation authority.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found: foreign, missing or noncovered exact scope/target.", + "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 admission gates.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Allow": { + "required": true, + "schema": { + "enum": [ + "GET, PUT" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "413": { + "description": "payload_too_large: input over the outer byte bound.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by existing 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 with payload-free 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; no unconfirmed success.", + "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/customization/custom-field-definitions/{id}/revisions": { + "get": { + "tags": [ + "CustomFieldDefinitions" + ], + "description": "Fresh exact scoped projection. No body; only the declared query keys. No-store. Own consent history remains available through retained scope without an Active Membership; it never authorizes a grant or profile write.", + "operationId": "ListCustomFieldDefinitionRevisions", + "parameters": [ + { + "name": "id", + "in": "path", + "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": "cursor", + "in": "query", + "schema": { + "maxLength": 256, + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Authorized current projection or minimal committed receipt.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CustomFieldDefinitionPageResponse" + } + } + } + }, + "400": { + "description": "validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized: invalid credentials.", + "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: no current operation authority.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found: foreign, missing or noncovered exact scope/target.", + "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 admission 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: input over the outer byte bound.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by existing 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 with payload-free 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; no unconfirmed success.", + "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/customization/custom-field-definitions/{id}/publication": { + "post": { + "tags": [ + "CustomFieldDefinitions" + ], + "description": "Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions.", + "operationId": "PublishCustomFieldDefinition", + "parameters": [ + { + "name": "id", + "in": "path", + "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", + "required": true, + "schema": { + "maxLength": 128, + "minLength": 8, + "pattern": "^[!-~]{8,128}$", + "type": "string" + } + }, + { + "name": "If-Match", + "in": "header", + "required": true, + "schema": { + "pattern": "^\u0022(0|[1-9][0-9]{0,18})\u0022$", + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CustomFieldPublicationInput" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Authorized current projection or minimal committed receipt.", + "headers": { + "ETag": { + "required": true, + "schema": { + "type": "string" + } + }, + "Idempotency-Replayed": { + "schema": { + "enum": [ + "true" + ], + "type": "string" + } + }, + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CustomFieldReceiptResponse" + } + } + } + }, + "400": { + "description": "validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "409": { + "description": "concurrency_conflict, business_rule_violation, limit_exceeded, request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable; no automatic retry.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized: invalid credentials.", + "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: no current operation authority.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found: foreign, missing or noncovered exact scope/target.", + "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 admission 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: input over the outer byte bound.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by existing 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 with payload-free 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; no unconfirmed success.", + "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/customization/custom-field-definitions/{id}/retirement": { + "post": { + "tags": [ + "CustomFieldDefinitions" + ], + "description": "Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions.", + "operationId": "RetireCustomFieldDefinition", + "parameters": [ + { + "name": "id", + "in": "path", + "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", + "required": true, + "schema": { + "maxLength": 128, + "minLength": 8, + "pattern": "^[!-~]{8,128}$", + "type": "string" + } + }, + { + "name": "If-Match", + "in": "header", + "required": true, + "schema": { + "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": "Authorized current projection or minimal committed receipt.", + "headers": { + "ETag": { + "required": true, + "schema": { + "type": "string" + } + }, + "Idempotency-Replayed": { + "schema": { + "enum": [ + "true" + ], + "type": "string" + } + }, + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CustomFieldReceiptResponse" + } + } + } + }, + "400": { + "description": "validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "409": { + "description": "concurrency_conflict, business_rule_violation, limit_exceeded, request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable; no automatic retry.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized: invalid credentials.", + "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: no current operation authority.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found: foreign, missing or noncovered exact scope/target.", + "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 admission 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: input over the outer byte bound.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by existing 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 with payload-free 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; no unconfirmed success.", + "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/customization/custom-field-definitions/{id}/discard": { + "post": { + "tags": [ + "CustomFieldDefinitions" + ], + "description": "Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions.", + "operationId": "DiscardCustomFieldDefinitionDraft", + "parameters": [ + { + "name": "id", + "in": "path", + "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", + "required": true, + "schema": { + "maxLength": 128, + "minLength": 8, + "pattern": "^[!-~]{8,128}$", + "type": "string" + } + }, + { + "name": "If-Match", + "in": "header", + "required": true, + "schema": { + "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": "Authorized current projection or minimal committed receipt.", + "headers": { + "ETag": { + "required": true, + "schema": { + "type": "string" + } + }, + "Idempotency-Replayed": { + "schema": { + "enum": [ + "true" + ], + "type": "string" + } + }, + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CustomFieldReceiptResponse" + } + } + } + }, + "400": { + "description": "validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "409": { + "description": "concurrency_conflict, business_rule_violation, limit_exceeded, request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable; no automatic retry.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized: invalid credentials.", + "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: no current operation authority.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "404": { + "description": "not_found: foreign, missing or noncovered exact scope/target.", + "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 admission 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: input over the outer byte bound.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited by existing 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 with payload-free 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; no unconfirmed success.", + "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/account/site": { + "get": { + "tags": [ + "Account" + ], + "description": "Authenticated host-backed read through the physical read-only pipeline. Returns only the validated actor UUID, resolved tenant/organization UUIDs and existing public site projection. Accepts no query parameters or client-selected identifiers. No response caching or validators.", + "operationId": "GetAccountSite", + "responses": { + "200": { + "description": "OK", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/AccountSite" + } + } + } + }, + "400": { + "description": "validation_failed; no query parameters are accepted, and malformed or repeated assertion headers are refused.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized; present invalid or undecidable credentials on a known host. Bare Bearer challenge; no credential or provider details.", + "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" + } + } + } + }, + "404": { + "description": "not_found for absent credentials, unknown hosts, membership refusals or missing host-backed authority; tenant_mismatch for authenticated host/claim or header disagreement, without disclosure.", + "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 from routing after credential and host-backed authority admission; this operation admits GET only. Absent credentials remain masked as 404.", + "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; the decoded body bound precedes host classification and authentication. Kestrel framing/backstop refusals may occur outside the application response policy and omit these headers/body.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited from early visitor/peer admission, validated-subject quota or subject-registry capacity.", + "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 from unexpected failures; no exception or query details.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable from live authorization storage, invalid public configuration or sticky subject-registry cleanup fault; refused audit writes preserve the original refusal.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Retry-After": { + "description": "Suggested dependency retry delay in seconds; not a recovery guarantee.", + "required": true, + "schema": { + "minimum": 0, + "type": "integer" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + } + }, + "security": [ + { + "TenantBearer": [] + } + ], + "x-version-introduced": "v1" + } + }, + "/api/v1/identity/self": { + "get": { + "tags": [ + "Identity" + ], + "description": "Off self-only binding read. Missing is distinct from Active; Closing/Closed/conflicting bindings return 401 and never look missing. federationAlias is the host tenant\u0027s Active, entitled federation alias or null, read through the one host-only read-only setter; an undecidable read is 503 and never null. It is a provider hint for the BFF host binding, not authority. No request body, query or assertion/scope selectors.", + "operationId": "GetIdentitySelf", + "responses": { + "400": { + "description": "validation_failed for malformed or repeated native selectors/assertions, unexpected query/body or Idempotency-Key.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized for invalid/expired native source, undecidable bearer or terminal/conflicting self binding; 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" + } + } + } + }, + "404": { + "description": "not_found for missing native source/credentials, unknown/platform host, noncoverage or host/scope disagreement.", + "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 native-source 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 from the existing decoded body bound; outer Kestrel refusals may omit application headers.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited from visitor/subject admission; bootstrap can also exhaust the shared authority creation-attempt windows.", + "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 or credential details.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable for binding/lifecycle/audit storage, unknown COMMIT, permanent creation capacity or cleanup fault. No association/result payload is disclosed.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "200": { + "description": "Successful bounded projection.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/IdentitySelfState" + } + } + } + } + }, + "security": [ + { + "TenantBearer": [], + "NativeSessionSource": [] + } + ], + "x-version-introduced": "v1" + } + }, + "/api/v1/identity/self/bootstrap": { + "post": { + "tags": [ + "Identity" + ], + "description": "Opt-in tenantless natural-key convergent create. New binding returns 201, existing/racing winner returns 200; unknown COMMIT returns 503 and a deliberate retry resolves the actual stored binding. Real creation alone writes the central MUST event. No membership, scoped session or browser cookie is created. Idempotency-Key and scope/assertion selectors are refused. Empty JSON object only, at most 512 bytes.", + "operationId": "BootstrapIdentitySelf", + "requestBody": { + "content": { + "application/json": { + "schema": { + "maxProperties": 0, + "type": "object", + "additionalProperties": false + } + } + }, + "required": true + }, + "responses": { + "400": { + "description": "validation_failed for malformed or repeated native selectors/assertions, unexpected query/body or Idempotency-Key.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized for invalid/expired native source, undecidable bearer or terminal/conflicting self binding; 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" + } + } + } + }, + "404": { + "description": "not_found for missing native source/credentials, unknown/platform host, noncoverage or host/scope disagreement.", + "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 native-source 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 from the existing decoded body bound; outer Kestrel refusals may omit application headers.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited from visitor/subject admission; bootstrap can also exhaust the shared authority creation-attempt windows.", + "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 or credential details.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable for binding/lifecycle/audit storage, unknown COMMIT, permanent creation capacity or cleanup fault. No association/result payload is disclosed.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "403": { + "description": "forbidden; creation is disabled for a genuinely missing binding. Existing bindings remain readable.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "200": { + "description": "Successful bounded projection.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/IdentitySelfActive" + } + } + } + }, + "201": { + "description": "New actor binding and central MUST audit committed; no tenant session.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + }, + "Location": { + "required": true, + "schema": { + "enum": [ + "/api/v1/identity/self" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/IdentitySelfActive" + } + } + } + } + }, + "security": [ + { + "TenantBearer": [], + "NativeSessionSource": [] + } + ], + "x-version-introduced": "v1" + } + }, + "/api/v1/identity/self/contexts": { + "get": { + "tags": [ + "Identity" + ], + "description": "Off self-only navigation read. Returns only Active self membership scopes with live tenant/organization labels and configured HTTPS entry origins. No profiles, role grants or arbitrary actor selection. Forward-only subject-bound seek cursor, not authority or a snapshot. No request body or assertion/scope selectors.", + "operationId": "ListIdentitySelfContexts", + "parameters": [ + { + "name": "cursor", + "in": "query", + "description": "Canonical base64url authority/digest-bound forward seek cursor. Foreign/malformed values are refused; no previous-page cursor.", + "schema": { + "maxLength": 1024, + "minLength": 1, + "type": "string" + } + }, + { + "name": "limit", + "in": "query", + "description": "Canonical positive ASCII decimal Int32 (1\u20132147483647), default 20; accepted values above 100 clamp to 100. Leading zeros, repeats, signs, overflow and unknown query keys are refused.", + "schema": { + "maximum": 2147483647, + "minimum": 1, + "type": "integer", + "format": "int32", + "default": 20 + } + } + ], + "responses": { + "400": { + "description": "validation_failed for malformed or repeated native selectors/assertions, unexpected query/body or Idempotency-Key.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "401": { + "description": "unauthorized for invalid/expired native source, undecidable bearer or terminal/conflicting self binding; 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" + } + } + } + }, + "404": { + "description": "not_found for missing native source/credentials, unknown/platform host, noncoverage or host/scope disagreement.", + "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 native-source 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 from the existing decoded body bound; outer Kestrel refusals may omit application headers.", + "headers": { + "Cache-Control": { + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "429": { + "description": "rate_limited from visitor/subject admission; bootstrap can also exhaust the shared authority creation-attempt windows.", + "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 or credential details.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "503": { + "description": "dependency_unavailable for binding/lifecycle/audit storage, unknown COMMIT, permanent creation capacity or cleanup fault. No association/result payload is disclosed.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/problem\u002Bjson": { + "schema": { + "$ref": "#/components/schemas/ProblemDetails" + } + } + } + }, + "200": { + "description": "Successful bounded projection.", + "headers": { + "Cache-Control": { + "required": true, + "schema": { + "enum": [ + "no-store" + ], + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SelfContextPage" + } + } + } + } + }, + "security": [ + { + "TenantBearer": [], + "NativeSessionSource": [] + } + ], + "x-version-introduced": "v1" + } + } + }, + "components": { + "schemas": { + "AccountClosureAcceptedResponse": { + "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": [ + "closure" + ], + "type": "string" + }, + "status": { + "enum": [ + "scheduled" + ], + "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 + }, + "AccountSite": { + "required": [ + "actorId", + "tenantId", + "organizationId", + "site" + ], + "type": "object", + "properties": { + "actorId": { + "$ref": "#/components/schemas/UserId" + }, + "tenantId": { + "$ref": "#/components/schemas/TenantId" + }, + "organizationId": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/OrganizationId" + } + ] + }, + "site": { + "$ref": "#/components/schemas/PublicSite" + } + } + }, + "AdministrationGrantResponse": { + "oneOf": [ + { + "required": [ + "scope", + "key" + ], + "type": "object", + "properties": { + "scope": { + "enum": [ + "Tenant" + ], + "type": "string" + }, + "key": { + "enum": [ + "customization.custom_field.admin" + ], + "type": "string" + } + }, + "additionalProperties": false + }, + { + "required": [ + "scope", + "key" + ], + "type": "object", + "properties": { + "scope": { + "enum": [ + "Tenant" + ], + "type": "string" + }, + "key": { + "enum": [ + "identity.federation.admin" + ], + "type": "string" + } + }, + "additionalProperties": false + }, + { + "required": [ + "scope", + "key" + ], + "type": "object", + "properties": { + "scope": { + "enum": [ + "Tenant" + ], + "type": "string" + }, + "key": { + "enum": [ + "identity.membership.admin" + ], + "type": "string" + } + }, + "additionalProperties": false + }, + { + "required": [ + "scope", + "key" + ], + "type": "object", + "properties": { + "scope": { + "enum": [ + "Tenant" + ], + "type": "string" + }, + "key": { + "enum": [ + "identity.membership_profile.write" + ], + "type": "string" + } + }, + "additionalProperties": false + }, + { + "required": [ + "scope", + "key" + ], + "type": "object", + "properties": { + "scope": { + "enum": [ + "Tenant" + ], + "type": "string" + }, + "key": { + "enum": [ + "identity.role.admin" + ], + "type": "string" + } + }, + "additionalProperties": false + }, + { + "required": [ + "scope", + "key" + ], + "type": "object", + "properties": { + "scope": { + "enum": [ + "Tenant" + ], + "type": "string" + }, + "key": { + "enum": [ + "tenancy.locale.write" + ], + "type": "string" + } + }, + "additionalProperties": false + }, + { + "required": [ + "scope", + "key" + ], + "type": "object", + "properties": { + "scope": { + "enum": [ + "Tenant" + ], + "type": "string" + }, + "key": { + "enum": [ + "tenancy.organization.admin" + ], + "type": "string" + } + }, + "additionalProperties": false + }, + { + "required": [ + "scope", + "key" + ], + "type": "object", + "properties": { + "scope": { + "enum": [ + "Tenant" + ], + "type": "string" + }, + "key": { + "enum": [ + "tenancy.setting.write" + ], + "type": "string" + } + }, + "additionalProperties": false + }, + { + "required": [ + "scope", + "key" + ], + "type": "object", + "properties": { + "scope": { + "enum": [ + "Organization" + ], + "type": "string" + }, + "key": { + "enum": [ + "identity.membership.admin" + ], + "type": "string" + } + }, + "additionalProperties": false + }, + { + "required": [ + "scope", + "key" + ], + "type": "object", + "properties": { + "scope": { + "enum": [ + "Organization" + ], + "type": "string" + }, + "key": { + "enum": [ + "identity.membership_profile.write" + ], + "type": "string" + } + }, + "additionalProperties": false + } + ] + }, + "AdministrationVersionReceipt": { + "required": [ + "version" + ], + "type": "object", + "properties": { + "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 + }, + "ConsentDetailsResponse": { + "required": [ + "evidenceId", + "sequence", + "isGranted", + "membershipId", + "definitionId", + "definitionVersion", + "purposeKey", + "noticeLocale", + "noticeHash", + "noticeText", + "labels" + ], + "type": "object", + "properties": { + "evidenceId": { + "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" + }, + "sequence": { + "maxLength": 19, + "pattern": "^(0|[1-9][0-9]{0,18})$", + "type": "string" + }, + "isGranted": { + "type": "boolean" + }, + "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" + }, + "definitionId": { + "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" }, "definitionVersion": { @@ -22657,259 +30152,732 @@ "enum": [ false ], - "type": "boolean" + "type": "boolean" + } + }, + "additionalProperties": false + }, + { + "required": [ + "type", + "items", + "minItems", + "maxItems" + ], + "type": "object", + "properties": { + "type": { + "enum": [ + "array" + ], + "type": "string" + }, + "items": { + "$ref": "#/components/schemas/CustomFieldSchemaNode2" + }, + "minItems": { + "maximum": 10, + "minimum": 0, + "type": "integer" + }, + "maxItems": { + "maximum": 10, + "minimum": 1, + "type": "integer" + } + }, + "additionalProperties": false + } + ] + }, + "CustomFieldSchemaNode2": { + "oneOf": [ + { + "required": [ + "type", + "minLength", + "maxLength" + ], + "type": "object", + "properties": { + "type": { + "enum": [ + "string" + ], + "type": "string" + }, + "minLength": { + "maximum": 256, + "minimum": 1, + "type": "integer" + }, + "maxLength": { + "maximum": 256, + "minimum": 1, + "type": "integer" + } + }, + "additionalProperties": false + }, + { + "required": [ + "type", + "minLength", + "maxLength", + "enum" + ], + "type": "object", + "properties": { + "type": { + "enum": [ + "string" + ], + "type": "string" + }, + "minLength": { + "maximum": 256, + "minimum": 1, + "type": "integer" + }, + "maxLength": { + "maximum": 256, + "minimum": 1, + "type": "integer" + }, + "enum": { + "maxItems": 20, + "minItems": 1, + "uniqueItems": true, + "type": "array", + "items": { + "maxLength": 256, + "type": "string" + } + } + }, + "additionalProperties": false + }, + { + "required": [ + "type", + "minimum", + "maximum" + ], + "type": "object", + "properties": { + "type": { + "enum": [ + "integer" + ], + "type": "string" + }, + "minimum": { + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "type": "integer" + }, + "maximum": { + "maximum": 9007199254740991, + "minimum": -9007199254740991, + "type": "integer" + } + }, + "additionalProperties": false + }, + { + "required": [ + "type", + "minimum", + "maximum" + ], + "type": "object", + "properties": { + "type": { + "enum": [ + "number" + ], + "type": "string" + }, + "minimum": { + "type": "number" + }, + "maximum": { + "type": "number" } }, "additionalProperties": false }, { "required": [ - "type", - "items", - "minItems", - "maxItems" + "type" ], "type": "object", "properties": { "type": { "enum": [ - "array" + "boolean" ], "type": "string" - }, - "items": { - "$ref": "#/components/schemas/CustomFieldSchemaNode2" - }, - "minItems": { - "maximum": 10, - "minimum": 0, - "type": "integer" - }, - "maxItems": { - "maximum": 10, - "minimum": 1, - "type": "integer" } }, "additionalProperties": false } - ] + ] + }, + "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" + } + ] + }, + "DataErasureAcceptedResponse": { + "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": [ + "erasure" + ], + "type": "string" + }, + "status": { + "enum": [ + "scheduled" + ], + "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 + }, + "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\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 + }, + "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 }, - "CustomFieldSchemaNode2": { - "oneOf": [ - { - "required": [ - "type", - "minLength", - "maxLength" - ], - "type": "object", - "properties": { - "type": { - "enum": [ - "string" - ], - "type": "string" - }, - "minLength": { - "maximum": 256, - "minimum": 1, - "type": "integer" - }, - "maxLength": { - "maximum": 256, - "minimum": 1, - "type": "integer" - } - }, - "additionalProperties": false + "DataExportTruncationResponse": { + "required": [ + "collection", + "included", + "total" + ], + "type": "object", + "properties": { + "collection": { + "maxLength": 65, + "type": "string" }, - { - "required": [ - "type", - "minLength", - "maxLength", - "enum" - ], - "type": "object", - "properties": { - "type": { - "enum": [ - "string" - ], - "type": "string" - }, - "minLength": { - "maximum": 256, - "minimum": 1, - "type": "integer" - }, - "maxLength": { - "maximum": 256, - "minimum": 1, - "type": "integer" - }, - "enum": { - "maxItems": 20, - "minItems": 1, - "uniqueItems": true, - "type": "array", - "items": { - "maxLength": 256, - "type": "string" - } - } - }, - "additionalProperties": false + "included": { + "maximum": 9007199254740991, + "minimum": 0, + "type": "integer", + "format": "int64" }, - { - "required": [ - "type", - "minimum", - "maximum" - ], - "type": "object", - "properties": { - "type": { - "enum": [ - "integer" - ], - "type": "string" - }, - "minimum": { - "maximum": 9007199254740991, - "minimum": -9007199254740991, - "type": "integer" - }, - "maximum": { - "maximum": 9007199254740991, - "minimum": -9007199254740991, - "type": "integer" - } - }, - "additionalProperties": false + "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" }, - { - "required": [ - "type", - "minimum", - "maximum" + "kind": { + "enum": [ + "export" ], - "type": "object", - "properties": { - "type": { - "enum": [ - "number" - ], - "type": "string" - }, - "minimum": { - "type": "number" - }, - "maximum": { - "type": "number" - } - }, - "additionalProperties": false + "type": "string" }, - { - "required": [ - "type" + "status": { + "enum": [ + "requested" ], - "type": "object", - "properties": { - "type": { - "enum": [ - "boolean" - ], - "type": "string" - } - }, - "additionalProperties": false + "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 }, - "CustomFieldValueEnvelope": { + "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", + "executeAt", + "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", + "description": "An erasure is scheduled until its window ends, then fulfilling and awaiting_privileged_step together (the job commits both at once, so fulfilling is not observed for an ordinary erasure), and completed once an operator finishes the audit redaction. After executeAt and before the job has run a request still reads scheduled: a client derives a \u0027due, running shortly\u0027 state from status and executeAt." }, - { - "maxItems": 10, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": [ + "null", + "string" + ], + "description": "When the request last changed; for a cancelled, blocked or failed request this is when it ended.", + "format": "date-time" + }, + "completedAt": { + "type": [ + "null", + "string" + ], + "description": "Set only for a completed request; a cancelled, blocked or failed request has none (read updatedAt).", + "format": "date-time" + }, + "lastRefusal": { + "enum": [ + "blocked_window", + "blocked_hold", + "blocked_last_administrator", + null + ], + "type": [ + "null", + "string" + ], + "description": "The closed refusal code of the last refused attempt, without the lockey_ prefix of the 409 keys." + }, + "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" + }, + "description": "What the request retains, a partial list: a kind not listed is retained and not counted, never zero. The audit log\u0027s kinds appear only once the request is completed. invitation_record counts the offers the person issued or accepted; a pending offer addressed to their e-mail address is retained and not counted, because it is not locatable by person." + }, + "artifact": { + "oneOf": [ + { + "$ref": "#/components/schemas/DataExportArtifactResponse" + }, + { + "type": "null" + } + ] }, - { - "maxProperties": 10, - "type": "object", - "additionalProperties": { - "$ref": "#/components/schemas/CustomFieldValueNode1" - } - } - ] - }, - "CustomFieldValueNode1": { - "anyOf": [ - { - "maxLength": 256, - "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." }, - { - "type": "number" + "executeAt": { + "type": [ + "null", + "string" + ], + "description": "An erasure\u0027s cancellable window ends here and its job may run from here: the deadline for a cancellation, to be read from the receipt and never computed as createdAt plus a constant. Null for an export.", + "format": "date-time" }, - { + "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 +32510,159 @@ }, "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", + "executeAt" + ], + "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", + "description": "An erasure is scheduled until its window ends, then fulfilling and awaiting_privileged_step together (the job commits both at once, so fulfilling is not observed for an ordinary erasure), and completed once an operator finishes the audit redaction. After executeAt and before the job has run a request still reads scheduled: a client derives a \u0027due, running shortly\u0027 state from status and executeAt. A closure has no job: it reads scheduled until an operator Begins it, at or after its executeAt, then fulfilling (the account no longer works, so its owner rarely reads it), and completed once an operator finalizes it; it is never blocked or failed." + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": [ + "null", + "string" + ], + "description": "When the request last changed; for a cancelled, blocked or failed request this is when it ended.", + "format": "date-time" + }, + "completedAt": { + "type": [ + "null", + "string" + ], + "description": "Set only for a completed request; a cancelled, blocked or failed request has none (read updatedAt).", + "format": "date-time" + }, + "lastRefusal": { + "enum": [ + "blocked_window", + "blocked_hold", + "blocked_last_administrator", + null + ], + "type": [ + "null", + "string" + ], + "description": "The closed refusal code of the last refused attempt, without the lockey_ prefix of the 409 keys. For a scheduled closure it is the reason an operator\u0027s Begin was refused (blocked_window, blocked_hold or blocked_last_administrator: another eligible tenant-wide administrator must be appointed first); the closure stays scheduled and cancellable." + }, + "failureReason": { + "enum": [ + "export_too_large", + "execution_failed", + null + ], + "type": [ + "null", + "string" + ] + }, + "retained": { + "maxItems": 16, + "type": "array", + "items": { + "$ref": "#/components/schemas/DataRequestRetainedResponse" + }, + "description": "What the request retains, a partial list: a kind not listed is retained and not counted, never zero. The audit log\u0027s kinds appear only once the request is completed. invitation_record counts the offers the person issued or accepted; a pending offer addressed to their e-mail address is retained and not counted, because it is not locatable by person." + }, + "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." + }, + "executeAt": { + "type": [ + "null", + "string" + ], + "description": "An erasure\u0027s cancellable window ends here and its job may run from here: the deadline for a cancellation, to be read from the receipt and never computed as createdAt plus a constant. Null for an export. For a closure it is the earliest time an operator may Begin it, not a cancellation deadline: a scheduled closure can be cancelled until that Begin commits.", + "format": "date-time" + } + }, + "additionalProperties": false + }, "OwnFieldConsentCurrentResponse": { "required": [ "consent" @@ -25258,6 +33379,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", @@ -25564,6 +33771,21 @@ { "name": "PublicSite" }, + { + "name": "DataRequestEntry" + }, + { + "name": "OwnDataRequests" + }, + { + "name": "OwnDataExportTickets" + }, + { + "name": "OwnDataExportChunks" + }, + { + "name": "DataRequests" + }, { "name": "Federation" }, diff --git a/backend/src/LearnStack.Api/Authentication/HttpAuthorizationTransportSource.cs b/backend/src/LearnStack.Api/Authentication/HttpAuthorizationTransportSource.cs index 54f57371e..1cbc8368b 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 new file mode 100644 index 000000000..55300fb44 --- /dev/null +++ b/backend/src/LearnStack.Api/Authentication/HttpDataExportSessionBinding.cs @@ -0,0 +1,101 @@ +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. +/// +/// +/// 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 + || 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 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); + 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 8f6191ea3..53b685be1 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/LiveAuthorizationRegistration.cs b/backend/src/LearnStack.Api/Authentication/LiveAuthorizationRegistration.cs index b643bf984..1d832d85e 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 21c6baf3d..f144bee4b 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 46efef226..a1b493888 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 ba1c05777..f5f6b1454 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() 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 260aeeea1..5d086e321 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; @@ -92,7 +93,8 @@ internal HttpOperationClassification Classify(Endpoint? endpoint, out OperationP if (anonymous.Count != 1 || authorization.Count != 0) return HttpOperationClassification.Refused; } 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.NativeSessionAdmission or OperationPolicyKind.OwnMembershipRead or OperationPolicyKind.InvitationEntry or OperationPolicyKind.OwnConsentEntry or OperationPolicyKind.OwnFieldConsentGrant + or OperationPolicyKind.OwnDataRequest or OperationPolicyKind.OwnDataRequestEntry) { if (anonymous.Count != 0 || authorization.Count != 1 || authorization[0].AuthenticationSchemes != TenantAuthenticationRegistration.Scheme @@ -209,6 +211,30 @@ 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.CreateErasure)) => (typeof(CreateOwnDataErasureCommand), "CreateOwnDataErasure", "POST"), + var pair when pair == (typeof(OwnDataRequestsController), nameof(OwnDataRequestsController.CreateClosure)) => (typeof(CreateOwnAccountClosureCommand), "CreateOwnAccountClosure", "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.CreateErasure)) => (typeof(CreateDataErasureForSubjectCommand), "CreateDataErasureForSubject", "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(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.CreateErasure)) => (typeof(CreateRetainedDataErasureCommand), "CreateRetainedDataErasure", "POST"), + var pair when pair == (typeof(DataRequestEntryController), nameof(DataRequestEntryController.CreateClosure)) => (typeof(CreateRetainedAccountClosureCommand), "CreateRetainedAccountClosure", "POST"), + var pair when pair == (typeof(DataRequestEntryController), nameof(DataRequestEntryController.Cancel)) => (typeof(CancelRetainedDataRequestCommand), "CancelRetainedDataRequest", "POST"), + var pair when pair == (typeof(DataRequestEntryController), nameof(DataRequestEntryController.RevokeExport)) => (typeof(RevokeRetainedDataExportCommand), "RevokeRetainedDataExport", "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 000000000..cecd63ba4 --- /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 CreateRetainedDataErasureCommand or CreateRetainedAccountClosureCommand or CancelRetainedDataRequestCommand or RevokeRetainedDataExportCommand + 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 000000000..233e64adb --- /dev/null +++ b/backend/src/LearnStack.Api/Authentication/OwnDataRequestHttpInput.cs @@ -0,0 +1,236 @@ +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, cancellation and revocation; If-Match only, and always, on +/// cancellation and revocation; 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 is OwnDataRequestPurpose.Cancel or OwnDataRequestPurpose.Revoke + && !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 + { + // One purpose, three routes: the operation's own request type says whether an export, an erasure or + // an account closure is filed. + OwnDataRequestPurpose.Create when AdministrationHttpInput.HasFields(body) => + operation.RequestType == typeof(CreateRetainedDataErasureCommand) ? new CreateRetainedDataErasureCommand(organization) + : operation.RequestType == typeof(CreateRetainedAccountClosureCommand) ? new CreateRetainedAccountClosureCommand(organization) + : (object)new CreateRetainedDataExportCommand(organization), + OwnDataRequestPurpose.Cancel => TryRequestId(body, out var cancelled, "requestId") + ? new CancelRetainedDataRequestCommand(organization, cancelled, version) : null, + OwnDataRequestPurpose.Revoke => TryRequestId(body, out var revoked, "requestId") + ? new RevokeRetainedDataExportCommand(organization, revoked, 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 or CreateRetainedDataErasureCommand or CreateRetainedAccountClosureCommand => OwnDataRequestPurpose.Create, + CancelRetainedDataRequestCommand => OwnDataRequestPurpose.Cancel, + RevokeRetainedDataExportCommand => OwnDataRequestPurpose.Revoke, + MintRetainedDataExportTicketCommand => OwnDataRequestPurpose.Ticket, + ReadRetainedDataExportChunkCommand => OwnDataRequestPurpose.Chunk, + _ => 0, + }; + + /// + /// A key only where the operation is keyed, If-Match only (and always) on cancellation and revocation, 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 is OwnDataRequestPurpose.Cancel or OwnDataRequestPurpose.Revoke + ? request.Headers.IfMatch.Count == 1 : !request.Headers.ContainsKey("If-Match")) + && (purpose is OwnDataRequestPurpose.Create or OwnDataRequestPurpose.Cancel or OwnDataRequestPurpose.Revoke + || !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 000000000..846bcdb97 --- /dev/null +++ b/backend/src/LearnStack.Api/Authentication/OwnDataRequestOperation.cs @@ -0,0 +1,50 @@ +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 nine 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 Erasures = new(Root + "/erasures", "POST", nameof(DataRequestEntryController.CreateErasure), typeof(CreateRetainedDataErasureCommand), OwnDataRequestPurpose.Create); + private static readonly OwnDataRequestOperation Closures = new(Root + "/closures", "POST", nameof(DataRequestEntryController.CreateClosure), typeof(CreateRetainedAccountClosureCommand), OwnDataRequestPurpose.Create); + private static readonly OwnDataRequestOperation Revocations = new(Root + "/revocations", "POST", nameof(DataRequestEntryController.RevokeExport), typeof(RevokeRetainedDataExportCommand), OwnDataRequestPurpose.Revoke); + 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 + "/erasures" => Erasures, + Root + "/closures" => Closures, + Root + "/cancellations" => Cancellations, + Root + "/revocations" => Revocations, + 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 000000000..d570d2cc7 --- /dev/null +++ b/backend/src/LearnStack.Api/Authentication/OwnDataRequestSubjectSource.cs @@ -0,0 +1,190 @@ +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 or OwnDataRequestPurpose.Revoke } purpose + || _input is not + { + Request: CreateRetainedDataExportCommand or CreateRetainedDataErasureCommand or CreateRetainedAccountClosureCommand + or CancelRetainedDataRequestCommand or RevokeRetainedDataExportCommand + } 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 or OwnDataRequestPurpose.Revoke) + || _request is not (CreateRetainedDataExportCommand or CreateRetainedDataErasureCommand or CreateRetainedAccountClosureCommand + or CancelRetainedDataRequestCommand or RevokeRetainedDataExportCommand) + || 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/PlatformOperatorDocumentTransformer.cs b/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs index ad63f706e..f8c33bcf3 100644 --- a/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs +++ b/backend/src/LearnStack.Api/Authentication/PlatformOperatorDocumentTransformer.cs @@ -20,8 +20,10 @@ internal sealed class PlatformOperatorDocumentTransformer(string documentName) : "Operator-only platform operations. Authenticate with a short-lived access token issued by the " + "deployment's operator issuer to the client learnstack-operator after a second factor; the token " + "profile and the runbooks are in docs/runbooks/operator-access.md, and the recovery of dead-lettered " - + "work is explained in docs/runbooks/operator-recovery.md and the federation operator steps in " - + "docs/runbooks/federation-operator.md. Authentication grants no " + + "work is explained in docs/runbooks/operator-recovery.md, the federation operator steps in " + + "docs/runbooks/federation-operator.md, the completion of an erasure in docs/runbooks/data-erasure.md and the " + + "closure of a person's account in docs/runbooks/account-closure.md. " + + "Authentication grants no " + "permission: each operation needs a Platform grant held by LearnStack and evaluated on every act."; public async Task TransformAsync( @@ -97,6 +99,7 @@ [new OpenApiSecuritySchemeReference(PlatformOperatorAuthentication.Scheme, docum "PlatformDeliveryReplay" => typeof(Platform.DeliveryReplayBody), "PlatformOutboxReset" => typeof(Platform.OutboxResetBody), "PlatformFederationRemove" or "PlatformFederationDisable" => typeof(Platform.FederationActBody), + "PlatformErasureComplete" or "PlatformClosureBegin" or "PlatformClosureFinalize" => typeof(Platform.DataRequestActBody), _ => throw new InvalidOperationException("An operator operation declares no request body: " + operationId), }; @@ -124,6 +127,15 @@ private static void DescribeInspectionParameters(OpenApiOperation operation) switch (concrete.Name) { + case "state" when operation.OperationId == "PlatformDataRequestInspect": + var states = Platform.PlatformOperatorEndpoints.DataRequestStates.Select(state => state.Name).ToList(); + concrete.Description = states[0] + " (default), " + string.Join(", ", states.Skip(1)) + "."; + concrete.Schema = new OpenApiSchema + { + Type = JsonSchemaType.String, + Enum = [.. states.Select(state => (JsonNode)JsonValue.Create(state)!)], + }; + break; case "state": concrete.Description = "dead_lettered (default) or terminal_requested."; concrete.Schema = new OpenApiSchema @@ -219,15 +231,15 @@ private static void DescribeResponses(OpenApiDocument document, OpenApiOperation private static readonly (string Status, string Description)[] Statuses = [ - ("400", "validation_failed: the body is malformed, a required field is missing, an onboarding identifier is not a UUIDv7, a recovery route names the nil or the platform tenant or a malformed subscription, a provider subject is blank or over 255 characters, a template name is not one of the closed set, or the ticket is not 1 to 64 characters of A-Z a-z 0-9 . _ : / # -. A refusal at the gate carries no per-field errors; a page parameter that is refused names itself on errors.state, errors.limit, errors.cursor or errors.query (a parameter the route does not take). A federation act names only an alias of the form lsf- and 32 lowercase hexadecimal characters."), + ("400", "validation_failed: the body is malformed, a required field is missing, an onboarding identifier is not a UUIDv7, a recovery route names the nil or the platform tenant or a malformed subscription, a provider subject is blank or over 255 characters, a template name is not one of the closed set, or the ticket is not 1 to 64 characters of A-Z a-z 0-9 . _ : / # -. A refusal at the gate carries no per-field errors; a page parameter that is refused names itself on errors.state, errors.limit, errors.cursor or errors.query (a parameter the route does not take). A federation act names only an alias of the form lsf- and 32 lowercase hexadecimal characters, and an erasure completion or a closure Begin or Finalize only a request identifier that is a UUIDv7."), ("401", "unauthorized: the credential is missing or does not meet the token profile. One answer for every cause; the cause is in the operator's signals."), ("403", "forbidden: the credential is good and this operator holds no grant for the operation."), - ("404", "not_found: the killswitch key is not declared, the tenant the route names does not exist, a recovery names no such row, or a federation disable names an alias no identity-provider instance has."), - ("409", "business_rule_violation: the act refuses the state it found; the reason is in errors (an identifier or slug is taken, the host is taken or reserved, the person has not signed in, the Role is not an initialized administrator Role, the tenant has Membership history or an administrator exists, or another change won). A recovery answers 409 with the reason on errors.fence (the row no longer shows the fence the inspection returned: read it again) or on errors.state (the fence holds and the row is not one the act may take; the rule that refused it is the reason's cause parameter: processed, leased, invalid_envelope, reason_refused, subscription_not_active, type_not_dispatchable or tenant_not_serving). A repeat that changes a value under the same identifiers is refused; an exact repeat answers 200. A federation act answers 409 with the reason on errors.owner (the instance's owner marker is not LearnStack's, or names another tenant than its row), errors.connection (a live connection row still names the broker and it reads or is still enabled: a remove is refused; disable an unreadable one first, and it is then removed even with the live row), errors.class (a disable found a healthy broker with a live row) or errors.provider (the provider definitively refused the change; nothing changed). A repeat of a federation act that had landed answers 200 already_applied and writes no row of its own, and does not say that a remove owes the account review."), + ("404", "not_found: the killswitch key is not declared, the tenant the route names does not exist, a recovery names no such row, a federation disable names an alias no identity-provider instance has, or an erasure completion or a closure Begin or Finalize names no request."), + ("409", "business_rule_violation: the act refuses the state it found; the reason is in errors (an identifier or slug is taken, the host is taken or reserved, the person has not signed in, the Role is not an initialized administrator Role, the tenant has Membership history or an administrator exists, or another change won). A recovery answers 409 with the reason on errors.fence (the row no longer shows the fence the inspection returned: read it again) or on errors.state (the fence holds and the row is not one the act may take; the rule that refused it is the reason's cause parameter: processed, leased, invalid_envelope, reason_refused, subscription_not_active, type_not_dispatchable or tenant_not_serving). A repeat that changes a value under the same identifiers is refused; an exact repeat answers 200. A federation act answers 409 with the reason on errors.owner (the instance's owner marker is not LearnStack's, or names another tenant than its row), errors.connection (a live connection row still names the broker and it reads or is still enabled: a remove is refused; disable an unreadable one first, and it is then removed even with the live row), errors.class (a disable found a healthy broker with a live row) or errors.provider (the provider definitively refused the change; nothing changed). A repeat of a federation act that had landed answers 200 already_applied and writes no row of its own, and does not say that a remove owes the account review. An erasure completion answers 409 with the reason on errors.kind (the request is not an erasure), errors.origin (a closure's fan-out erasure, which only that closure's finalization completes) or errors.status (the erasure is not awaiting its privileged step; its stored status is the reason's cause parameter), and writes nothing; a repeat of a completion that had landed answers 200 already_completed and writes no second row. A closure Begin answers 409 with the reason on errors.refusal (the closure was refused and the request stays scheduled with the closed code, the reason's cause parameter, as its last_refusal: blocked_window, blocked_hold or blocked_last_administrator), errors.kind (the request is not a closure), errors.status (the closure is completed or cancelled; its stored status is the reason's cause parameter), errors.account (the person's account is already closed), errors.participants (the person holds Memberships in more participant groups, served or not, or more Memberships in one participant tenant, than one closure is admitted for; no code is recorded, the person stays Active, and Phase 11's data operations serve them) or errors.provider (the identity provider's account-removal client is not configured, or would refuse the person's provider identifier, so the account could never be deleted; no code is recorded and the person stays Active: repair the client by its runbook and Begin again), and changes nothing else; a Begin that committed, or found its closure begun, answers 200 begun or resumed, with complete false while a group's fan-out is waiting or failed. A closure Finalize answers 409 with the reason on errors.kind (the request is not a closure), errors.status (the closure was never begun or was cancelled; its stored status is the reason's cause parameter) or errors.groups (a required group's erasure, a served group's or an unserved group's open one, has not reached its privileged step or did not complete during the closure; the reason's served, ready, pending and unserved parameters are closed counts and no group is named: repeat the Begin, let each group's erasure job run, then finalize again), and writes nothing of the closure; a repeat of a Finalize that had landed answers 200 already_finalized and writes no row of its own."), ("413", "payload_too_large: the body is over 4096 bytes."), ("415", "unsupported_media_type: the body is not application/json."), ("429", "rate_limited: the caller exceeded the per-peer request budget."), - ("500", "internal_error: an unexpected failure. An act's final commit may have landed: read the state before changing it. An exact repeat of an onboarding act answers 200; a repeat of a recovery that had landed answers 409 on errors.fence."), - ("503", "audit_unavailable or dependency_unavailable: the audit row could not be written, a connection or an ordered lock could not be taken, or a read failed, so nothing changed. Retry after the delay. A recovery's dependency_unavailable can carry errors.outcome = lockey_outcome_unknown: its commit may have landed, so inspect the row before repeating, because a landed recovery answers a repeat 409 on errors.fence. A federation act's dependency_unavailable carries it when a provider change was sent and its completion could not be recorded or its answer was lost: read the report or the alias before repeating."), + ("500", "internal_error: an unexpected failure. An act's final commit may have landed: read the state before changing it. An exact repeat of an onboarding act answers 200; a repeat of a recovery that had landed answers 409 on errors.fence, and of an erasure completion 200 already_completed, and of a closure Begin 200 resumed, and of a closure Finalize 200 already_finalized."), + ("503", "audit_unavailable or dependency_unavailable: the audit row could not be written, a connection or an ordered lock could not be taken, or a read failed, so nothing changed (except as the closure Finalize clause below says). Retry after the delay. A recovery's dependency_unavailable can carry errors.outcome = lockey_outcome_unknown: its commit may have landed, so inspect the row before repeating, because a landed recovery answers a repeat 409 on errors.fence. A federation act's dependency_unavailable carries it when a provider change was sent and its completion could not be recorded or its answer was lost: read the report or the alias before repeating. An erasure completion's dependency_unavailable carries it when its commit was sent and the answer was lost; a repeat is safe and answers 200 already_completed if the commit had landed, and the redaction is idempotent if it had not. A closure Begin answers dependency_unavailable when another act held one of the person's fences past three seconds, and carries errors.outcome when its commit was sent and the answer was lost; a repeat is safe and answers 200 resumed if the commit had landed. A closure Finalize answers dependency_unavailable when a fence was held past three seconds, and also when any step of its second transaction (an ordered lock, a read, a write or the result row) fails after the provider step: then the person's account may already be deleted at the provider while the closure stays fulfilling, and a repeat finishes it, because a missing account is success. It carries errors.outcome when its final commit was sent and the answer was lost (a repeat answers 200 already_finalized if it had landed), and carries errors.provider when the identity provider did not delete the person's account: lockey_provider_refused (the account-removal client is refused or not configured; repair it by its runbook), lockey_provider_unavailable (the provider could not be reached) or lockey_provider_outcome_unknown (the deletion was sent and its answer was lost). On errors.provider the redaction and its intent row committed and the closure stays fulfilling; a repeat resumes, and a missing account is success."), ]; } diff --git a/backend/src/LearnStack.Api/Authentication/TenantAuthenticationRegistration.cs b/backend/src/LearnStack.Api/Authentication/TenantAuthenticationRegistration.cs index 5fd5d78de..13b438bd4 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 08d8798ce..36d6dbd5f 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 1cd4318f0..3d4cd5137 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 000000000..26d747226 --- /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/AdministrationHttpInput.cs b/backend/src/LearnStack.Api/Common/AdministrationHttpInput.cs index a3d46f2da..9e1dbb1a5 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/Common/AdministrationHttpSurface.cs b/backend/src/LearnStack.Api/Common/AdministrationHttpSurface.cs index 42e70e93d..aa42011f3 100644 --- a/backend/src/LearnStack.Api/Common/AdministrationHttpSurface.cs +++ b/backend/src/LearnStack.Api/Common/AdministrationHttpSurface.cs @@ -23,13 +23,28 @@ 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 "erasures" or "closures" or "cancellations" or "revocations" 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, ("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/Composition/AccountRemovalComposition.cs b/backend/src/LearnStack.Api/Composition/AccountRemovalComposition.cs new file mode 100644 index 000000000..612217b9d --- /dev/null +++ b/backend/src/LearnStack.Api/Composition/AccountRemovalComposition.cs @@ -0,0 +1,59 @@ +using LearnStack.Infrastructure.Identity.AccountRemoval; +using LearnStack.Infrastructure.Resilience; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Resilience; +using LearnStack.SharedKernel.Secrets; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace LearnStack.Api.Composition; + +/// +/// ADR-0107 § 7 composition: the confined Keycloak account-removal adapter replaces the fail-closed +/// only when the confined client's secret is configured +/// (). Otherwise the port keeps its default and every call is refused +/// without any network effect. The Development check that admits a loopback HTTP issuer is made here, never in a module; +/// modules never read DeploymentMode. +/// +internal static class AccountRemovalComposition +{ + internal const string ConfigurationSection = "Resilience:" + AccountRemovalAdapterFactory.PortName; + + internal static IServiceCollection AddLearnStackAccountRemovalAdapter(this IServiceCollection services, IConfiguration configuration) + { + var defaults = new Dictionary + { + [ConfigurationSection + ":Retry:Enabled"] = "false", + [ConfigurationSection + ":Retry:MaxRetryAttempts"] = "0", + [ConfigurationSection + ":Timeout:Enabled"] = "true", + [ConfigurationSection + ":Timeout:TotalSeconds"] = "5", + [ConfigurationSection + ":CircuitBreaker:Enabled"] = "true", + [ConfigurationSection + ":Bulkhead:MaxConcurrency"] = "1", + [ConfigurationSection + ":Bulkhead:QueueLength"] = "0", + }; + var policyConfiguration = new ConfigurationBuilder().AddInMemoryCollection(defaults).AddConfiguration(configuration).Build(); + var policy = policyConfiguration.GetSection(ConfigurationSection).Get()!; + // The shape is fixed, not a range. Retry is off: the closure's Finalize is the repeatable, operator-visible retry, and an + // automatic repeat after a lost answer would hide that answer behind a quiet "absent". The timeout is the adapter's own + // call ceiling (token and deletion together), the breaker is on within the federation range, and the bulkhead admits + // one call with no queue: the sole caller is a deliberate, serialized operator act, and a second concurrent call is + // refused as unavailable and repeated. Any other value refuses at startup. + if (policy.Retry.Enabled || policy.Retry.MaxRetryAttempts != 0 || !policy.Timeout.Enabled + || policy.Timeout.TotalSeconds != AccountRemovalAdapterFactory.CallCeilingSeconds + || !policy.CircuitBreaker.Enabled || !FederationComposition.BreakerInRange(policy.CircuitBreaker) + || policy.Bulkhead is not { MaxConcurrency: 1, QueueLength: 0 }) + throw new InvalidOperationException("Account removal requires finite provider resilience without retries."); + services.AddProviderResilience(policyConfiguration, AccountRemovalAdapterFactory.PortName); + + services.Replace(ServiceDescriptor.Singleton(provider => + { + var secrets = provider.GetRequiredService(); + if (string.IsNullOrEmpty(secrets.GetSecret(AccountRemovalAdapterFactory.SecretKey))) return new RefusingIdentityProviderAccountRemoval(); + var development = provider.GetRequiredService().IsDevelopment(); + var options = new KeycloakAccountRemovalOptions(configuration["Authentication:Tenant:Issuer"] ?? "", development); + return AccountRemovalAdapterFactory.Create(options, secrets, + provider.GetRequiredService>(), + provider.GetRequiredService()); + })); + return services; + } +} diff --git a/backend/src/LearnStack.Api/Composition/DataExportComposition.cs b/backend/src/LearnStack.Api/Composition/DataExportComposition.cs new file mode 100644 index 000000000..3b1d799c1 --- /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/FederationComposition.cs b/backend/src/LearnStack.Api/Composition/FederationComposition.cs index 9a37feef4..27f2e0164 100644 --- a/backend/src/LearnStack.Api/Composition/FederationComposition.cs +++ b/backend/src/LearnStack.Api/Composition/FederationComposition.cs @@ -73,7 +73,7 @@ internal static IServiceCollection AddLearnStackFederationAdapter(this IServiceC /// The admitted breaker range: failure ratio in (0, 1], minimum throughput in [2, 100] (Polly's own floor is 2), /// sampling duration in [1, 60] seconds and break duration in [1, 300] seconds. NaN refuses. /// - private static bool BreakerInRange(CircuitBreakerOptions breaker) => + internal static bool BreakerInRange(CircuitBreakerOptions breaker) => breaker.FailureRatio is > 0 and <= 1 && breaker.MinimumThroughput is >= 2 and <= 100 && breaker.SamplingDurationSeconds is >= 1 and <= 60 diff --git a/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs b/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs index d25268315..3674ff59b 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 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 @@ -309,6 +313,17 @@ public static IServiceCollection AddLearnStackPersistence( // ADR-0099 Amendment 10: the operator's federation report, remove and disable, over the platform scope and the // operator port, which the composition root replaces with the confined adapter when the admin client is configured. services.TryAddScoped(); + // ADR-0107 § 8, ADR-0108: the operator's data-request inspection and erasure completion in the platform scope. + services.TryAddScoped(); + // ADR-0107 § 7: the operator's closure Begin in the platform scope. It hands the served groups to IClosureFanOut, + // which the operator authority registers with the gate and the act executor it needs (a host that composes + // persistence alone has neither); with none registered the Begin refuses before it enters the scope, so no person + // is moved to Closing by a deployment that cannot fan the closure out. + services.TryAddScoped(); + services.TryAddScoped(); // The entitlement socket. A SINGLETON and registered in EVERY deployment mode, // not Development only: ADR-0035 names NullEntitlementProvider the working default @@ -336,6 +351,9 @@ public static IServiceCollection AddLearnStackPersistence( services.AddHealthChecks().AddCheck(AuditHealthCheck.Name); services.TryAddScoped(); + // ADR-0108 § 2: the one redaction executor, a singleton over every module's IUserReferenceLocator, which the + // platform scope resolves for the act it admitted; LearnStack.Infrastructure never references it. + services.TryAddSingleton(); services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); @@ -419,6 +437,8 @@ public static IServiceCollection AddLearnStackPersistence( services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); + services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); diff --git a/backend/src/LearnStack.Api/Composition/PlatformOperatorCompositionExtensions.cs b/backend/src/LearnStack.Api/Composition/PlatformOperatorCompositionExtensions.cs index ec6395753..cee61de98 100644 --- a/backend/src/LearnStack.Api/Composition/PlatformOperatorCompositionExtensions.cs +++ b/backend/src/LearnStack.Api/Composition/PlatformOperatorCompositionExtensions.cs @@ -31,7 +31,8 @@ internal static IServiceCollection AddLearnStackPlatformOperatorAuthority( services.TryAddSingleton(); // The five onboarding acts the operator may run through the ordinary pipeline on the application - // role (ADR-0102 § 2): the closed list the executor and the operator source both judge by. + // role (ADR-0102 § 2), and a closure's per-group fan-out (ADR-0107 § 7), which the closure's Begin + // owner runs and no route does: the closed list the executor and the operator source both judge by. services.AddPlatformOperatorActs(new PlatformOperatorActCatalog( [ Act(PlatformOperations.TenantProvision), @@ -39,8 +40,14 @@ internal static IServiceCollection AddLearnStackPlatformOperatorAuthority( Act(PlatformOperations.RoleInitialize), Act(PlatformOperations.FirstAdminCreate), Act(PlatformOperations.AdminRecover), + Act(PlatformOperations.ClosureFanOut), ])); + // ADR-0107 § 7: a closure's per-group fan-out, one admitted pipeline act per participant group through the act + // executor, which the closure's Begin owner calls after its transaction commits. It lives with the gate and the + // executor it is built from, so a host that composes persistence alone still validates its service graph. + services.TryAddScoped(); + var settings = PlatformOperatorSettings.FromConfiguration(configuration, deploymentMode); if (settings is not null) { diff --git a/backend/src/LearnStack.Api/Idempotency/ProtectedAdministrationOperation.cs b/backend/src/LearnStack.Api/Idempotency/ProtectedAdministrationOperation.cs index ac88fd6f9..b39db4b76 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,20 @@ public enum ProtectedAdministrationOperation SetOwnCustomFields = 21, GrantOwnFieldConsent = 22, WithdrawOwnFieldConsent = 23, + CreateOwnDataExport = 24, + CreateDataExportForSubject = 25, + CancelOwnDataRequest = 26, + CancelDataRequest = 27, + RevokeOwnDataExport = 28, + RevokeDataExport = 29, + CreateRetainedDataExport = 30, + CancelRetainedDataRequest = 31, + CreateOwnDataErasure = 32, + CreateDataErasureForSubject = 33, + CreateRetainedDataErasure = 34, + RevokeRetainedDataExport = 35, + CreateOwnAccountClosure = 36, + CreateRetainedAccountClosure = 37, } internal sealed record ProtectedAdministrationDescriptor( @@ -49,6 +64,41 @@ 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 => IsDataExportCreation || IsDataErasureCreation || IsAccountClosureCreation; + + internal bool IsDataExportCreation => Operation is ProtectedAdministrationOperation.CreateOwnDataExport + or ProtectedAdministrationOperation.CreateDataExportForSubject or ProtectedAdministrationOperation.CreateRetainedDataExport; + + /// ADR-0106 § 11: an erasure is accepted scheduled, executed once its cancellable window ends. + internal bool IsDataErasureCreation => Operation is ProtectedAdministrationOperation.CreateOwnDataErasure + or ProtectedAdministrationOperation.CreateDataErasureForSubject or ProtectedAdministrationOperation.CreateRetainedDataErasure; + + /// + /// ADR-0106 § 11, ADR-0107 § 7: a closure is accepted scheduled; the person alone files it, so it has no + /// administrator operation. + /// + internal bool IsAccountClosureCreation => Operation is ProtectedAdministrationOperation.CreateOwnAccountClosure + or ProtectedAdministrationOperation.CreateRetainedAccountClosure; + + /// + /// 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 is not (ProtectedAdministrationOperation.CreateRetainedDataExport + or ProtectedAdministrationOperation.CreateRetainedDataErasure or ProtectedAdministrationOperation.CreateRetainedAccountClosure); + + /// 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.CreateRetainedDataErasure or ProtectedAdministrationOperation.CreateRetainedAccountClosure + or ProtectedAdministrationOperation.CancelRetainedDataRequest or ProtectedAdministrationOperation.RevokeRetainedDataExport; + + internal int SuccessStatus => IsDataRequestCreation ? StatusCodes.Status202Accepted + : Creates ? StatusCodes.Status201Created : StatusCodes.Status200OK; private static readonly ProtectedAdministrationDescriptor[] Descriptors = Enum.GetValues().Select(For).ToArray(); @@ -84,6 +134,20 @@ 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), + ProtectedAdministrationOperation.CreateRetainedDataExport => new(operation, typeof(CreateRetainedDataExportCommand), IdempotencyReplayTargetKind.DataSubjectRequest, true), + ProtectedAdministrationOperation.CancelRetainedDataRequest => new(operation, typeof(CancelRetainedDataRequestCommand), IdempotencyReplayTargetKind.DataSubjectRequest), + ProtectedAdministrationOperation.CreateOwnDataErasure => new(operation, typeof(CreateOwnDataErasureCommand), IdempotencyReplayTargetKind.DataSubjectRequest, true), + ProtectedAdministrationOperation.CreateDataErasureForSubject => new(operation, typeof(CreateDataErasureForSubjectCommand), IdempotencyReplayTargetKind.DataSubjectRequest, true), + ProtectedAdministrationOperation.CreateRetainedDataErasure => new(operation, typeof(CreateRetainedDataErasureCommand), IdempotencyReplayTargetKind.DataSubjectRequest, true), + ProtectedAdministrationOperation.RevokeRetainedDataExport => new(operation, typeof(RevokeRetainedDataExportCommand), IdempotencyReplayTargetKind.DataSubjectRequest), + ProtectedAdministrationOperation.CreateOwnAccountClosure => new(operation, typeof(CreateOwnAccountClosureCommand), IdempotencyReplayTargetKind.DataSubjectRequest, true), + ProtectedAdministrationOperation.CreateRetainedAccountClosure => new(operation, typeof(CreateRetainedAccountClosureCommand), IdempotencyReplayTargetKind.DataSubjectRequest, true), _ => throw new ArgumentOutOfRangeException(nameof(operation)), }; @@ -112,6 +176,20 @@ 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, + CreateRetainedDataExportCommand => ProtectedAdministrationOperation.CreateRetainedDataExport, + CancelRetainedDataRequestCommand => ProtectedAdministrationOperation.CancelRetainedDataRequest, + CreateOwnDataErasureCommand => ProtectedAdministrationOperation.CreateOwnDataErasure, + CreateDataErasureForSubjectCommand => ProtectedAdministrationOperation.CreateDataErasureForSubject, + CreateRetainedDataErasureCommand => ProtectedAdministrationOperation.CreateRetainedDataErasure, + RevokeRetainedDataExportCommand => ProtectedAdministrationOperation.RevokeRetainedDataExport, + CreateOwnAccountClosureCommand => ProtectedAdministrationOperation.CreateOwnAccountClosure, + CreateRetainedAccountClosureCommand => ProtectedAdministrationOperation.CreateRetainedAccountClosure, _ => null, }; @@ -137,6 +215,19 @@ 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, + CreateRetainedDataExportCommand => null, + CancelRetainedDataRequestCommand command => command.ExpectedVersion, + CreateOwnDataErasureCommand => null, + CreateDataErasureForSubjectCommand => null, + CreateRetainedDataErasureCommand => null, + RevokeRetainedDataExportCommand command => command.ExpectedArtifactVersion, + CreateOwnAccountClosureCommand => null, + CreateRetainedAccountClosureCommand => null, _ => throw new ArgumentException("The protected operation is not registered.", nameof(request)), }; internal bool TryReadPrecondition(HttpRequest request, out long? expected) @@ -155,6 +246,14 @@ 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"), + ProtectedAdministrationOperation.CreateOwnDataErasure => "/api/v1/identity/me/data-requests/" + id.ToString("D"), + ProtectedAdministrationOperation.CreateDataErasureForSubject => "/api/v1/identity/data-requests/" + id.ToString("D"), + ProtectedAdministrationOperation.CreateOwnAccountClosure => "/api/v1/identity/me/data-requests/" + id.ToString("D"), + ProtectedAdministrationOperation.CreateRetainedDataExport or ProtectedAdministrationOperation.CreateRetainedDataErasure + or ProtectedAdministrationOperation.CreateRetainedAccountClosure => + 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 f1c922b81..565d4190a 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,30 @@ 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), + CreateRetainedDataExportCommand command => DataRequest(await sender.Send(command, cancellationToken), null), + CancelRetainedDataRequestCommand command => DataRequest(await sender.Send(command, cancellationToken), command.RequestId), + CreateOwnDataErasureCommand command => DataRequest(await sender.Send(command, cancellationToken), null), + CreateDataErasureForSubjectCommand command => DataRequest(await sender.Send(command, cancellationToken), null), + CreateRetainedDataErasureCommand command => DataRequest(await sender.Send(command, cancellationToken), null), + RevokeRetainedDataExportCommand command => Artifact(await sender.Send(command, cancellationToken), command.RequestId), + CreateOwnAccountClosureCommand command => DataRequest(await sender.Send(command, cancellationToken), null), + CreateRetainedAccountClosureCommand command => DataRequest(await sender.Send(command, cancellationToken), null), _ => 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 +144,12 @@ 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") + + (descriptor.IsDataErasureCreation ? "\",\"kind\":\"erasure\",\"status\":\"scheduled\"" + : descriptor.IsAccountClosureCreation ? "\",\"kind\":\"closure\",\"status\":\"scheduled\"" + : "\",\"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,10 +159,10 @@ 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); + 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 2d7bd56eb..95b4f81e4 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; @@ -271,10 +271,10 @@ 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) + 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 ac5520a29..6c1d08526 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,20 @@ 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.CreateOwnDataErasure + or ProtectedAdministrationOperation.CreateOwnAccountClosure or ProtectedAdministrationOperation.CancelOwnDataRequest + or ProtectedAdministrationOperation.RevokeOwnDataExport => sender.Send(new ReadOwnDataRequestReceiptQuery(target.Id), cancellationToken), + ProtectedAdministrationOperation.CreateDataExportForSubject or ProtectedAdministrationOperation.CreateDataErasureForSubject + or ProtectedAdministrationOperation.CancelDataRequest + or ProtectedAdministrationOperation.RevokeDataExport => sender.Send(new ReadDataRequestReceiptQuery(target.Id), cancellationToken), + ProtectedAdministrationOperation.CreateRetainedDataExport or ProtectedAdministrationOperation.CreateRetainedDataErasure + or ProtectedAdministrationOperation.CreateRetainedAccountClosure or ProtectedAdministrationOperation.CancelRetainedDataRequest + or ProtectedAdministrationOperation.RevokeRetainedDataExport when http?.Features.Get()?.Request is ReadRetainedDataRequestReceiptQuery retained + && retained.RequestId == target.Id => sender.Send(retained, cancellationToken), + ProtectedAdministrationOperation.CreateRetainedDataExport or ProtectedAdministrationOperation.CreateRetainedDataErasure + or ProtectedAdministrationOperation.CreateRetainedAccountClosure or ProtectedAdministrationOperation.CancelRetainedDataRequest + or ProtectedAdministrationOperation.RevokeRetainedDataExport => + 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 b6c4ed49b..325fbb511 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; @@ -44,8 +45,20 @@ 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 CreateRetainedDataErasureCommand + or CreateRetainedAccountClosureCommand or CancelRetainedDataRequestCommand or RevokeRetainedDataExportCommand) + || 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 @@ -64,12 +77,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"); } @@ -83,6 +97,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"); @@ -95,19 +112,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, @@ -139,6 +160,15 @@ or ProtectedAdministrationOperation.PublishCustomFieldRevision or ProtectedAdmin or ProtectedAdministrationOperation.DiscardCustomFieldDraft => typeof(ReadCustomFieldDefinitionReceiptQuery), ProtectedAdministrationOperation.GrantOwnFieldConsent => typeof(ReadOwnGrantedFieldConsentReceiptQuery), ProtectedAdministrationOperation.WithdrawOwnFieldConsent => typeof(ReadOwnWithdrawnFieldConsentReceiptQuery), + ProtectedAdministrationOperation.CreateOwnDataExport or ProtectedAdministrationOperation.CreateOwnDataErasure + or ProtectedAdministrationOperation.CreateOwnAccountClosure or ProtectedAdministrationOperation.CancelOwnDataRequest + or ProtectedAdministrationOperation.RevokeOwnDataExport => typeof(ReadOwnDataRequestReceiptQuery), + ProtectedAdministrationOperation.CreateDataExportForSubject or ProtectedAdministrationOperation.CreateDataErasureForSubject + or ProtectedAdministrationOperation.CancelDataRequest + or ProtectedAdministrationOperation.RevokeDataExport => typeof(ReadDataRequestReceiptQuery), + ProtectedAdministrationOperation.CreateRetainedDataExport or ProtectedAdministrationOperation.CreateRetainedDataErasure + or ProtectedAdministrationOperation.CreateRetainedAccountClosure or ProtectedAdministrationOperation.CancelRetainedDataRequest + or ProtectedAdministrationOperation.RevokeRetainedDataExport => typeof(ReadRetainedDataRequestReceiptQuery), _ => throw new ArgumentOutOfRangeException(nameof(operation)), }; @@ -159,7 +189,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; @@ -172,7 +203,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 new file mode 100644 index 000000000..8f8053702 --- /dev/null +++ b/backend/src/LearnStack.Api/Identity/DataRequestDocumentTransformer.cs @@ -0,0 +1,601 @@ +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"]; + + /// 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 gone (revoked, expired, purged, or sealed under a key the export key " + + "ring no longer holds) and only a new export helps; with data_export_ticket_limit, a ticket bound is reached (see the mint's 409)."; + + /// 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 = + [ + new("identity/me/data-requests/exports", HttpMethod.Post, "CreateOwnDataExport", Shape.Create, "DataRequestAcceptedResponse", "EmptyAdministrationInput", true), + new("identity/me/data-requests/erasures", HttpMethod.Post, "CreateOwnDataErasure", Shape.Create, "DataErasureAcceptedResponse", "EmptyAdministrationInput", true), + new("identity/me/data-requests/closures", HttpMethod.Post, "CreateOwnAccountClosure", Shape.Create, "AccountClosureAcceptedResponse", "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/erasures", HttpMethod.Post, "CreateDataErasureForSubject", Shape.Create, "DataErasureAcceptedResponse", "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); + } + 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/erasures", HttpMethod.Post, "CreateRetainedDataErasure", Shape.Create, "DataErasureAcceptedResponse", "EmptyAdministrationInput", true), + new("identity/data-request-entry/closures", HttpMethod.Post, "CreateRetainedAccountClosure", Shape.Create, "AccountClosureAcceptedResponse", "EmptyAdministrationInput", true), + new("identity/data-request-entry/cancellations", HttpMethod.Post, "CancelRetainedDataRequest", Shape.Mutation, "AdministrationVersionReceipt", "RetainedDataRequestTargetInput", true), + new("identity/data-request-entry/revocations", HttpMethod.Post, "RevokeRetainedDataExport", 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. Paging is forward only: follow pageInfo.nextCursor; there is no previous page.", + }); + } + 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 = IfMatchDescription(contract), + }); + } + 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 when Closure(contract) => ClosureAccepted + " Read the group's requests for its status while the account still works.", + Shape.Create => Erasure(contract) + ? "Accepted: the request's initial resource, scheduled. Its erasure runs as a background job once its " + WindowHours + "-hour cancellable window ends; read the group's requests for its status." + : "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 " + ChunkSize + " 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.", + }, + 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." + + (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."), + ("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. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header)."), + ], methods); + if (contract.Body is not null && contract.Shape != Shape.Chunk) operation.Responses["409"] = new OpenApiResponse + { + Description = contract.Shape switch + { + Shape.Create when Erasure(contract) => OwnErasureConflict, + Shape.Create when Closure(contract) => ClosureConflict, + Shape.Create => "business_rule_violation: errors.$ carries lockey_request_already_active (a request of this kind is still active in the group), lockey_blocked_hold" + SubjectNotAdmitted + "; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", + Shape.Ticket => TicketConflict, + _ when contract.Name.StartsWith("Cancel", StringComparison.Ordinal) => OwnCancelConflict, + _ when contract.Name.StartsWith("Revoke", StringComparison.Ordinal) => "concurrency_conflict for a valid stale artifact 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.", + _ => "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 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.", + "CreateRetainedDataErasure" => "The subject files an erasure of their own data in one retained group (ADR-0106 § 3, § 9; ADR-0107 § 5): the path of a Suspended person and of one whose Membership was revoked. The request is scheduled and its job runs once the " + WindowHours + "-hour window ends; until then it can be cancelled. Refused when the subject holds no Membership of any status there, while the subject is the tenant's only eligible tenant-wide administrator (tenant-wide group) or while a hold applies. Strict empty JSON object. MUST audited.", + "CreateRetainedAccountClosure" => "The subject files the closure of their whole account from one retained group, its originating group (ADR-0106 § 3, § 9; ADR-0107 § 7): the path of a Suspended person and of one whose Membership was revoked. " + ClosureEffect + " Refused when the subject holds no Membership of any status there, while another closure of the subject is active in the group, or while a hold applies. Strict empty JSON object. MUST audited.", + "CancelRetainedDataRequest" => "The subject cancels their own request in one retained group: a requested export (requested to cancelled), or a scheduled erasure before its execution time (scheduled to cancelled). Strict JSON object with requestId only. MUST audited." + ClosureCancellation, + "RevokeRetainedDataExport" => "The subject revokes an unexpired available artifact of their own request in one retained group, which deletes its chunks at once; the metadata stays as the receipt (ADR-0107 § 4). If-Match carries the ARTIFACT version: the receipt's artifact.version, not the request's. Strict JSON object with requestId only. MUST audited.", + "MintRetainedDataExportTicket" => "The subject mints a " + TicketMinutes + "-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; + 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; 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) + { + 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 = IfMatchDescription(contract), + }); + } + 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 when Closure(contract) => ClosureAccepted + " Read the Location for its status while the account still works.", + Shape.Create => Erasure(contract) + ? "Accepted: the request's initial resource, scheduled. Its erasure runs as a background job once its " + WindowHours + "-hour cancellable window ends; read the Location for its status." + : "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 " + ChunkSize + " 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.", + }, + 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." + + (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."), + ("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. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header)."), + ], methods); + if (contract.Body is not null) operation.Responses["409"] = new OpenApiResponse + { + Description = contract.Shape switch + { + Shape.Create when Erasure(contract) => contract.Own ? OwnErasureConflict : AdministratorErasureConflict, + Shape.Create when Closure(contract) => ClosureConflict, + Shape.Create when !contract.Own => "business_rule_violation: errors.$ carries lockey_request_already_active (a request of this kind is still active in the group), lockey_blocked_hold, lockey_subject_export_available (the person holds a readable export artifact in the group, of any origin, which this export would revoke: it can be filed once that artifact is revoked or has expired)" + SubjectNotAdmitted + "; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", + Shape.Create => "business_rule_violation: errors.$ carries lockey_request_already_active (a request of this kind is still active in the group), lockey_blocked_hold" + SubjectNotAdmitted + "; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state.", + Shape.Ticket => TicketConflict, + Shape.Chunk => "Never: a chunk refusal is not_found.", + _ when contract.Name.StartsWith("Cancel", StringComparison.Ordinal) => contract.Own ? OwnCancelConflict : CancelConflict, + _ => "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 (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 + { + 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.", + }; + } + + /// + /// The mint's two refusals, told apart (ADR-0107 § 4): gone means file a new export; a bound means wait, or, for the + /// per-artifact bound, that the artifact's downloads are spent. The numbers are 's. + /// + private static readonly string ChunkSize = string.Create(System.Globalization.CultureInfo.InvariantCulture, + $"{DataRequestLimits.ChunkPlaintextBytes / 1024} KiB"); + + private static readonly string TicketMinutes = string.Create(System.Globalization.CultureInfo.InvariantCulture, + $"{DataRequestLimits.TicketLifetime.TotalMinutes}"); + + private static readonly string WindowHours = string.Create(System.Globalization.CultureInfo.InvariantCulture, + $"{DataRequestLimits.CancellationWindow.TotalHours}"); + + /// + /// The refusal every creation shares (ADR-0107 § 7): the request guard reads the subject's User status under the User + /// fence, so a filing that reaches it after the person's account began closing stores nothing. + /// + private const string SubjectNotAdmitted = ", or lockey_subject_not_admitted (the person's account is closing or closed: " + + "nothing is filed)"; + + /// The creation refusals of an erasure the person files (ADR-0106 § 3, § 7): each a closed code in errors.$. + private const string OwnErasureConflict = "business_rule_violation: errors.$ carries lockey_request_already_active (an erasure is still active in the group), " + + "lockey_blocked_last_administrator (the person is the tenant's only eligible tenant-wide administrator; another must be appointed first), " + + "lockey_blocked_hold" + SubjectNotAdmitted + "; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state."; + + /// The creation refusals of an erasure an administrator files for a Membership: the person's own, and its eligibility. + private const string AdministratorErasureConflict = "business_rule_violation: errors.$ carries lockey_request_already_active (an erasure is still active in the group), " + + "lockey_blocked_last_administrator (the person is the tenant's only eligible tenant-wide administrator; another must be appointed first), " + + "lockey_blocked_hold, lockey_subject_membership_current (the person still holds an Active or Suspended Membership in the group: revoke it first)" + + SubjectNotAdmitted + "; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state."; + + private static bool Erasure(Contract contract) => contract.Name.Contains("Erasure", StringComparison.Ordinal); + + private static bool Closure(Contract contract) => contract.Name.Contains("Closure", StringComparison.Ordinal); + + /// What filing a closure does, stated on both filing routes (ADR-0106 § 11; ADR-0107 § 7). + private static readonly string ClosureEffect = "An account closure ends the person's account in every tenant and organization where they hold a Membership, " + + "not only in this group. The request is scheduled with its execution time " + WindowHours + " hours after it is filed and holds the frozen snapshot " + + "of the subject's Memberships of any status in the group. No job is queued: an operator confirms the request with the person and Begins it at or " + + "after its execution time, and the person can cancel it until that Begin commits. Once begun it is irreversible: the account stops working at " + + "once, the person's data is erased group by group, and the sign-in account is removed when an operator finalizes the closure. No in-product " + + "status remains afterwards; the person can read the receipt only while the account still works."; + + /// How the subject cancels a closure, appended to both cancellation routes (ADR-0106 § 11). + private const string ClosureCancellation = " A scheduled closure is cancelled the same way (scheduled to cancelled) until an operator's Begin commits, also after its " + + "execution time; a begun closure is fulfilling and cannot be cancelled."; + + /// The accepted answer of a closure's filing. + private static readonly string ClosureAccepted = "Accepted: the request's initial resource, scheduled. No job runs it: an operator may Begin it from its " + + "executeAt, and until that Begin commits it can be cancelled."; + + /// The creation refusals of a closure: its originating group's structure and a hold; never the last administrator, which its Begin judges. + private const string ClosureConflict = "business_rule_violation: errors.$ carries lockey_request_already_active (another closure of the person is still " + + "active in the group), lockey_blocked_hold" + SubjectNotAdmitted + + "; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state."; + + /// A cancellation's refusals (ADR-0106 § 8, § 11). + private const string CancelConflict = "concurrency_conflict for a valid stale version; business_rule_violation with errors.$ carrying lockey_data_request_window_ended (an erasure's cancellable window has ended and it runs now) or lockey_data_request_not_cancellable (the request is no longer one a cancellation admits: it already ended, or an export already started); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state."; + + /// The subject's cancellation also reaches their closure (ADR-0106 § 11, ADR-0107 § 7). + private const string OwnCancelConflict = CancelConflict + + " A closure is never window_ended: its not_cancellable means an operator's Begin committed, after which the closure is irreversible."; + + /// The precondition a mutation names: a revocation's is its artifact's version, every other one the request's. + private static string IfMatchDescription(Contract contract) => contract.Name.StartsWith("Revoke", StringComparison.Ordinal) + ? "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."; + + private static readonly string TicketConflict = string.Create(System.Globalization.CultureInfo.InvariantCulture, + $"business_rule_violation. errors.artifact carries data_export_unavailable when the request has no available, unexpired artifact " + + $"or the key it was sealed under is no longer in the export key ring: the artifact is gone and only a new export helps. It carries " + + $"data_export_ticket_limit when a ticket bound is reached: this session already holds {DataRequestLimits.MaximumOpenTicketsPerBinding} " + + $"unconsumed, unexpired tickets over the artifact (wait until one is consumed by its final chunk or expires, " + + $"{DataRequestLimits.TicketLifetime.TotalMinutes} minutes after it was minted; a ticket of an earlier, refreshed credential does not " + + $"count), or {DataRequestLimits.MaximumTicketsPerArtifact} tickets have been minted over the artifact in all, which is final: " + + $"file a new export."); + + private static string Description(Contract contract) => contract.Shape switch + { + Shape.Create when Closure(contract) => "The subject files the closure of their whole account from the session's group, its originating group (ADR-0106 § 3; ADR-0107 § 7). Only the person files one; no administrator can file, read or cancel a closure. Requires an Active Membership in exactly that group; no permission key. " + ClosureEffect + " Refused while another closure of the subject is active in the group or while a hold applies. Strict empty JSON object. MUST audited.", + Shape.Create when contract.Own && Erasure(contract) => "The subject files an erasure of their own data in the session's group (ADR-0106 § 3; ADR-0107 § 5). Requires an Active Membership in exactly that group; no permission key. The request is scheduled, holds the frozen snapshot of the subject's Memberships of any status in the group, and its job is submitted on the same transaction, due when the " + WindowHours + "-hour cancellable window ends. The job then revokes the subject's export artifacts in the group, removes the Membership's role assignments, clears its profile, leaves it as a Revoked tombstone and revokes the pending invitations the subject issued there; the request then awaits the operator's privileged step. Refused while the subject is the tenant's only eligible tenant-wide administrator (tenant-wide group) or while a hold applies. Strict empty JSON object. MUST audited.", + Shape.Create when Erasure(contract) => "An administrator holding identity.membership.admin over the group files an erasure for the person who held the named Membership in the group, only once that Membership is Revoked: an Active or Suspended member is revoked first, by the separately audited administration act (ADR-0106 § 3). Never for themselves. The request is scheduled and runs when its " + WindowHours + "-hour window ends; the administrator who filed it may cancel it until then. Status and counts only. Strict JSON object with membershipId only. MUST audited.", + 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. When it completes, it revokes the subject's previous available artifact in the group, whoever filed that one. 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. Refused while the person holds a readable artifact in the group, of any origin, because the new export would revoke it. 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 with their counts (the list is partial: a kind absent from it is not counted, which is not zero) 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) or a scheduled erasure before its execution time (scheduled to cancelled). A request already fulfilling finishes. Strict empty JSON object. MUST audited." + ClosureCancellation + : "The administrator who filed a request cancels it: an export while it is still requested, an erasure before its execution time. 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 " + TicketMinutes + "-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()))); + schemas["DataRequestAcceptedResponse"] = Object(("id", Uuid()), ("kind", Enum("export")), ("status", Enum("requested")), ("version", Version())); + schemas["DataErasureAcceptedResponse"] = Object(("id", Uuid()), ("kind", Enum("erasure")), ("status", Enum("scheduled")), ("version", Version())); + schemas["AccountClosureAcceptedResponse"] = Object(("id", Uuid()), ("kind", Enum("closure")), ("status", Enum("scheduled")), ("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 })); + // The subject's receipt also describes their closure (ADR-0107 § 7); an administrator's never reaches one, so its + // schema keeps the erasure and export descriptions alone. + (string, IOpenApiSchema)[] Receipt(bool own) => + [ + ("id", Uuid()), ("kind", Enum([.. DataRequestCodes.Kinds.Codes])), ("origin", Enum([.. DataRequestCodes.Origins.Codes])), + ("status", With(Enum([.. DataRequestCodes.Statuses.Codes]), + "An erasure is scheduled until its window ends, then fulfilling and awaiting_privileged_step together (the job commits both at once, so fulfilling is not observed for an ordinary erasure), " + + "and completed once an operator finishes the audit redaction. After executeAt and before the job has run a request still reads scheduled: a client derives a 'due, running shortly' state from status and executeAt." + + (own ? " A closure has no job: it reads scheduled until an operator Begins it, at or after its executeAt, then fulfilling (the account no longer works, so its owner rarely reads it), and completed once an operator finalizes it; it is never blocked or failed." : ""))), + ("createdAt", DateTime()), + ("updatedAt", With(DateTime(true), "When the request last changed; for a cancelled, blocked or failed request this is when it ended.")), + ("completedAt", With(DateTime(true), "Set only for a completed request; a cancelled, blocked or failed request has none (read updatedAt).")), + ("lastRefusal", With(Nullable(Enum([.. DataRequestCodes.Refusals.Codes])), "The closed refusal code of the last refused attempt, without the lockey_ prefix of the 409 keys." + + (own ? " For a scheduled closure it is the reason an operator's Begin was refused (blocked_window, blocked_hold or blocked_last_administrator: another eligible tenant-wide administrator must be appointed first); the closure stays scheduled and cancellable." : ""))), + ("failureReason", Nullable(Enum([.. DataRequestCodes.FailureReasons.Codes]))), + ("retained", With(Array(Ref(document, "DataRequestRetainedResponse"), DataRequestCodes.RetainedKinds.Codes.Length), + "What the request retains, a partial list: a kind not listed is retained and not counted, never zero. The audit log's kinds appear only once the request is completed. invitation_record counts the offers the person issued or accepted; a pending offer addressed to their e-mail address is retained and not counted, because it is not locatable by person.")), + ("artifact", NullableRef(document, "DataExportArtifactResponse")), ("version", Version()), + ("executeAt", With(DateTime(true), "An erasure's cancellable window ends here and its job may run from here: the deadline for a cancellation, to be read from the receipt and never computed as createdAt plus a constant. Null for an export." + + (own ? " For a closure it is the earliest time an operator may Begin it, not a cancellation deadline: a scheduled closure can be cancelled until that Begin commits." : ""))), + ]; + schemas["OwnDataRequestResponse"] = Object(Receipt(own: true)); + schemas["OwnDataRequestPage"] = Object(("items", Array(Ref(document, "OwnDataRequestResponse"), 100)), ("pageInfo", Ref(document, "PageInfo"))); + schemas["DataRequestResponse"] = Object([.. Receipt(own: false), ("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["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" }), + ("bytes", new OpenApiSchema + { + Type = JsonSchemaType.String, + ContentEncoding = "base64", + MinLength = 4, + MaxLength = 174764, + Description = "Base64 of one chunk of the decrypted bundle, at most " + ChunkSize + " 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." + })); + } + + 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 With(OpenApiSchema schema, string description) + { + schema.Description = description; + return schema; + } + + 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/DataRequestEntryController.cs b/backend/src/LearnStack.Api/Identity/DataRequestEntryController.cs new file mode 100644 index 000000000..6d01bd257 --- /dev/null +++ b/backend/src/LearnStack.Api/Identity/DataRequestEntryController.cs @@ -0,0 +1,135 @@ +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 retained own-scope native entry of the subject's data requests (ADR-0106 § 9, ADR-0107 § 4, § 5, § 7): nine 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("erasures", Name = "CreateRetainedDataErasure")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.RetainedDataErasureCreateOperation)] + [OperationPolicy(typeof(CreateRetainedDataErasureCommand))] + [Idempotent(ProtectedAdministrationOperation.CreateRetainedDataErasure)] + [ProducesResponseType(StatusCodes.Status202Accepted)] + public async Task CreateErasure(CancellationToken cancellationToken) + { + if (HttpContext.Features.Get()?.Request is not CreateRetainedDataErasureCommand request) return AdministrationHttpInput.Invalid(); + return await ProtectedAdministrationResult.ExecuteAsync(HttpContext, sender, tenant, request, cancellationToken); + } + + [HttpPost("closures", Name = "CreateRetainedAccountClosure")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.RetainedAccountClosureCreateOperation)] + [OperationPolicy(typeof(CreateRetainedAccountClosureCommand))] + [Idempotent(ProtectedAdministrationOperation.CreateRetainedAccountClosure)] + [ProducesResponseType(StatusCodes.Status202Accepted)] + public async Task CreateClosure(CancellationToken cancellationToken) + { + if (HttpContext.Features.Get()?.Request is not CreateRetainedAccountClosureCommand 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("revocations", Name = "RevokeRetainedDataExport")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.RetainedDataExportRevokeOperation)] + [OperationPolicy(typeof(RevokeRetainedDataExportCommand))] + [Idempotent(ProtectedAdministrationOperation.RevokeRetainedDataExport)] + [ProducesResponseType(StatusCodes.Status200OK)] + public async Task RevokeExport(CancellationToken cancellationToken) + { + if (HttpContext.Features.Get()?.Request is not RevokeRetainedDataExportCommand 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(DataRequestProjection.Ticket(result.Value)); + } + + [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/Identity/DataRequestResponses.cs b/backend/src/LearnStack.Api/Identity/DataRequestResponses.cs new file mode 100644 index 000000000..b3b5d171a --- /dev/null +++ b/backend/src/LearnStack.Api/Identity/DataRequestResponses.cs @@ -0,0 +1,112 @@ +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); + +/// +/// The 202 answer to an erasure's creation: the request's initial resource, scheduled until its 24-hour window +/// ends (ADR-0106 § 10, § 11). +/// +public sealed record DataErasureAcceptedResponse(string Id, string Kind, string Status, string Version); + +/// +/// The 202 answer to an account closure's filing: the request's initial resource, scheduled; an operator may +/// Begin it from its execution time, and the person may cancel it until that Begin commits (ADR-0106 § 10, § 11; +/// ADR-0107 § 7). +/// +public sealed record AccountClosureAcceptedResponse(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. +/// +/// is a scheduled request's execution time: the end of an erasure's cancellable window, and the +/// earliest time an operator may Begin a closure, which stays cancellable until that Begin commits. +/// +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, string? ExecuteAt); + +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, string? ExecuteAt); + +public sealed record DataRequestPage(IReadOnlyList Items, PageInfo PageInfo); + +/// 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); + +/// 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), Instant(view.ExecuteAt)); + + 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(), Instant(view.ExecuteAt)); + + internal static DataExportTicketResponse Ticket(DataExportTicketGrant grant) => + new(grant.Ticket, Instant(grant.ExpiresAt), grant.ChunkCount, grant.ByteCount); + + 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 000000000..e417a0f03 --- /dev/null +++ b/backend/src/LearnStack.Api/Identity/DataRequestsController.cs @@ -0,0 +1,308 @@ +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, § 5): key-less +/// OwnDataRequest operations confined to the session's group. An export, an erasure and an account closure are +/// filed on distinct routes; reading, listing and cancelling a request are the same for every kind. 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); + } + + [HttpPost("erasures", Name = "CreateOwnDataErasure")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.OwnDataErasureCreateOperation)] + [OperationPolicy(typeof(CreateOwnDataErasureCommand))] + [Idempotent(ProtectedAdministrationOperation.CreateOwnDataErasure)] + [ProducesResponseType(StatusCodes.Status202Accepted)] + public async Task CreateErasure(CancellationToken cancellationToken) + { + using var body = await AdministrationHttpInput.ReadObjectAsync(HttpContext); + if (body is null) return AdministrationHttpInput.Invalid(); + return await ProtectedAdministrationResult.ExecuteAsync(HttpContext, sender, tenant, new CreateOwnDataErasureCommand(), cancellationToken); + } + + /// + /// ADR-0107 § 7: the person alone files the closure of their whole account from the session's group. Distinct from + /// an erasure by its route, its operation and its accepted resource; the administrator surface has no closure route. + /// + [HttpPost("closures", Name = "CreateOwnAccountClosure")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.OwnAccountClosureCreateOperation)] + [OperationPolicy(typeof(CreateOwnAccountClosureCommand))] + [Idempotent(ProtectedAdministrationOperation.CreateOwnAccountClosure)] + [ProducesResponseType(StatusCodes.Status202Accepted)] + public async Task CreateClosure(CancellationToken cancellationToken) + { + using var body = await AdministrationHttpInput.ReadObjectAsync(HttpContext); + if (body is null) return AdministrationHttpInput.Invalid(); + return await ProtectedAdministrationResult.ExecuteAsync(HttpContext, sender, tenant, new CreateOwnAccountClosureCommand(), 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) + { + // 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); + return result.IsFailure ? result.ToActionResult() + : Ok(DataRequestProjection.Ticket(result.Value)); + } +} + +/// +/// ADR-0107 § 4: one decrypted chunk through a ticket presented in the body, never in the URL. Not keyed and not +/// 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 +{ + [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) + { + // 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 + || !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); + } + + [HttpPost("erasures", Name = "CreateDataErasureForSubject")] + [Authorize(AuthenticationSchemes = TenantAuthenticationRegistration.Scheme, + Policy = OperationPolicyRequirement.Prefix + IdentityOperationPolicySource.DataErasureCreateOperation)] + [OperationPolicy(typeof(CreateDataErasureForSubjectCommand))] + [Idempotent(ProtectedAdministrationOperation.CreateDataErasureForSubject)] + [ProducesResponseType(StatusCodes.Status202Accepted)] + public async Task CreateErasure(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 CreateDataErasureForSubjectCommand(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/Platform/PlatformOperatorEndpoints.Closure.cs b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Closure.cs new file mode 100644 index 000000000..4de4262a7 --- /dev/null +++ b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Closure.cs @@ -0,0 +1,339 @@ +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Localization; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Results; + +namespace LearnStack.Api.Platform; + +/// What a closure's fan-out did, by participant group: closed counts, never an identifier. +/// Groups whose tenant allows ordinary work and whose organization, if any, is Active. +/// Served groups whose fan-out erasure this call created. +/// Served groups whose erasure was already in flight or awaiting its operator step. +/// Served groups with an erasure past its window and not yet run; a repeated Begin picks them up. +/// Served groups whose act did not report a start or an adoption; a repeated Begin retries them. +/// Groups of a tenant that does not allow ordinary work or of an organization not Active. +internal sealed record ClosureGroupsResponse(int Served, int Started, int Adopted, int Waiting, int Failed, int Unserved); + +/// +/// What a Begin that committed, or found its closure already begun, answers. complete is false while a served group +/// is waiting or failed: the closure stands, and the operator repeats Begin. +/// +/// begun or resumed. +/// The closure request. +/// The request's stored status, fulfilling. +/// Whether every served group is started or adopted. +/// The per-group counts. +/// The correlation id the result row and the fan-out's rows carry. +internal sealed record ClosureBeginResponse( + string Outcome, Guid RequestId, string Status, bool Complete, ClosureGroupsResponse Groups, string CorrelationId); + +/// Where a Finalize found the participant groups: closed counts, never an identifier. +/// Groups whose tenant allows ordinary work and whose organization, if any, is Active; a group that is no longer served but still holds an open closure erasure is required as well, so ready and pending count required groups. +/// Required groups whose erasure awaits the privileged step or completed during the closure. +/// Required groups that are not ready. +/// Groups of a tenant that does not allow ordinary work or of an organization not Active. +/// The participant erasures this call completed. +/// The person's closure requests this call completed, this one included. +internal sealed record ClosureFinalizeGroupsResponse( + int Served, int Ready, int Pending, int Unserved, int ErasuresCompleted, int ClosuresCompleted); + +/// One unserved group, which Phase 11's offboarding owns: a tenant and its organization, or none. +internal sealed record ClosureUnservedGroupResponse(Guid TenantId, Guid? OrganizationId); + +/// This call's redaction passes, summed: closed counts per column and per retained kind. +/// The participant tenants a pass ran over; the platform sentinel tenant's pass is in the totals. +/// The audit rows the passes selected. +/// The rows changed per redacted column; zero everywhere on a repeat. +/// The retained references per closed kind. +internal sealed record ClosureRedactionResponse( + int Tenants, long RowsSelected, IReadOnlyDictionary Redacted, IReadOnlyDictionary Retained); + +/// +/// What a Finalize that completed the closure, or found it completed, answers. A repeat of a finalization that had landed +/// answers already_finalized with the recorded result and no counts of its own. +/// +/// finalized or already_finalized. +/// The closure request. +/// The request's stored status, completed. +/// For the call that finalized, the per-group counts. +/// For the call that finalized, the unserved groups by tenant and organization. +/// For the call that finalized, its redaction passes summed. +/// The closure request's recorded result: the retained audit kinds and unserved_group. +/// The correlation id the intent and result rows carry. +internal sealed record ClosureFinalizeResponse( + string Outcome, Guid RequestId, string Status, ClosureFinalizeGroupsResponse? Groups, + IReadOnlyList UnservedGroups, ClosureRedactionResponse? Redaction, + IReadOnlyDictionary Retained, string CorrelationId); + +/// +/// The account-closure routes of the operator surface (ADR-0107 §§ 7 and 8): the Begin and the Finalize of one person's +/// global closure. Each runs the gate first, under platform.data_request.write. +/// +/// +/// +/// A Begin judges and moves the person and the request in one platform transaction and then fans the closure out: a +/// refusal answers 409 with the closed code it recorded on the request, a closure that could never finish (a person +/// past the closure's bounds, or an account the provider's port could never delete) answers 409 on +/// errors.participants or errors.provider with nothing recorded, a fan-out that did not reach every served +/// group answers 200 with complete: false, and a commit whose outcome is unknown answers 503 with +/// errors.outcome, after which a repeat is safe and resumes. +/// +/// +/// A Finalize redacts and records its intent, deletes the provider account, then closes the account and completes the +/// requests: a closure not ready answers 409 with the closed tallies on errors.groups, a provider that did not +/// delete answers 503 with the provider's closed outcome on errors.provider, and a repeat resumes from where +/// any earlier call stopped. +/// +/// +internal static partial class PlatformOperatorEndpoints +{ + private static void MapClosure(RouteGroupBuilder group) + { + Describe( + group.MapPost(DataRequestPrefix + "/{requestId:guid}/begin-closure", BeginClosureAsync) + .WithName("PlatformClosureBegin") + .WithSummary("Begin a person's global account closure: fence, judge, move the person to Closing and fan out.") + .WithDescription( + "One platform transaction takes the person's User fence and every participant tenant's fence, refuses " + + "blocked_window (the request's execution time has not come by the database clock), blocked_hold (a hold " + + "source reports one) or blocked_last_administrator (the person is the only eligible tenant-wide " + + "administrator of a participant tenant that allows ordinary work) by recording the code on the request, " + + "or moves the person's User from Active to Closing and the request from scheduled to fulfilling, and " + + "writes the result row under the platform sentinel with the ticket. After that commit the closure is " + + "fanned out to every served participant group, each in its own transaction. A group whose tenant does " + + "not allow ordinary work or whose organization is not Active is unserved and is not fanned out. Before " + + "any write, and with no code recorded, it refuses a closure that could never finish: a person with " + + string.Create(System.Globalization.CultureInfo.InvariantCulture, + $"Memberships in more than {ClosureLimits.MaximumParticipantGroups} participant groups, served or not, ") + + string.Create(System.Globalization.CultureInfo.InvariantCulture, + $"or with more than {ClosureLimits.MaximumTenantMemberships} Memberships in one participant tenant, ") + + "and a person whose identity-provider account the account-removal client could never delete. " + + "complete is false while a served group is waiting or failed: repeat Begin, which resumes, judges " + + "nothing again and adopts what started. Closing cannot be undone."), + typeof(ClosureBeginResponse)); + Describe( + group.MapPost(DataRequestPrefix + "/{requestId:guid}/finalize-closure", FinalizeClosureAsync) + .WithName("PlatformClosureFinalize") + .WithSummary("Finalize a begun closure: redact the person's audit rows, delete the provider account, close the account.") + .WithDescription( + "Allowed once every served participant group's newest erasure of the person awaits its privileged step or " + + "completed during the closure; a group whose tenant does not allow ordinary work or whose organization is " + + "not Active is unserved and needs none. The first platform transaction takes the person's fences, redacts " + + "the person's audit rows in every participant tenant and in the platform sentinel tenant, and commits with " + + "the intent row that carries the summed counts. The person's identity-provider account is then deleted; a " + + "missing account is success. The second transaction takes the fences again, moves the account from Closing " + + "to Closed with the raw provider subject removed, completes every participant erasure awaiting the " + + "privileged step, this closure and every other open closure of the person, and writes the result row under " + + "the platform sentinel with the ticket. The first transaction holds the person's User fence alone, so no " + + "participant tenant waits for the redaction; the second holds every participant tenant's fence too. A " + + "group made unserved after the Begin whose fan-out erasure is still open stays required until it awaits " + + "its privileged step. A provider that did not delete answers 503 and leaves the closure " + + "fulfilling; every step is idempotent, so a repeat resumes, and a repeat after the act landed answers " + + "already_finalized and writes nothing."), + typeof(ClosureFinalizeResponse)); + } + + private static async Task BeginClosureAsync( + Guid requestId, HttpContext http, IPlatformOperatorGate gate, IAccountClosureOperatorOperations operations, + ILoggerFactory loggers, CancellationToken cancellationToken) + { + var operation = PlatformOperations.ClosureBegin; + var (body, refusal, admission) = await AdmitWithBodyAsync( + http, gate, operation, request => request.Ticket, cancellationToken); + if (refusal is not null) + { + return refusal; + } + + // A request identifier is a UUIDv7 the database assigned; anything else names no request and reaches nothing. + if (body is null || !IsOperatorId(requestId)) + { + return Problem(http, StatusCodes.Status400BadRequest, "lockey_validation_failed"); + } + + try + { + var result = await operations.BeginAsync(admission!, requestId, cancellationToken); + PlatformOperatorMetrics.DataRequest(operation, ClosureOutcomeToken(result)); + return result.Outcome switch + { + ClosureBeginOutcome.Begun or ClosureBeginOutcome.Resumed => Results.Ok(new ClosureBeginResponse( + result.Outcome == ClosureBeginOutcome.Begun ? "begun" : "resumed", requestId, result.Status!, + result.Groups!.Complete, + new ClosureGroupsResponse( + result.Groups.Served, result.Groups.Started, result.Groups.Adopted, result.Groups.Waiting, + result.Groups.Failed, result.Groups.Unserved), + admission!.Operator.CorrelationId ?? http.TraceIdentifier)), + ClosureBeginOutcome.RefusedWindow or ClosureBeginOutcome.RefusedHold + or ClosureBeginOutcome.RefusedLastAdministrator => ResultProblem( + http, Rule("refusal", "lockey_data_request_closure_refused", result.Refusal)), + ClosureBeginOutcome.NotFound => Problem(http, StatusCodes.Status404NotFound, "lockey_not_found"), + ClosureBeginOutcome.NotClosure => ResultProblem(http, Rule("kind", "lockey_data_request_not_closure")), + ClosureBeginOutcome.NotBeginnable => ResultProblem( + http, Rule("status", "lockey_data_request_closure_not_beginnable", result.Status)), + ClosureBeginOutcome.SubjectNotAdmitted => ResultProblem( + http, Rule("account", "lockey_data_request_closure_account_closed")), + ClosureBeginOutcome.RefusedTooLarge => ResultProblem( + http, Rule("participants", "lockey_data_request_closure_too_large")), + ClosureBeginOutcome.RefusedProvider => ResultProblem(http, Rule("provider", "lockey_account_removal_unavailable")), + _ => throw new InvalidOperationException("A closure Begin outcome the route does not answer."), + }; + } + catch (AuditWriteFailedException failure) + { + PlatformOperatorMetrics.DataRequest(operation, "audit_unavailable"); + return AuditUnavailableProblem(http, loggers, operation, failure); + } + catch (OperatorRecoveryUnavailableException failure) + { + PlatformOperatorMetrics.DataRequest(operation, failure.CommitOutcomeUnknown ? "commit_unknown" : "unavailable"); + return UnavailableProblem(http, loggers, operation, failure); + } + catch (Exception) when (CountFailure(operation)) + { + throw; + } + } + + private static async Task FinalizeClosureAsync( + Guid requestId, HttpContext http, IPlatformOperatorGate gate, IAccountClosureOperatorOperations operations, + ILoggerFactory loggers, CancellationToken cancellationToken) + { + var operation = PlatformOperations.ClosureFinalize; + var (body, refusal, admission) = await AdmitWithBodyAsync( + http, gate, operation, request => request.Ticket, cancellationToken); + if (refusal is not null) + { + return refusal; + } + + // A request identifier is a UUIDv7 the database assigned; anything else names no request and reaches nothing. + if (body is null || !IsOperatorId(requestId)) + { + return Problem(http, StatusCodes.Status400BadRequest, "lockey_validation_failed"); + } + + try + { + var result = await operations.FinalizeAsync(admission!, requestId, cancellationToken); + PlatformOperatorMetrics.DataRequest(operation, FinalizeOutcomeToken(result.Outcome)); + return result.Outcome switch + { + ClosureFinalizeOutcome.Finalized or ClosureFinalizeOutcome.AlreadyFinalized => Results.Ok(new ClosureFinalizeResponse( + result.Outcome == ClosureFinalizeOutcome.Finalized ? "finalized" : "already_finalized", requestId, result.Status!, + result.Outcome == ClosureFinalizeOutcome.Finalized && result.Groups is { } groups + ? new ClosureFinalizeGroupsResponse( + groups.Served, groups.Ready, groups.Pending, groups.Unserved, groups.ErasuresCompleted, groups.ClosuresCompleted) + : null, + result.Outcome == ClosureFinalizeOutcome.Finalized + ? [.. (result.UnservedGroups ?? []).Select(group => + new ClosureUnservedGroupResponse(group.TenantId.Value, group.OrganizationId?.Value))] + : [], + result.Outcome == ClosureFinalizeOutcome.Finalized && result.Redaction is { } redaction + ? new ClosureRedactionResponse( + redaction.Tenants.Count, redaction.Total.RowsSelected, + redaction.Total.Redacted.ToDictionary( + entry => AuditRedactionCodes.Columns.ToCode(entry.Key), entry => entry.Value, StringComparer.Ordinal), + redaction.Total.Retained.ToDictionary( + entry => DataRequestCodes.RetainedKinds.ToCode(entry.Kind), entry => entry.Count, StringComparer.Ordinal)) + : null, + result.Retained ?? new Dictionary(StringComparer.Ordinal), + admission!.Operator.CorrelationId ?? http.TraceIdentifier)), + ClosureFinalizeOutcome.NotFound => Problem(http, StatusCodes.Status404NotFound, "lockey_not_found"), + ClosureFinalizeOutcome.NotClosure => ResultProblem(http, Rule("kind", "lockey_data_request_not_closure")), + ClosureFinalizeOutcome.NotFinalizable => ResultProblem( + http, Rule("status", "lockey_data_request_closure_not_finalizable", result.Status)), + ClosureFinalizeOutcome.GroupsPending => ResultProblem(http, GroupsPending(result.Groups!)), + ClosureFinalizeOutcome.ProviderRefused => ResultProblem(http, ProviderStopped("lockey_provider_refused")), + ClosureFinalizeOutcome.ProviderUnavailable => ResultProblem(http, ProviderStopped("lockey_provider_unavailable")), + ClosureFinalizeOutcome.ProviderUncertain => ResultProblem(http, ProviderStopped("lockey_provider_outcome_unknown")), + _ => throw new InvalidOperationException("A closure Finalize outcome the route does not answer."), + }; + } + catch (AuditWriteFailedException failure) + { + PlatformOperatorMetrics.DataRequest(operation, "audit_unavailable"); + return AuditUnavailableProblem(http, loggers, operation, failure); + } + catch (OperatorRecoveryUnavailableException failure) + { + PlatformOperatorMetrics.DataRequest(operation, failure.CommitOutcomeUnknown ? "commit_unknown" : "unavailable"); + if (failure.InnerException is AuditWriteFailedException durable) + { + // A MUST row refused after the provider step answers a retryable 503, but the audit store's failure is still the + // alert's signal: the act that failed at its last row had already deleted the account. + PlatformOperatorMetrics.AuditFailed(operation); + LogAuditRefused(loggers.CreateLogger(typeof(PlatformOperatorEndpoints).FullName!), durable); + } + + return UnavailableProblem(http, loggers, operation, failure); + } + catch (Exception) when (CountFailure(operation)) + { + throw; + } + } + + /// + /// A 409 with the closed tallies on errors.groups: how many served groups are ready and pending and how many are + /// unserved. No group is named, because a group's tenant and organization are the person's memberships. + /// + private static Error GroupsPending(ClosureFinalizeTally tally) => new( + new LocalizedMessage("lockey_business_rule_violation"), + new Dictionary>(StringComparer.Ordinal) + { + ["groups"] = [new LocalizedMessage( + "lockey_data_request_closure_groups_pending", + new Dictionary(StringComparer.Ordinal) + { + ["served"] = tally.Served.ToString(System.Globalization.CultureInfo.InvariantCulture), + ["ready"] = tally.Ready.ToString(System.Globalization.CultureInfo.InvariantCulture), + ["pending"] = tally.Pending.ToString(System.Globalization.CultureInfo.InvariantCulture), + ["unserved"] = tally.Unserved.ToString(System.Globalization.CultureInfo.InvariantCulture), + })], + }); + + /// + /// A 503 whose reason is the provider's closed outcome on errors.provider: the redaction and its intent row + /// committed, the closure stays fulfilling, and a repeat resumes. The status map is closed, so the reason travels + /// on the field of dependency_unavailable. + /// + private static Error ProviderStopped(string reason) => new( + new LocalizedMessage("lockey_dependency_unavailable"), + new Dictionary>(StringComparer.Ordinal) + { + ["provider"] = [new LocalizedMessage(reason)], + }); + + private static string FinalizeOutcomeToken(ClosureFinalizeOutcome outcome) => outcome switch + { + ClosureFinalizeOutcome.Finalized => "finalized", + ClosureFinalizeOutcome.AlreadyFinalized => "already_finalized", + ClosureFinalizeOutcome.NotFound => "not_found", + ClosureFinalizeOutcome.NotClosure => "not_closure", + ClosureFinalizeOutcome.NotFinalizable => "not_finalizable", + ClosureFinalizeOutcome.GroupsPending => "groups_pending", + ClosureFinalizeOutcome.ProviderRefused => "provider_refused", + ClosureFinalizeOutcome.ProviderUnavailable => "provider_unavailable", + ClosureFinalizeOutcome.ProviderUncertain => "provider_uncertain", + _ => throw new InvalidOperationException("A closure Finalize outcome the route does not count."), + }; + + private static string ClosureOutcomeToken(ClosureBeginResult result) => result.Outcome switch + { + ClosureBeginOutcome.Begun => result.Groups!.Complete ? "begun" : "begun_partial", + ClosureBeginOutcome.Resumed => result.Groups!.Complete ? "resumed" : "resumed_partial", + ClosureBeginOutcome.RefusedWindow => "blocked_window", + ClosureBeginOutcome.RefusedHold => "blocked_hold", + ClosureBeginOutcome.RefusedLastAdministrator => "blocked_last_administrator", + ClosureBeginOutcome.NotFound => "not_found", + ClosureBeginOutcome.NotClosure => "not_closure", + ClosureBeginOutcome.NotBeginnable => "not_beginnable", + ClosureBeginOutcome.SubjectNotAdmitted => "account_closed", + ClosureBeginOutcome.RefusedTooLarge => "refused_too_large", + ClosureBeginOutcome.RefusedProvider => "refused_provider", + _ => throw new InvalidOperationException("A closure Begin outcome the route does not count."), + }; +} diff --git a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.DataRequests.cs b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.DataRequests.cs new file mode 100644 index 000000000..a7b44eedf --- /dev/null +++ b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.DataRequests.cs @@ -0,0 +1,237 @@ +using System.ComponentModel.DataAnnotations; +using System.Globalization; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Platform; +using Microsoft.AspNetCore.Mvc; + +namespace LearnStack.Api.Platform; + +/// The optional ticket of a data-request act; the body is otherwise empty. +/// An optional ticket reference, 1 to 64 characters of [A-Za-z0-9._:/#-]. +internal sealed record DataRequestActBody( + [property: StringLength(64, MinimumLength = 1)] + [property: RegularExpression(TicketPattern.Value)] + string? Ticket); + +/// +/// What an erasure completion answers: the request's recorded retained kinds and, for the call that completed it, the +/// redaction's closed counts. A repeat of a completion that had landed answers already_completed and has no +/// counts. +/// +/// completed or already_completed. +/// The request. +/// The request's tenant, whose audit trail holds the result row. +/// When the request completed, by the database clock. +/// The audit rows the redaction selected; null on a repeat. +/// The rows changed per redacted column; null on a repeat. +/// The request's retained kinds and counts, the audit log's included. +/// The correlation id the result row carries. +internal sealed record ErasureCompletionResponse( + string Outcome, Guid RequestId, Guid TenantId, DateTimeOffset? CompletedAt, long? RowsSelected, + IReadOnlyDictionary? Redacted, IReadOnlyDictionary Retained, string CorrelationId); + +/// +/// The data-request routes of the operator surface (ADR-0107 § 8, ADR-0108): a metadata-only inspection of the requests +/// and artifacts that need a person, and the completion of an erasure's privileged step. Each runs the gate first. +/// +/// +/// A completion redacts, completes and records in one transaction: a refused state answers 409 and writes +/// nothing but the scope's entry row, a MUST row or a redaction that cannot finish answers 503 with nothing +/// changed, and a commit whose outcome is unknown answers 503 with errors.outcome, after which a repeat +/// is safe and answers already_completed if it had landed. +/// +internal static partial class PlatformOperatorEndpoints +{ + private const string DataRequestPrefix = "/data-requests"; + private static readonly string[] DataRequestInspectionParameters = ["state", "limit", "cursor", "ticket"]; + + /// + /// The closed list names of the inspection, in the order the document offers them; the first is the default. + /// + internal static readonly IReadOnlyList<(string Name, DataRequestInspectionState State)> DataRequestStates = + [ + ("awaiting_privileged_step", DataRequestInspectionState.AwaitingPrivilegedStep), + ("overdue_scheduled", DataRequestInspectionState.OverdueScheduled), + ("stuck_fulfilling", DataRequestInspectionState.StuckFulfilling), + ("expired_artifact", DataRequestInspectionState.ExpiredArtifact), + ]; + + private static void MapDataRequests(RouteGroupBuilder group) + { + DescribeInspection( + group.MapGet(DataRequestPrefix, InspectDataRequestsAsync) + .WithName("PlatformDataRequestInspect") + .WithSummary("List the data requests and export artifacts that need an operator, metadata only.") + .WithDescription( + "state is awaiting_privileged_step (erasures waiting for their audit redaction), overdue_scheduled " + + "(requests whose window ended and that nothing started), stuck_fulfilling (requests still fulfilling " + + string.Format(CultureInfo.InvariantCulture, "{0:0} hours", DataRequestLimits.StuckFulfillingAfter.TotalHours) + + " after they fell due) or expired_artifact (export artifacts past their expiry whose purge has not " + + "run). Oldest due first. Each item names the request, its kind, origin, status, tenant, organization, " + + "times and recorded refusal or failure code, and on expired_artifact the artifact; never the subject or " + + "any person data. A ticket is checked and recorded only on the platform scope's entry row."), + typeof(InspectionResponse)); + Describe( + group.MapPost(DataRequestPrefix + "/{requestId:guid}/complete-erasure", CompleteErasureAsync) + .WithName("PlatformErasureComplete") + .WithSummary("Complete an erasure awaiting its privileged step: redact the subject's audit rows and complete the request.") + .WithDescription( + "One transaction redacts ip_address, user_agent, actor_email and the subject's references in the audit " + + "states, moves the request from awaiting_privileged_step to completed and writes the result row in the " + + "request's tenant. actor_user_id, entity_id, metadata and the causation and correlation identifiers " + + "survive and are reported as retained kinds. A repeat after the act landed answers already_completed " + + "and writes no second row. A ticket is checked and recorded only on the platform scope's entry row, " + + "never on the tenant's row."), + typeof(ErasureCompletionResponse)); + } + + private static async Task InspectDataRequestsAsync( + [FromQuery] string? state, [FromQuery] string? limit, [FromQuery] string? cursor, [FromQuery] string? ticket, + HttpContext http, IPlatformOperatorGate gate, IDataRequestOperatorOperations operations, ILoggerFactory loggers, + CancellationToken cancellationToken) + { + var operation = PlatformOperations.DataRequestInspect; + var (refusal, admission) = await AdmitAsync(http, gate, operation, ticket, cancellationToken); + if (refusal is not null) + { + return refusal; + } + + if (!TryDataRequestState(state, out var parsedState)) + { + return InvalidParameter(http, "state"); + } + + if (!TryLimit(limit, out var size)) + { + return InvalidParameter(http, "limit"); + } + + // A misspelt parameter would otherwise be ignored and answer a different list; its name is the caller's text. + if (http.Request.Query.Keys.Any(key => !DataRequestInspectionParameters.Contains(key, StringComparer.Ordinal))) + { + return InvalidParameter(http, "query"); + } + + try + { + var page = await operations.InspectAsync( + admission!, new DataRequestInspectionQuery(parsedState, cursor, size), cancellationToken); + PlatformOperatorMetrics.DataRequest(operation, page is null ? "invalid_cursor" : "ok"); + return page is null + ? InvalidParameter(http, "cursor") + : Results.Ok(new InspectionResponse( + page.Items, new InspectionPageInfo(page.NextCursor, null, page.NextCursor is not null, false))); + } + catch (AuditWriteFailedException failure) + { + PlatformOperatorMetrics.DataRequest(operation, "audit_unavailable"); + return AuditUnavailableProblem(http, loggers, operation, failure); + } + catch (OperatorRecoveryUnavailableException failure) + { + PlatformOperatorMetrics.DataRequest(operation, failure.CommitOutcomeUnknown ? "commit_unknown" : "unavailable"); + return UnavailableProblem(http, loggers, operation, failure); + } + catch (Exception) when (CountFailure(operation)) + { + throw; + } + } + + private static async Task CompleteErasureAsync( + Guid requestId, HttpContext http, IPlatformOperatorGate gate, IDataRequestOperatorOperations operations, + ILoggerFactory loggers, CancellationToken cancellationToken) + { + var operation = PlatformOperations.ErasureComplete; + var (body, refusal, admission) = await AdmitWithBodyAsync( + http, gate, operation, request => request.Ticket, cancellationToken); + if (refusal is not null) + { + return refusal; + } + + // A request identifier is a UUIDv7 the database assigned; anything else names no request and reaches nothing. + if (body is null || !IsOperatorId(requestId)) + { + return Problem(http, StatusCodes.Status400BadRequest, "lockey_validation_failed"); + } + + try + { + var result = await operations.CompleteErasureAsync(admission!, requestId, cancellationToken); + PlatformOperatorMetrics.DataRequest(operation, ErasureOutcomeToken(result.Outcome)); + return result.Outcome switch + { + ErasureCompletionOutcome.Completed or ErasureCompletionOutcome.AlreadyCompleted => Results.Ok( + new ErasureCompletionResponse( + result.Outcome == ErasureCompletionOutcome.Completed ? "completed" : "already_completed", + requestId, result.TenantId!.Value, result.CompletedAt, result.Report?.RowsSelected, + result.Report?.Redacted.ToDictionary( + entry => AuditRedactionCodes.Columns.ToCode(entry.Key), entry => entry.Value, StringComparer.Ordinal), + result.Retained ?? new Dictionary(StringComparer.Ordinal), + admission!.Operator.CorrelationId ?? http.TraceIdentifier)), + ErasureCompletionOutcome.NotFound => Problem(http, StatusCodes.Status404NotFound, "lockey_not_found"), + ErasureCompletionOutcome.NotErasure => ResultProblem(http, Rule("kind", "lockey_data_request_not_erasure")), + ErasureCompletionOutcome.ClosureFanout => ResultProblem(http, Rule("origin", "lockey_data_request_closure_fanout")), + ErasureCompletionOutcome.NotAwaiting => ResultProblem( + http, Rule("status", "lockey_data_request_not_awaiting_privileged_step", result.Status)), + _ => throw new InvalidOperationException("An erasure completion outcome the route does not answer."), + }; + } + catch (AuditWriteFailedException failure) + { + PlatformOperatorMetrics.DataRequest(operation, "audit_unavailable"); + return AuditUnavailableProblem(http, loggers, operation, failure); + } + catch (OperatorRecoveryUnavailableException failure) + { + PlatformOperatorMetrics.DataRequest(operation, failure.CommitOutcomeUnknown ? "commit_unknown" : "unavailable"); + return UnavailableProblem(http, loggers, operation, failure); + } + catch (Exception) when (CountFailure(operation)) + { + throw; + } + } + + /// Counts an unexpected failure (a defect or a deployment fault, answered 500) and never swallows it. + private static bool CountFailure(PlatformOperation operation) + { + PlatformOperatorMetrics.DataRequest(operation, "failed"); + return false; + } + + private static string ErasureOutcomeToken(ErasureCompletionOutcome outcome) => outcome switch + { + ErasureCompletionOutcome.Completed => "completed", + ErasureCompletionOutcome.AlreadyCompleted => "already_completed", + ErasureCompletionOutcome.NotFound => "not_found", + ErasureCompletionOutcome.NotErasure => "not_erasure", + ErasureCompletionOutcome.ClosureFanout => "closure_fanout", + ErasureCompletionOutcome.NotAwaiting => "not_awaiting", + _ => throw new InvalidOperationException("An erasure completion outcome the route does not count."), + }; + + private static bool TryDataRequestState(string? text, out DataRequestInspectionState state) + { + state = DataRequestStates[0].State; + if (text is null) + { + return true; + } + + foreach (var (name, value) in DataRequestStates) + { + if (string.Equals(name, text, StringComparison.Ordinal)) + { + state = value; + return true; + } + } + + return false; + } +} diff --git a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs index a4c2721fa..82883b10f 100644 --- a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs +++ b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.Recovery.cs @@ -276,7 +276,7 @@ private static async Task RecoverAsync( LoggerMessage.Define( LogLevel.Warning, new EventId(7110, nameof(LogRecoveryUnavailable)), - "An operator owner (recovery, inspection or federation) was unavailable for {Operation}; the outcome unknown: {CommitOutcomeUnknown}."); + "An operator owner (recovery, inspection, federation or data request) was unavailable for {Operation}; the outcome unknown: {CommitOutcomeUnknown}."); /// /// A 503 whose cause the operator can find: the fault is logged, and the response names only whether the commit's diff --git a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs index 58ba6d94b..e5f22443c 100644 --- a/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs +++ b/backend/src/LearnStack.Api/Platform/PlatformOperatorEndpoints.cs @@ -70,6 +70,8 @@ internal static WebApplication MapLearnStackPlatformOperator(this WebApplication MapOnboarding(group); MapRecovery(group); MapFederation(group); + MapDataRequests(group); + MapClosure(group); return app; } diff --git a/backend/src/LearnStack.Api/Program.cs b/backend/src/LearnStack.Api/Program.cs index 87ad7a235..7f7801104 100644 --- a/backend/src/LearnStack.Api/Program.cs +++ b/backend/src/LearnStack.Api/Program.cs @@ -52,6 +52,8 @@ // ADR-0099: after persistence, so the confined federation adapter and guarded egress fetcher replace the // module's fail-closed defaults only when the federation admin client is configured. builder.Services.AddLearnStackFederationAdapter(builder.Configuration); +// ADR-0107 § 7: the confined account-removal adapter replaces the refusing default only when its client secret is configured. +builder.Services.AddLearnStackAccountRemovalAdapter(builder.Configuration); builder.Services.AddLearnStackRateLimiting(); // Register and activate the entire closed HTTP boundary together. Minimal hosting diff --git a/backend/src/LearnStack.Api/Tenancy/TenantResolverMiddleware.cs b/backend/src/LearnStack.Api/Tenancy/TenantResolverMiddleware.cs index 27a549fb8..cb1b61248 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/LearnStack.Api/Versioning/ApiVersioningExtensions.cs b/backend/src/LearnStack.Api/Versioning/ApiVersioningExtensions.cs index 615ecf9d0..02d91cc05 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.Application/Authorization/OperationAuthorizationCoordinator.cs b/backend/src/LearnStack.Application/Authorization/OperationAuthorizationCoordinator.cs index f66927190..185ca47c4 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/DataProtection/DataExportBundleBuilder.cs b/backend/src/LearnStack.Application/DataProtection/DataExportBundleBuilder.cs new file mode 100644 index 000000000..a000c4d86 --- /dev/null +++ b/backend/src/LearnStack.Application/DataProtection/DataExportBundleBuilder.cs @@ -0,0 +1,363 @@ +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 and the record's collection cap are checked first: a record that would pass one of them and the +/// ceiling is a truncation of its collection, 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. +/// +/// +/// A cap truncates, whatever the ceiling. Every declared section and collection cap is clamped to half the +/// configured ceiling (). At the default 16 MiB ceiling the audit section's 8 MiB is +/// unchanged; at the smallest admitted ceiling (1 MiB) an unclamped 8 MiB cap would never apply and a long audit +/// history would fail the request permanently with export_too_large. The clamp is a bound, not a budget: the +/// uncapped sections and two capped ones together can still reach the ceiling, and that genuine case stays +/// export_too_large. +/// +/// +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, options.MaxBytes), + CollectionCaps(participant, options.MaxBytes)); + 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)); + } + + /// A declared cap, clamped to half the ceiling so that it truncates before the ceiling refuses the bundle. + public static long EffectiveCap(long declared, long ceiling) => + declared is >= 1 and <= DataRequestLimits.MaximumBundleBytes + ? Math.Min(declared, ceiling / 2) + : throw new InvalidOperationException("A participant's export cap is outside the bundle's range."); + + private static long SectionCap(IUserDataParticipant participant, long ceiling) => + participant.ExportSectionCapBytes is { } cap ? EffectiveCap(cap, ceiling) : long.MaxValue; + + private static Dictionary CollectionCaps(IUserDataParticipant participant, long ceiling) + { + var caps = new Dictionary(StringComparer.Ordinal); + foreach (var (collection, cap) in participant.ExportCollectionCapBytes + ?? throw new InvalidOperationException("A participant's collection caps are a collection.")) + { + if (!DataRequestLimits.IsCollectionName(collection)) + { + throw new InvalidOperationException("A collection cap names a collection of its section."); + } + + caps.Add(collection, EffectiveCap(cap, ceiling)); + } + + return caps; + } + + 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, IReadOnlyDictionary collectionCaps) + : IUserDataExportWriter + { + private readonly HashSet _closedCollections = new(StringComparer.Ordinal); + private readonly HashSet _declared = new(StringComparer.Ordinal); + private string? _current; + private long _sectionBytes; + private long _collectionBytes; + private bool _closed; + + /// What the section may still append, before the open collection's own cap. + 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); + var collectionBytes = opening ? 0L : _collectionBytes; + if (_sectionBytes + cost > cap + || collectionCaps.TryGetValue(collection, out var collectionCap) && collectionBytes + cost > collectionCap) + { + 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; + _collectionBytes = collectionBytes + 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 000000000..de475adf2 --- /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 000000000..5beb192fa --- /dev/null +++ b/backend/src/LearnStack.Application/DataProtection/PlaintextSegmentBuffer.cs @@ -0,0 +1,169 @@ +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. 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 : 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; } + + /// 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) + { + // 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, take)); + _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++) + { + // 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].AsMemory(0, DataRequestLimits.ChunkPlaintextBytes); + } + } + + public void Dispose() + { + if (_disposed) + { + return; + } + + _disposed = true; + foreach (var segment in _segments) + { + Release(segment); + } + + CryptographicOperations.ZeroMemory(_scratch); + _segments.Clear(); + _scratch = []; + 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); + 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/UserDataParticipantRegistry.cs b/backend/src/LearnStack.Application/DataProtection/UserDataParticipantRegistry.cs new file mode 100644 index 000000000..c8b90c266 --- /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 000000000..47672dbeb --- /dev/null +++ b/backend/src/LearnStack.Application/DataProtection/UserDataProtectionRegistration.cs @@ -0,0 +1,41 @@ +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 +{ + /// 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.Application/Persistence/TransactionExecutionCoordinator.cs b/backend/src/LearnStack.Application/Persistence/TransactionExecutionCoordinator.cs index 48dcd35d8..9c4851aab 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 446409434..d6f1a7370 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.Audit/AuditRedactionExecutor.cs b/backend/src/LearnStack.Infrastructure.Audit/AuditRedactionExecutor.cs new file mode 100644 index 000000000..ad7a6c9fc --- /dev/null +++ b/backend/src/LearnStack.Infrastructure.Audit/AuditRedactionExecutor.cs @@ -0,0 +1,776 @@ +using System.Data; +using System.Data.Common; +using System.Text; +using System.Text.Json; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Secrets; +using Npgsql; +using NpgsqlTypes; + +namespace LearnStack.Infrastructure.Audit; + +/// +/// The one executor of privileged audit redaction, and the one file in the solution that updates audit_log +/// (ADR-0108 §§ 2, 4–6). +/// +/// +/// +/// Bound to its act. It refuses, before any statement, an admission that does not name a sanctioned operation +/// for the plan's kind (), an admission that has not opened a platform scope, a job frame, and a +/// connection that is not an open Npgsql one with its transaction; its first statement then refuses any role but the +/// platform's. It runs on the caller's connection and work transaction and never begins, commits or rolls back one, so +/// the redaction commits with what that transaction carries: an erasure's status change and result row, or a closure +/// Finalize's intent row (ADR-0108 § 8). +/// +/// +/// Selection (ADR-0108 § 4). A request the person filed, a closure's fan-out erasure and a closure's tenant pass +/// reach the whole tenant; an administrator's request reaches only rows whose organization_id is the group's (none +/// for the tenant-wide group). A row is selected when its actor is the subject, its entity_id is the subject or one +/// of the plan's Memberships (an erasure's frozen snapshot, or every Membership a closing person holds in the tenant), or +/// a declared path of its entity type holds one of them. The actor and entity branches are +/// index-served (ix_audit_log_actor_user_id_timestamp; ix_audit_log_tenant_id_entity_type_entity_id_timestamp +/// by a skip scan over the entity types). A payload reference has no index, so the tenant's rows are read in batches, +/// newest first along ix_audit_log_tenant_id_timestamp, each batch one statement: a cheap filter walks each +/// payload column once for either canonical spelling of the identifiers, and only a row it keeps is rewritten to decide +/// whether a declared path holds one. That test is the redaction itself, so a row is selected for its payload exactly +/// when the redaction changes its payload. The filter tests the walked strings against the spellings by array +/// containment for a plan of few identifiers and by a hashed set lookup from spellings, so a +/// closure's pass over a tenant where the person holds hundreds of Memberships costs what an erasure's pass costs. +/// +/// +/// The sentinel pass (ADR-0108 § 4). A closure's Finalize also reaches the platform sentinel tenant, whose rows +/// about a person are the global creation rows: the creation and every failed or undetermined attempt carry the subject +/// key in metadata.identity_subject_key, which is the only way to find an attempt, whose entity is an identifier +/// no User ever took. There a row is selected when its metadata carries the subject key, its actor is the subject, or it +/// is the subject's User as entity; nothing else of the sentinel tenant (the operators' entry, intent and result +/// rows, the issuer rebind's) is selected, because none of those names a person. The batches and the rewrite are the +/// tenant pass's, over the sentinel tenant: the key has no index, so each batch's rows are read once along +/// ix_audit_log_tenant_id_timestamp and the three predicates filter them. Its selection reads no payload, so its +/// batch boundary sizes none (@size_payload is false) and only the row cap ends a batch; the handful of rows it +/// selects are rewritten by the same bounded UPDATEs. A selected row is redacted at the same +/// declared paths; the creation rows' address, agent and e-mail are NULL by the insert guard and their captured +/// User holds its provider subject only as the capture's replacement, so today the pass selects and reports them +/// and changes a payload only where a declared path names the subject. +/// +/// +/// Batches. A batch is a half-open range of the key ("timestamp", id), descending: the next batch's upper +/// end is this batch's lower end, excluded, so the batches partition the tenant's rows committed before the act begins +/// and none of them is read twice or skipped, rows sharing a timestamp included (they are ordered by id, so a +/// boundary may fall inside them); a row committed while the act runs is read only if its key falls in a batch not yet +/// read. Its lower end is the first row, newest first, at which the batch holds rows or the +/// decompressed size of the three payload columns of its rows in the reach reaches : the work of +/// the selection and the UPDATE is proportional to the decompressed payload they walk, which a highly +/// compressible value can make tens of times its stored size, and they walk no payload outside the reach, nor any in the +/// sentinel pass, whose batches the row cap alone ends. A value stored +/// uncompressed is sized by pg_column_size without detoasting it; a compressed one is decompressed in memory to +/// measure it. A batch therefore holds at most rows and less than of +/// decompressed payload in the reach plus one row's, and a single row larger than the budget is a batch of its own. +/// +/// +/// Redaction (ADR-0108 § 5). On every selected row ip_address, user_agent and actor_email +/// become NULL. In before_state, after_state and changes a string at a declared path becomes +/// only when it is the subject's UserId (a +/// path) or one of the frozen Membership identifiers (a +/// path), compared case-insensitively; another person's value at the same +/// path is untouched. Each UPDATE names only the six columns the platform role may update, by primary key, locks +/// the rows it rewrites so a concurrent redaction of the same row is never overwritten, and changes a row only where a +/// value differs, so a re-run rewrites nothing. An elided payload ({"_elided":true,…}) holds no value, only its +/// length and digest, so it has no path to redact and no reference to report. +/// +/// +/// Report (ADR-0108 §§ 3, 6). Counts only: the rows selected; the rows changed per column, from the +/// UPDATEs' own RETURNING; the selected rows that keep the subject as actor +/// (audit_actor_reference) or as entity (audit_entity_reference); the rows of the reach whose metadata names +/// the subject, by the Audit participant's predicates, selected or not (audit_metadata_reference, exact for the +/// rows committed before the act begins, because the batches read every such row of the reach anyway), which in the +/// sentinel pass are the rows that carry the subject key; and, for an administrator's request, the rows outside the group +/// whose actor or entity is the subject or a Membership (unscoped_audit_rows, at least: payloads and metadata +/// outside the reach are not read). A closure's passes each reach their whole tenant, so none reports that last kind. +/// +/// +/// Bounds. Every statement runs under ; a statement that does not finish fails +/// the act, whose transaction the scope then discards. A selection statement's work grows with the rows and the +/// decompressed payload bytes of its batch, which both budgets cap, and each UPDATE rewrites at most +/// rows of one batch, so its payload is within the same byte budget; the number of batches, and +/// the act's total time, grow with the tenant's decompressed payload. What the budgets do not cap is one row: a payload column holds at most +/// (256 KiB) before it is elided, so a row is at most about 768 KiB. The budget was +/// chosen from measurement so a batch stays far inside the timeout (Audit module performance budget). +/// +/// +public sealed class AuditRedactionExecutor : IAuditRedactor +{ + /// + /// The wall-clock bound of one statement. Measured with the budgets below, no statement took more than 2 s, on + /// ordinary rows, on incompressible and on highly compressible payloads (Audit module performance budget). Thirty seconds leaves a degraded + /// database room without letting one statement hold the operator's scope open for long (Audit module performance + /// budget). + /// + public static readonly TimeSpan StatementTimeout = TimeSpan.FromSeconds(30); + + /// The most of the tenant's rows one selection statement reads, newest first. + public const int BatchRows = 100_000; + + /// + /// The decompressed payload bytes (before_state, after_state and changes) at which a batch ends + /// before . + /// + /// + /// 64 MiB, from measurement. A value stored uncompressed is read at its stored size, and rows of 100 KiB of + /// incompressible text were read at about 35–70 MB a second (a batch of about 650 rows took at most 2 s), so a batch + /// stays near two seconds, under five on a disk twice as slow, and far inside . + /// Compressed payloads were walked at 0.6–5 GB a second decompressed, so their batches take a fraction of a second; + /// counted by stored size instead, one batch of 250 KB documents stored as 3 KB held 3.7 GB, which took 1.2 s on the + /// measuring host and has no bound on a slower one. An UPDATE rewrote decompressed payload at 17–165 MB a + /// second, so a batch whose every row is selected stays within about four seconds. The decompression the boundary + /// pays to measure compressed rows is the act's cost of the bound: at 1.5 million ordinary rows it draws 155 batches + /// instead of 24 and a whole-tenant act takes about 12.5 s instead of 7.5 s. + /// + public const long BatchBytes = 64L * 1024 * 1024; + + /// The most selected rows one UPDATE rewrites. + public const int UpdateRows = 1_000; + + /// + /// The number of spellings (two for each identifier) from which the cheap payload filter looks each walked string up in + /// a hashed set of the spellings instead of testing the walked array for each spelling. + /// + /// + /// From measurement on PostgreSQL 18.4 (Audit module performance budget). Over 300,000 rows of one tenant the + /// containment test took 2.1 s at six spellings (an erasure of two Memberships) and grew by about 0.03 s for every + /// spelling, to 16.7 s at 514 (a closure pass of 256 Memberships), while the set lookup took 4.0 to 5.5 s whatever the + /// count, its unnest paid on every row. They cross at about 110 spellings, so below this bound the containment test is + /// the cheaper, and above it a closure pass costs what a pass of a few identifiers costs. + /// + public const int SetLookupFrom = 128; + + private const string PlatformRole = "learnstack_platform"; + + // The declarations, bound as one jsonb map and read by key: {"Entity": {"p": {"Property": [shape, kind]}, + // "n": {"Navigation": {"Property": kind}}}}, so a row's declarations are a lookup by its entity type, never a join. + private const string Declarations = "@declarations"; + + // The reach (ADR-0108 § 4): the tenant, and for an administrator's request the group's organization, none for the + // tenant-wide group. Bound per call, so the planner folds the branch that does not apply. + private const string Reach = """ + a.tenant_id = @tenant + AND (@whole_tenant OR (@organization IS NULL AND a.organization_id IS NULL) OR a.organization_id = @organization) + """; + + // One batch of the tenant's rows: [lower, upper) on the key ("timestamp", id). The plain range on the timestamp is + // what ix_audit_log_tenant_id_timestamp serves; the two id terms then split the rows that share a boundary's timestamp. + private const string Batch = """ + a."timestamp" >= @lower AND a."timestamp" <= @upper + AND (a."timestamp" > @lower OR a.id >= @lower_id) AND (a."timestamp" < @upper OR a.id < @upper_id) + """; + + // The redaction of one value at a declared path, by the declaration's kind: a string equal to an identifier of its + // kind becomes the sentinel, and so does each such element of an array of identifiers. + private const string RedactString = """ + CASE WHEN jsonb_typeof($VALUE$) = 'string' AND lower($VALUE$ #>> '{}') = ANY(CASE $KIND$ WHEN 1 THEN @users ELSE @memberships END) + THEN to_jsonb(@sentinel) ELSE $VALUE$ END + """; + + private const string RedactElements = """ + CASE WHEN jsonb_typeof($VALUE$) = 'array' THEN ( + SELECT COALESCE(jsonb_agg(CASE WHEN jsonb_typeof(x.value) = 'string' + AND lower(x.value #>> '{}') = ANY(CASE $KIND$ WHEN 1 THEN @users ELSE @memberships END) + THEN to_jsonb(@sentinel) ELSE x.value END ORDER BY x.position), '[]'::jsonb) + FROM jsonb_array_elements($VALUE$) WITH ORDINALITY AS x(value, position)) + ELSE $VALUE$ END + """; + + // One snapshot column (an object): each declared property, each declared array, and each declared member of a + // contained collection, keyed by the member's own key. Every other key is copied as it is, and an object with no + // declared key comes back equal, which is what makes the UPDATE's guard skip it. + private static readonly string RedactState = Sql( + "CASE WHEN jsonb_typeof($VALUE$) = 'object' AND", Declarations, "? a.entity_type::text THEN (", + "SELECT COALESCE(jsonb_object_agg(e.key, CASE", + "WHEN (", Declarations, "#> ARRAY[a.entity_type::text, 'p']) ? e.key THEN", + "CASE WHEN (", Declarations, "#>> ARRAY[a.entity_type::text, 'p', e.key, '0']) = '3' THEN", + Format(RedactElements, "e.value", "(" + Declarations + " #>> ARRAY[a.entity_type::text, 'p', e.key, '1'])::int"), + "ELSE", + Format(RedactString, "e.value", "(" + Declarations + " #>> ARRAY[a.entity_type::text, 'p', e.key, '1'])::int"), + "END", + "WHEN (", Declarations, "#> ARRAY[a.entity_type::text, 'n']) ? e.key AND jsonb_typeof(e.value) = 'object' THEN (", + "SELECT COALESCE(jsonb_object_agg(m.key, CASE WHEN jsonb_typeof(m.value) = 'object' THEN (", + "SELECT COALESCE(jsonb_object_agg(f.key, CASE WHEN (", Declarations, "#> ARRAY[a.entity_type::text, 'n', e.key]) ? f.key THEN", + Format(RedactString, "f.value", "(" + Declarations + " #>> ARRAY[a.entity_type::text, 'n', e.key, f.key])::int"), + """ + ELSE f.value END), '{}'::jsonb) + FROM jsonb_each(m.value) AS f) + ELSE m.value END), '{}'::jsonb) + FROM jsonb_each(e.value) AS m) + ELSE e.value END), '{}'::jsonb) + FROM jsonb_each($VALUE$) AS e) + ELSE $VALUE$ END + """); + + // The changes column (an array of {path, before, after}): an item whose path is /{the row's entity type}/{id}/ and + // then a declared property, or a declared navigation, a member key and a property, has its before and after + // redacted; the id segment is whatever instance the item describes. Every other item is copied in place. + private static readonly string RedactChanges = Sql( + "CASE WHEN jsonb_typeof($VALUE$) = 'array' AND", Declarations, "? a.entity_type::text THEN (", + "SELECT COALESCE(jsonb_agg(CASE WHEN s.kind IS NULL THEN i.item ELSE", + "jsonb_set(jsonb_set(i.item, '{before}', COALESCE(CASE WHEN s.shape = 3 THEN", + Format(RedactElements, "(i.item -> 'before')", "s.kind"), "ELSE", Format(RedactString, "(i.item -> 'before')", "s.kind"), + "END, 'null'::jsonb), false), '{after}', COALESCE(CASE WHEN s.shape = 3 THEN", + Format(RedactElements, "(i.item -> 'after')", "s.kind"), "ELSE", Format(RedactString, "(i.item -> 'after')", "s.kind"), + """ + END, 'null'::jsonb), false) END ORDER BY i.position), '[]'::jsonb) + FROM jsonb_array_elements($VALUE$) WITH ORDINALITY AS i(item, position) + CROSS JOIN LATERAL (SELECT string_to_array(i.item ->> 'path', '/') AS segments) AS p + CROSS JOIN LATERAL (SELECT + CASE WHEN cardinality(p.segments) = 6 THEN 2 + ELSE ( + """, + Declarations, "#>> ARRAY[a.entity_type::text, 'p', p.segments[4], '0'])::int END AS shape,", + "CASE WHEN p.segments[1] <> '' OR p.segments[2] <> a.entity_type::text THEN NULL", + "WHEN cardinality(p.segments) = 4 THEN (", Declarations, "#>> ARRAY[a.entity_type::text, 'p', p.segments[4], '1'])::int", + "WHEN cardinality(p.segments) = 6 THEN (", Declarations, "#>> ARRAY[a.entity_type::text, 'n', p.segments[4], p.segments[6]])::int", + """ + END AS kind) AS s) + ELSE $VALUE$ END + """); + + private static readonly string RedactedBefore = Format(RedactState, "a.before_state"); + private static readonly string RedactedAfter = Format(RedactState, "a.after_state"); + private static readonly string RedactedChanges = Format(RedactChanges, "a.changes"); + + // The cheap filter: one level-bounded walk per payload column for a string equal to either canonical spelling of + // an identifier (the capture writes the lower-case one). It reaches every path the grammar can declare (a + // property, an element of an array property, a member's property; a changes item's before and after and their + // elements) and more, so it only narrows: the rewrite decides. Two forms answer the same question, chosen by the + // number of spellings (SetLookupFrom). The containment test asks the walked array for each spelling, so its cost + // is the spellings times the strings: the cheapest for an erasure's few identifiers, and about six times the act + // for a closure pass with 256 Memberships. The set lookup unnests each walked string once and looks it up in the + // spellings, which the statement is planned with as a constant array that PostgreSQL hashes, so its cost does not + // grow with the identifiers, at the price of the unnest on every row (Audit module performance budget). + private const string MayHoldByContainment = """ + (jsonb_path_query_array(a.before_state, 'lax $.**{1 to 3}') ?| @spellings + OR jsonb_path_query_array(a.after_state, 'lax $.**{1 to 3}') ?| @spellings + OR jsonb_path_query_array(a.changes, 'lax $.**{1 to 3}') ?| @spellings) + """; + + private const string MayHoldInSet = """ + EXISTS (SELECT 1 FROM jsonb_array_elements_text( + COALESCE(jsonb_path_query_array(a.before_state, 'lax $.**{1 to 3} ? (@.type() == "string")'), '[]'::jsonb) + || COALESCE(jsonb_path_query_array(a.after_state, 'lax $.**{1 to 3} ? (@.type() == "string")'), '[]'::jsonb) + || COALESCE(jsonb_path_query_array(a.changes, 'lax $.**{1 to 3} ? (@.type() == "string")'), '[]'::jsonb)) + AS v(value) + WHERE v.value = ANY(@spellings)) + """; + + // A declared path holds an identifier exactly when the redaction would change the row's payload. + private static readonly string Holds = Sql( + "(", RedactedBefore, "IS DISTINCT FROM a.before_state OR", RedactedAfter, "IS DISTINCT FROM a.after_state OR", + RedactedChanges, "IS DISTINCT FROM a.changes)"); + + // The metadata person references the Audit participant reads (ADR-0107 § 6): the subject as causal actor, top level + // or in the authorization evidence, or as a provider event's affected user; and a frozen Membership in the + // authorization evidence of a row the subject acted in. + private const string NamesSubject = """ + COALESCE(a.metadata ->> 'causal_actor_user_id' = @subject_text + OR a.metadata #>> '{authorization,causal_actor_user_id}' = @subject_text + OR a.metadata #>> '{provider_event,affected_user_id}' = @subject_text + OR (a.actor_user_id = @subject AND COALESCE(a.metadata -> 'authorization' -> 'memberships', '[]'::jsonb) ?| @memberships), false) + """; + + // The role, and whether JIT is on for this transaction. + private const string EnterSql = "SELECT current_user::text, current_setting('jit') = 'on'"; + + // JIT off for the redaction's own statements, and back on after them when it was on. Their long per-row expressions + // carry planner estimates far above jit_optimize_above_cost, and compiling them cost more than running them + // (measured on 1.5 million rows: a selection batch took 1.6–3.1 s with JIT and at most 0.96 s without, a whole-tenant + // act 41–42 s against 10–12 s). A planner setting, transaction-local, and no session announcement: the scope's + // tenant-free context is untouched. + private const string JitOffSql = "SET LOCAL jit = off"; + + private const string JitOnSql = "SET LOCAL jit = on"; + + // One payload column's decompressed size: its stored size when it is stored uncompressed, which pg_column_size + // reads without detoasting, and the size of the decompressed value when it is compressed. The empty path #> '{}' + // hands back the whole document, decompressed by the operator's argument fetch, so pg_column_size measures it in + // memory: the decompression the selection pays anyway, without rendering the document as text (measured on 1.5 + // million rows, 1.9 s against 4.2 s for octet_length(value::text)). NULL is zero. + private const string PayloadBytes = """ + CASE WHEN pg_column_compression($VALUE$) IS NULL THEN COALESCE(pg_column_size($VALUE$), 0) + ELSE pg_column_size($VALUE$ #> '{}') END + """; + + // The next batch's lower bound: newest first below the upper one, the first row at which the batch holds + // @batch_rows rows or the payload of its rows in the reach reaches @batch_bytes. A payload's size is what the + // selection and the UPDATE work through, its decompressed size: a value stored uncompressed (inline or out of line) + // is sized by pg_column_size, which reads it from the header or the TOAST pointer without detoasting; a compressed one + // has no such header, so it is decompressed once to measure it, as the selection then does anyway. A row + // outside the reach counts no bytes: the selection reads its key and organization and never its payload, and the + // row cap bounds those reads. The inner query reads the + // rows in order from ix_audit_log_tenant_id_timestamp (ties sorted by id incrementally) and sizes each row where + // it reads it, so the sort carries a key and a number, never a payload. Its LIMIT is the row cap no batch exceeds, + // which keeps the inner query a top-N that the index serves in order. The running sums stream, so the statement + // stops at the boundary. No row once fewer rows and bytes remain, and the last batch is open below. A pass whose selection + // walks no payload, the sentinel pass, binds @size_payload false: CASE evaluates no THEN whose condition is false, so + // no payload is decompressed to be sized, every row counts nothing and only the row cap ends its batches. + private static readonly string BoundarySql = Checked(Sql( + """ + SELECT b."timestamp", b.id FROM ( + SELECT s."timestamp", s.id, count(*) OVER batch AS n, sum(s.bytes) OVER batch AS bytes + FROM ( + SELECT a."timestamp", a.id, + CASE WHEN @size_payload AND (@whole_tenant OR (@organization IS NULL AND a.organization_id IS NULL) + OR a.organization_id = @organization) + THEN + """, + Format(PayloadBytes, "a.before_state"), "+", Format(PayloadBytes, "a.after_state"), "+", Format(PayloadBytes, "a.changes"), + """ + ELSE 0 END AS bytes + FROM public.audit_log AS a + WHERE a.tenant_id = @tenant AND a."timestamp" <= @upper AND (a."timestamp" < @upper OR a.id < @upper_id) + ORDER BY a."timestamp" DESC, a.id DESC + LIMIT @batch_rows) AS s + WINDOW batch AS (ORDER BY s."timestamp" DESC, s.id DESC ROWS UNBOUNDED PRECEDING)) AS b + WHERE b.n >= @batch_rows OR b.bytes >= @batch_bytes + ORDER BY b."timestamp" DESC, b.id DESC + LIMIT 1 + """)); + + // What a matched row reports, read from the row itself: whether it is selected (its actor, its entity or a declared + // path names the subject), whether the actor or the entity is the subject, and whether its metadata names the + // subject. Every value is the row's own, so a row two branches match is one row of the union. The rewrite that + // decides a payload reference runs only where the cheap filter keeps the row, as in the third branch's WHERE: a row + // matched for its metadata alone, or by the actor or entity branch, never pays it for nothing. + private static string Matched(string mayHold) => Sql( + "SELECT a.id, a.\"timestamp\",", + "CASE WHEN a.actor_user_id = @subject OR a.entity_id = ANY(@identifiers) THEN true", + "WHEN", Declarations, "? a.entity_type::text AND", mayHold, "THEN", Holds, "ELSE false END,", + "COALESCE(a.actor_user_id = @subject, false), COALESCE(a.entity_id = ANY(@identifiers), false),", + NamesSubject, + "FROM public.audit_log AS a WHERE", Reach, "AND", Batch); + + // One batch's selection: the actor and the entity branches, index-served, and one pass over the batch's rows of the + // reach for a metadata or a payload reference. A row that names the subject only in its metadata is counted and + // never redacted. The two statements differ only in the cheap filter's form. + private static string Selection(string mayHold) => Checked(Sql( + Matched(mayHold), "AND a.actor_user_id = @subject", + "UNION", + Matched(mayHold), "AND a.entity_id = ANY(@identifiers)", + "UNION", + Matched(mayHold), "AND (", NamesSubject, + "OR CASE WHEN", Declarations, "? a.entity_type::text AND", mayHold, "THEN", Holds, "ELSE false END)")); + + private static readonly string SelectionSql = Selection(MayHoldByContainment); + + private static readonly string SetSelectionSql = Selection(MayHoldInSet); + + // One batch of the sentinel pass, in the selection's column order: the rows of the platform sentinel tenant that + // carry the subject key in their metadata (a global creation and its failed and undetermined attempts), whose actor + // is the subject, or whose entity is the subject's User. Every row it returns is selected, and a row that carries the + // key is the pass's metadata reference. One read of the batch's rows, filtered by the three predicates: the key has + // no index, and a batch is bounded. + private static readonly string SentinelSelectionSql = Checked(Sql( + "SELECT a.id, a.\"timestamp\", true,", + "COALESCE(a.actor_user_id = @subject, false),", + "COALESCE(a.entity_type = 'User' AND a.entity_id = @subject_text, false),", + "COALESCE(a.metadata ->> 'identity_subject_key' = @subject_key, false)", + "FROM public.audit_log AS a WHERE a.tenant_id = @tenant AND", Batch, + "AND (a.actor_user_id = @subject OR (a.entity_type = 'User' AND a.entity_id = @subject_text)", + "OR a.metadata ->> 'identity_subject_key' = @subject_key)")); + + // The rows an administrator's request deliberately does not reach that still name the subject as actor or entity: + // the tenant's rows outside the group's organization (outside the tenant level for the tenant-wide group). + private const string UnscopedSql = """ + SELECT count(*) FROM ( + SELECT a.id, a."timestamp" FROM public.audit_log AS a + WHERE a.tenant_id = @tenant AND a.actor_user_id = @subject + AND (CASE WHEN @organization IS NULL THEN a.organization_id IS NOT NULL ELSE a.organization_id IS DISTINCT FROM @organization END) + UNION + SELECT a.id, a."timestamp" FROM public.audit_log AS a + WHERE a.tenant_id = @tenant AND a.entity_id = ANY(@identifiers) + AND (CASE WHEN @organization IS NULL THEN a.organization_id IS NOT NULL ELSE a.organization_id IS DISTINCT FROM @organization END) + ) AS outside + """; + + // The redaction of one set of selected rows, by primary key and inside the tenant. Each row is locked and its new + // payload computed once from the version the lock returns, so a concurrent redaction of the same row is never + // overwritten; a row changes only where a value differs, and the statement returns which of the six columns it + // changed. A payload column the redaction leaves equal keeps its own stored value, so an unchanged large payload is + // not recompressed, rewritten to TOAST and logged again only because the rewrite rebuilt an equal copy. + private static readonly string RedactSql = Checked(Sql( + "WITH locked AS MATERIALIZED (", + "SELECT a.id, a.\"timestamp\",", RedactedBefore, "AS before_state,", RedactedAfter, "AS after_state,", RedactedChanges, "AS changes", + """ + FROM unnest(@ids, @timestamps) AS t(id, "timestamp") + JOIN public.audit_log AS a ON a.id = t.id AND a."timestamp" = t."timestamp" + WHERE a.tenant_id = @tenant + FOR UPDATE OF a) + UPDATE public.audit_log AS a + SET ip_address = NULL, user_agent = NULL, actor_email = NULL, + before_state = CASE WHEN a.before_state IS DISTINCT FROM l.before_state THEN l.before_state ELSE a.before_state END, + after_state = CASE WHEN a.after_state IS DISTINCT FROM l.after_state THEN l.after_state ELSE a.after_state END, + changes = CASE WHEN a.changes IS DISTINCT FROM l.changes THEN l.changes ELSE a.changes END + FROM locked AS l + WHERE a.id = l.id AND a."timestamp" = l."timestamp" + AND (a.ip_address IS NOT NULL OR a.user_agent IS NOT NULL OR a.actor_email IS NOT NULL + OR a.before_state IS DISTINCT FROM l.before_state OR a.after_state IS DISTINCT FROM l.after_state + OR a.changes IS DISTINCT FROM l.changes) + RETURNING old.ip_address IS NOT NULL, old.user_agent IS NOT NULL, old.actor_email IS NOT NULL, + old.before_state IS DISTINCT FROM new.before_state, old.after_state IS DISTINCT FROM new.after_state, + old.changes IS DISTINCT FROM new.changes + """)); + + // The open ends of the first and the last batch: infinity and -infinity on the wire, so the id beside them is never + // compared for a row with a finite timestamp. A row stamped +infinity would be outside the keyset and never read; + // no writer produces one (the composer stamps a clock reading), and -infinity is inside the last batch. + private static readonly Key OpenUpper = new(DateTime.SpecifyKind(DateTime.MaxValue, DateTimeKind.Utc), Guid.Empty); + private static readonly Key OpenLower = new(DateTime.SpecifyKind(DateTime.MinValue, DateTimeKind.Utc), Guid.Empty); + + private readonly string _declarations; + private readonly int _batchRows; + private readonly long _batchBytes; + private readonly int _updateRows; + private readonly int _setLookupFrom; + + /// Merges and checks every registered locator's declarations once, and binds them as one map. + /// The declarations are empty, duplicated or ambiguous (). + public AuditRedactionExecutor(IEnumerable locators) + : this(locators, BatchRows, BatchBytes, UpdateRows) + { + } + + /// + /// The same executor with other batch and chunk sizes, so a test proves the batching with a few rows, and another bound + /// of the set lookup, so a test runs both forms of the cheap filter over the same rows. + /// + /// The declarations are empty, duplicated or ambiguous. + /// A size is not positive. + internal AuditRedactionExecutor( + IEnumerable locators, int batchRows, long batchBytes, int updateRows, int setLookupFrom = SetLookupFrom) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(batchRows); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(batchBytes); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(updateRows); + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(setLookupFrom); + var catalog = new UserReferenceCatalog(locators); + if (catalog.Redactable.IsEmpty) + { + throw new ArgumentException("The redaction needs at least one registered user reference locator.", nameof(locators)); + } + + _declarations = DeclarationMap(catalog); + _batchRows = batchRows; + _batchBytes = batchBytes; + _updateRows = updateRows; + _setLookupFrom = setLookupFrom; + } + + /// + public async Task RedactAsync( + AuditRedactionPlan plan, + PlatformAdmission admission, + DbConnection connection, + DbTransaction transaction, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(plan); + ArgumentNullException.ThrowIfNull(admission); + ArgumentNullException.ThrowIfNull(connection); + ArgumentNullException.ThrowIfNull(transaction); + JobApplicationSourceOwner.RefuseExternalEntry(); + if (JobApplicationSourceOwner.Current is not null) + { + throw new InvalidOperationException("Audit redaction is an operator act and never runs in a job frame."); + } + + if (!Sanctions(admission.Operation, plan)) + { + throw new InvalidOperationException("The admission does not name an operation that may redact this plan's audit rows."); + } + + // The scope consumed the admission on entry; an admission still unspent never opened a scope, and is spent here. + if (admission.TryConsume()) + { + throw new InvalidOperationException("Audit redaction runs inside the platform scope its admission opened."); + } + + if (connection is not NpgsqlConnection platform || transaction is not NpgsqlTransaction work + || !ReferenceEquals(work.Connection, platform) || platform.State != ConnectionState.Open) + { + throw new InvalidOperationException("Audit redaction runs on the platform scope's open connection and its work transaction."); + } + + var run = new Run(this, plan, platform, work); + var jit = await run.EnterAsync(cancellationToken).ConfigureAwait(false); + var tally = await run.RedactBatchesAsync(cancellationToken).ConfigureAwait(false); + List retained = + [ + new(RetainedReferenceKind.AuditActorReference, tally.Actor), + new(RetainedReferenceKind.AuditEntityReference, tally.Entity), + new(RetainedReferenceKind.AuditMetadataReference, tally.Metadata), + ]; + if (!plan.WholeTenant) + { + retained.Add(new(RetainedReferenceKind.UnscopedAuditRows, + await run.ScalarAsync(UnscopedSql, cancellationToken).ConfigureAwait(false))); + } + + await run.RestoreAsync(jit, cancellationToken).ConfigureAwait(false); + return new AuditRedactionReport(tally.Selected, tally.Redacted, retained); + } + + /// + /// The one place in this file an operation is bound to the plans it may redact: complete_erasure + /// (audit.redaction.apply) an erasure request's rows, and the closure's Finalize + /// (platform.closure.finalize, ADR-0107 § 7) a closure's tenant and sentinel passes. Neither redacts the other's + /// plan, and no other operation redacts anything. The platform scope checks the same pairing before it calls; this is + /// the executor's own, so neither check stands alone. + /// + private static bool Sanctions(PlatformOperation operation, AuditRedactionPlan plan) => plan.Pass switch + { + AuditRedactionPass.Erasure => + ReferenceEquals(operation, PlatformOperations.ErasureComplete) && plan.Subject.Kind == DataRequestKind.Erasure, + AuditRedactionPass.ClosureTenant or AuditRedactionPass.ClosureSentinel => + ReferenceEquals(operation, PlatformOperations.ClosureFinalize), + _ => false, + }; + + /// + /// The declarations as the statements read them: per entity name, p maps a property to its shape and kind + /// and n maps a contained collection's navigation to its members' declared properties and their kinds. + /// + private static string DeclarationMap(UserReferenceCatalog catalog) + { + using var stream = new MemoryStream(); + using (var json = new Utf8JsonWriter(stream)) + { + json.WriteStartObject(); + foreach (var entity in catalog.Redactable.GroupBy(declaration => declaration.EntityName, StringComparer.Ordinal)) + { + json.WriteStartObject(entity.Key); + json.WriteStartObject("p"); + foreach (var declaration in entity.Where(declaration => declaration.Path.Navigation is null)) + { + json.WriteStartArray(declaration.Path.Property); + json.WriteNumberValue((int)declaration.Path.Shape); + json.WriteNumberValue((int)declaration.Kind); + json.WriteEndArray(); + } + + json.WriteEndObject(); + json.WriteStartObject("n"); + foreach (var navigation in entity.Where(declaration => declaration.Path.Navigation is not null) + .GroupBy(declaration => declaration.Path.Navigation!, StringComparer.Ordinal)) + { + json.WriteStartObject(navigation.Key); + foreach (var declaration in navigation) + { + json.WriteNumber(declaration.Path.Property, (int)declaration.Kind); + } + + json.WriteEndObject(); + } + + json.WriteEndObject(); + json.WriteEndObject(); + } + + json.WriteEndObject(); + } + + return Encoding.UTF8.GetString(stream.ToArray()); + } + + /// Joins fixed fragments into one statement, a line each, so no two tokens ever run together. + private static string Sql(params string[] fragments) => string.Join('\n', fragments); + + /// A composed statement with every fragment token filled; checked once, when the type is initialized. + private static string Checked(string sql) => + sql.Contains("$VALUE$", StringComparison.Ordinal) || sql.Contains("$KIND$", StringComparison.Ordinal) + ? throw new InvalidOperationException("A redaction statement kept an unfilled fragment token.") + : sql; + + /// Fills a fragment's value and kind tokens with fixed column and alias names, never with data. + private static string Format(string template, string value, string? kind = null) => + template.Replace("$VALUE$", value, StringComparison.Ordinal).Replace("$KIND$", kind ?? "$KIND$", StringComparison.Ordinal); + + /// One end of a batch: a row's key in the batches' order, newest first. + private readonly record struct Key(DateTime Timestamp, Guid Id); + + /// The counts one redaction accumulates over its batches. + private sealed class Tally + { + public long Selected { get; set; } + public long Actor { get; set; } + public long Entity { get; set; } + public long Metadata { get; set; } + public Dictionary Redacted { get; } = Enum.GetValues().ToDictionary(column => column, _ => 0L); + } + + /// One redaction's statements, all on the caller's connection and transaction. + private sealed class Run(AuditRedactionExecutor executor, AuditRedactionPlan plan, NpgsqlConnection connection, NpgsqlTransaction transaction) + { + private readonly string _subject = plan.SubjectUserId.Value.ToString("D"); + private readonly string[] _memberships = [.. plan.MembershipIds.Select(membership => membership.ToString("D"))]; + + /// Refuses any role but the platform's, switches JIT off, and returns whether it was on. + public async Task EnterAsync(CancellationToken cancellationToken) + { + bool jit; + await using (var command = Command(EnterSql)) + { + await using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false); + if (!await reader.ReadAsync(cancellationToken).ConfigureAwait(false) + || !string.Equals(reader.GetString(0), PlatformRole, StringComparison.Ordinal)) + { + throw new InvalidOperationException("Audit redaction runs as the platform role, whose grants are its only bound."); + } + + jit = reader.GetBoolean(1); + } + + await NonQueryAsync(JitOffSql, cancellationToken).ConfigureAwait(false); + return jit; + } + + /// Leaves the transaction's JIT setting as the redaction found it. + public async Task RestoreAsync(bool jit, CancellationToken cancellationToken) + { + if (jit) + { + await NonQueryAsync(JitOnSql, cancellationToken).ConfigureAwait(false); + } + } + + private async Task NonQueryAsync(string sql, CancellationToken cancellationToken) + { + await using var command = new NpgsqlCommand(sql, connection, transaction) { CommandTimeout = (int)StatementTimeout.TotalSeconds }; + await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + } + + public async Task ScalarAsync(string sql, CancellationToken cancellationToken) + { + await using var command = Command(sql); + return (T)(await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false))!; + } + + public async Task RedactBatchesAsync(CancellationToken cancellationToken) + { + var tally = new Tally(); + var upper = OpenUpper; + while (true) + { + Key? boundary = null; + await using (var command = Command(BoundarySql)) + { + Bind(command, "upper", upper); + command.Parameters.AddWithValue("batch_rows", NpgsqlDbType.Bigint, (long)executor._batchRows); + command.Parameters.AddWithValue("batch_bytes", NpgsqlDbType.Bigint, executor._batchBytes); + await using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false); + if (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) + { + boundary = new Key(DateTime.SpecifyKind(reader.GetDateTime(0), DateTimeKind.Utc), reader.GetGuid(1)); + } + } + + var selected = await SelectAsync(boundary ?? OpenLower, upper, tally, cancellationToken).ConfigureAwait(false); + foreach (var chunk in selected.Chunk(executor._updateRows)) + { + await RedactAsync(chunk, tally, cancellationToken).ConfigureAwait(false); + } + + if (boundary is not { } lower) + { + return tally; + } + + upper = lower; + } + } + + private async Task> SelectAsync(Key lower, Key upper, Tally tally, + CancellationToken cancellationToken) + { + var selected = new List<(Guid Id, DateTime Timestamp)>(); + await using var command = Command(plan.Pass == AuditRedactionPass.ClosureSentinel ? SentinelSelectionSql + : 2 * (1 + _memberships.Length) >= executor._setLookupFrom ? SetSelectionSql : SelectionSql); + Bind(command, "lower", lower); + Bind(command, "upper", upper); + await using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false); + while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) + { + tally.Metadata += reader.GetBoolean(5) ? 1 : 0; + if (!reader.GetBoolean(2)) + { + continue; + } + + selected.Add((reader.GetGuid(0), DateTime.SpecifyKind(reader.GetDateTime(1), DateTimeKind.Utc))); + tally.Selected++; + tally.Actor += reader.GetBoolean(3) ? 1 : 0; + tally.Entity += reader.GetBoolean(4) ? 1 : 0; + } + + return selected; + } + + private async Task RedactAsync((Guid Id, DateTime Timestamp)[] rows, Tally tally, CancellationToken cancellationToken) + { + await using var command = Command(RedactSql); + command.Parameters.Add(new NpgsqlParameter("ids", NpgsqlDbType.Array | NpgsqlDbType.Uuid) { Value = rows.Select(row => row.Id).ToArray() }); + command.Parameters.Add(new NpgsqlParameter("timestamps", NpgsqlDbType.Array | NpgsqlDbType.TimestampTz) + { + Value = rows.Select(row => row.Timestamp).ToArray(), + }); + await using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false); + while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) + { + Count(tally, AuditRedactedColumn.IpAddress, reader.GetBoolean(0)); + Count(tally, AuditRedactedColumn.UserAgent, reader.GetBoolean(1)); + Count(tally, AuditRedactedColumn.ActorEmail, reader.GetBoolean(2)); + Count(tally, AuditRedactedColumn.BeforeState, reader.GetBoolean(3)); + Count(tally, AuditRedactedColumn.AfterState, reader.GetBoolean(4)); + Count(tally, AuditRedactedColumn.Changes, reader.GetBoolean(5)); + } + } + + private static void Count(Tally tally, AuditRedactedColumn column, bool changed) + { + if (changed) + { + tally.Redacted[column]++; + } + } + + private NpgsqlCommand Command(string sql) + { + var command = new NpgsqlCommand(sql, connection, transaction) { CommandTimeout = (int)StatementTimeout.TotalSeconds }; + string[] identifiers = [_subject, .. _memberships]; + command.Parameters.AddWithValue("tenant", plan.TenantId.Value); + command.Parameters.AddWithValue("whole_tenant", plan.WholeTenant); + // The sentinel selection reads no payload, so its batches are cut by rows alone. + command.Parameters.AddWithValue("size_payload", plan.Pass != AuditRedactionPass.ClosureSentinel); + command.Parameters.AddWithValue("organization", NpgsqlDbType.Uuid, (object?)plan.OrganizationId?.Value ?? DBNull.Value); + command.Parameters.AddWithValue("subject", plan.SubjectUserId.Value); + command.Parameters.AddWithValue("subject_text", _subject); + command.Parameters.AddWithValue("subject_key", NpgsqlDbType.Text, (object?)plan.SubjectKey?.Hex ?? DBNull.Value); + command.Parameters.Add(Texts("users", [_subject])); + command.Parameters.Add(Texts("memberships", _memberships)); + command.Parameters.Add(Texts("identifiers", identifiers)); + command.Parameters.Add(Texts("spellings", [.. identifiers, .. identifiers.Select(identifier => identifier.ToUpperInvariant())])); + command.Parameters.AddWithValue("declarations", NpgsqlDbType.Jsonb, executor._declarations); + command.Parameters.AddWithValue("sentinel", NpgsqlDbType.Text, SensitiveTokenCatalog.RedactedValue); + return command; + } + + private static NpgsqlParameter Texts(string name, string[] values) => + new(name, NpgsqlDbType.Array | NpgsqlDbType.Text) { Value = values }; + + /// Binds one end of a batch as @name and @name_id. + private static void Bind(NpgsqlCommand command, string name, Key key) + { + command.Parameters.AddWithValue(name, NpgsqlDbType.TimestampTz, key.Timestamp); + command.Parameters.AddWithValue(name + "_id", NpgsqlDbType.Uuid, key.Id); + } + } +} diff --git a/backend/src/LearnStack.Infrastructure.Audit/AuditStateCapture.cs b/backend/src/LearnStack.Infrastructure.Audit/AuditStateCapture.cs index 2d52e9c54..38ee0ba75 100644 --- a/backend/src/LearnStack.Infrastructure.Audit/AuditStateCapture.cs +++ b/backend/src/LearnStack.Infrastructure.Audit/AuditStateCapture.cs @@ -222,6 +222,26 @@ public void AttachProviderEvent(ProviderEventAuditEvidence evidence) _intents[index] = attached; } + /// + public void WithholdProviderEvent(ProviderEventAuditEvidence evidence) + { + ArgumentNullException.ThrowIfNull(evidence); + if (!HasOpenFrame || State != AuditIntentState.Pending) + throw new InvalidOperationException("Provider observation is withheld only from an actual pending audit frame."); + var candidates = Enumerable.Range(0, _intents.Count).Where(index => _intentFrames[index] == CurrentFrame + && _intents[index].Operation == "audit.provider_event.observe").ToArray(); + if (candidates.Length != 1 || _intents[candidates[0]] is not + { + ProviderEvent: null, ModuleName: "audit", OperationClass: OperationClass.Must, OrganizationId: null, + GlobalIdentity: null, Authorization: null, JobId: null, ParentJobId: null, + } intent + || intent.TenantId != evidence.TenantId || intent.CausationId != evidence.EventId + || intent.ActorUserId != UserId.SystemActor || intent.EntityType != typeof(ProviderEventAuditEvidence)) + throw new InvalidOperationException("Provider observation withholding requires its one unclaimed delivery intent."); + _intents.RemoveAt(candidates[0]); + _intentFrames.RemoveAt(candidates[0]); + } + /// public void Designate(IAggregateRoot aggregate) where TId : struct, IStronglyTypedId diff --git a/backend/src/LearnStack.Infrastructure.Audit/LearnStack.Infrastructure.Audit.csproj b/backend/src/LearnStack.Infrastructure.Audit/LearnStack.Infrastructure.Audit.csproj index edca61ee4..e4986f610 100644 --- a/backend/src/LearnStack.Infrastructure.Audit/LearnStack.Infrastructure.Audit.csproj +++ b/backend/src/LearnStack.Infrastructure.Audit/LearnStack.Infrastructure.Audit.csproj @@ -29,4 +29,9 @@ + + + + + diff --git a/backend/src/LearnStack.Infrastructure/DataProtection/AttributionReferenceCounter.cs b/backend/src/LearnStack.Infrastructure/DataProtection/AttributionReferenceCounter.cs new file mode 100644 index 000000000..f68762617 --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/DataProtection/AttributionReferenceCounter.cs @@ -0,0 +1,209 @@ +using System.Linq.Expressions; +using System.Reflection; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Persistence; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; + +namespace LearnStack.Infrastructure.DataProtection; + +/// +/// Counts the rows of one module context that retain a subject as an attribution reference, for the closed retained +/// kind attribution_reference +/// (ADR-0107 § 6). +/// +/// +/// +/// Derived from the model, not listed. An attribution property is every mapped scalar property of CLR type +/// or UserId? on a mapped tenant-owned entity type: the creator, updater and deleter +/// columns of every AuditableEntity, and equally an UpdatedBy that is not one +/// (TenantFeatureFlag) or any later actor column, so an aggregate or column a module adds is counted without +/// a change here. The caller names what it reports under another kind instead: whole entity types (a request's own +/// receipt rows) and single properties that are the row's subject or party rather than its author (a Membership's +/// UserId, an invitation's inviter and acceptor). A named property the model does not map as a +/// is a programming error, so an exclusion cannot silently go stale. +/// +/// +/// The unit is a row. A row counts once when one or more of its attribution properties name the subject: a row +/// the subject created and later updated is one retained row, not two. Another kind may count the same row for +/// another reason (an invitation the subject issued is also an invitation_record); kinds are reasons, not a +/// partition of rows. +/// +/// +/// 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. Owned entity types are part of their +/// owner's row and are not queried on their own. +/// +/// +public static class AttributionReferenceCounter +{ + private static readonly MethodInfo CountMethod = typeof(AttributionReferenceCounter) + .GetMethod(nameof(CountForAsync), BindingFlags.NonPublic | BindingFlags.Static)!; + + private static readonly MethodInfo PropertyMethod = typeof(EF).GetMethod(nameof(EF.Property))!; + + /// 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 Task CountAsync(DbContext context, UserDataSubject subject, IReadOnlySet? excluded, + CancellationToken cancellationToken) => CountAsync(context, subject, excluded, null, cancellationToken); + + /// 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. + /// + /// properties that hold the row's subject or a party to it, reported under another kind or + /// exported as the subject's own record, never attribution. + /// + /// Cancels the reads. + /// A named party property is not a mapped property. + public static async Task CountAsync(DbContext context, UserDataSubject subject, IReadOnlySet? excluded, + IReadOnlyCollection<(Type Entity, string Property)>? parties, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(subject); + return await SumAsync(context, subject, Plan(context.Model, excluded, parties), cancellationToken).ConfigureAwait(false); + } + + /// + /// Counts the rows of the named entity types in which any mapped column names the subject, once + /// per row and exactly in the group: the rows a caller reports under a kind of its own (a request's receipts, as + /// request_receipt) and excludes from attribution_reference by passing the same types there. + /// + /// + /// Every column counts, the subject, the requester and every author column alike, so a person + /// who filed, cancelled or revoked a request about someone else is told the row survives, and a column a later + /// change adds is counted without a change here. + /// + /// A named type is not a mapped tenant-owned entity with a column. + public static async Task CountNamingRowsAsync(DbContext context, UserDataSubject subject, IReadOnlyCollection types, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(subject); + return await SumAsync(context, subject, NamingPlan(context.Model, types), cancellationToken).ConfigureAwait(false); + } + + /// + /// The columns per named entity type, in a stable order: what + /// reads, without reading it. + /// + /// A named type is not a mapped tenant-owned entity with a column. + public static IReadOnlyList<(Type Entity, IReadOnlyList Properties)> NamingPlan(IModel model, IReadOnlyCollection types) + { + ArgumentNullException.ThrowIfNull(model); + ArgumentNullException.ThrowIfNull(types); + return + [ + .. types.Distinct().OrderBy(type => type.FullName, StringComparer.Ordinal).Select(type => + { + var entity = model.FindEntityType(type); + IReadOnlyList properties = entity is null || entity.IsOwned() || !typeof(ITenantOwned).IsAssignableFrom(type) + ? [] + : [.. entity.GetProperties().Where(property => IsUserId(property.ClrType)).Select(property => property.Name) + .Order(StringComparer.Ordinal)]; + return properties.Count == 0 + ? throw new InvalidOperationException("A named type is a mapped tenant-owned entity with a UserId column.") + : (type, properties); + }), + ]; + } + + private static async Task SumAsync(DbContext context, UserDataSubject subject, + IReadOnlyList<(Type Entity, IReadOnlyList Properties)> plan, CancellationToken cancellationToken) + { + long total = 0; + foreach (var (type, properties) in plan) + { + var scoped = typeof(IOrganizationScoped).IsAssignableFrom(type); + if (!scoped && !subject.Group.IsTenantWide) + { + continue; + } + + var count = (Task)CountMethod.MakeGenericMethod(type) + .Invoke(null, [context, properties, subject.SubjectUserId, subject.Group.OrganizationId, scoped, cancellationToken])!; + total = checked(total + await count.ConfigureAwait(false)); + } + + return total; + } + + /// + /// The attribution properties per counted entity type, in a stable order: what + /// reads, without reading it. + /// + public static IReadOnlyList<(Type Entity, IReadOnlyList Properties)> Plan(IModel model, IReadOnlySet? excluded, + IReadOnlyCollection<(Type Entity, string Property)>? parties) + { + ArgumentNullException.ThrowIfNull(model); + var entities = model.GetEntityTypes().Where(entity => !entity.IsOwned() && !entity.HasSharedClrType).ToList(); + var omitted = new HashSet<(Type, string)>(); + foreach (var party in parties ?? []) + { + var property = entities.FirstOrDefault(entity => entity.ClrType == party.Entity)?.FindProperty(party.Property); + if (property is null || !IsUserId(property.ClrType)) + { + throw new InvalidOperationException("A party property names a mapped UserId property of the context."); + } + + omitted.Add((party.Entity, party.Property)); + } + + return + [ + .. entities + .Where(entity => typeof(ITenantOwned).IsAssignableFrom(entity.ClrType) && excluded?.Contains(entity.ClrType) != true) + .Select(entity => (Entity: entity.ClrType, Properties: (IReadOnlyList) + [ + .. entity.GetProperties().Where(property => IsUserId(property.ClrType) && !omitted.Contains((entity.ClrType, property.Name))) + .Select(property => property.Name).Order(StringComparer.Ordinal), + ])) + .Where(entry => entry.Properties.Count > 0) + .DistinctBy(entry => entry.Entity) + .OrderBy(entry => entry.Entity.FullName, StringComparer.Ordinal), + ]; + } + + private static bool IsUserId(Type type) => type == typeof(UserId) || type == typeof(UserId?); + + private static async Task CountForAsync(DbContext context, IReadOnlyList properties, 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); + } + + // One predicate per row: any attribution property naming the subject. The subject travels as a query + // parameter through the closure, never as a literal in the SQL text. + var person = new Person(subject); + var row = Expression.Parameter(typeof(T), "row"); + Expression? names = null; + var entity = context.Model.FindEntityType(typeof(T))!; + foreach (var name in properties) + { + var type = entity.FindProperty(name)!.ClrType; + var access = Expression.Call(PropertyMethod.MakeGenericMethod(type), row, Expression.Constant(name)); + var value = Expression.Property(Expression.Constant(person), type == typeof(UserId) ? nameof(Person.Value) : nameof(Person.Nullable)); + var match = Expression.Equal(access, value); + names = names is null ? match : Expression.OrElse(names, match); + } + + return await rows.LongCountAsync(Expression.Lambda>(names!, row), cancellationToken).ConfigureAwait(false); + } + + /// The subject as the closure the predicate reads, so EF binds it as a parameter. + private sealed class Person(UserId value) + { + public UserId Value { get; } = value; + + public UserId? Nullable { get; } = value; + } +} diff --git a/backend/src/LearnStack.Infrastructure/DataProtection/DataExportCipher.cs b/backend/src/LearnStack.Infrastructure/DataProtection/DataExportCipher.cs new file mode 100644 index 000000000..804aa884a --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/DataProtection/DataExportCipher.cs @@ -0,0 +1,266 @@ +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; +/// 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 +{ + /// 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 readonly Lock _gate = new(); + private volatile bool _disposed; + + /// The key ring is absent or malformed. + /// + /// The secret is read before the ring is judged: a provider that fails to answer propagates its own exception + /// unchanged, so the startup refusal never blames a ring that was never read. + /// + public DataExportCipher(ISecretProvider secrets) + { + ArgumentNullException.ThrowIfNull(secrets); + var secret = secrets.GetSecret(KeyRingSecret); + var keys = new Dictionary(StringComparer.Ordinal); + try + { + using var ring = JsonDocument.Parse(secret ?? 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 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) + { + 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 = Keyed(_keys[ActiveKeyVersion]); + 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 = Keyed(key); + 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() + { + lock (_gate) + { + 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; + } + + /// + /// 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\": \" /// -/// Built once by the composition root from the five command types and never changed, so the source -/// and the executor judge the same list and a request outside it is never captured. +/// Built once by the composition root from the five onboarding command types and a closure's fan-out +/// command, and never changed, so the source and the executor judge the same list and a request outside +/// it is never captured. /// public sealed class PlatformOperatorActCatalog { diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs index a33810738..78cb02d0f 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs @@ -40,9 +40,26 @@ public sealed partial class PlatformOperatorActExecutor( { /// Runs for under . /// The admission or the request is not admissible. + public Task ExecuteAsync( + PlatformAdmission admission, + TenantId tenantId, + IRequest request, + CancellationToken cancellationToken = default) + where TResponse : IResultBase => + ExecuteAsync(admission, tenantId, null, request, cancellationToken); + + /// + /// Runs for and, for a closure's fan-out alone, + /// under (ADR-0102 Amendment 2): the context it installs + /// carries that organization, so the ordinary transaction behavior announces the group's tenant and organization and the + /// group's organization-bound rows are writable. An organization named for any other operation is refused before the + /// admission is spent. + /// + /// The admission, the request or the group is not admissible. public async Task ExecuteAsync( PlatformAdmission admission, TenantId tenantId, + OrganizationId? organizationId, IRequest request, CancellationToken cancellationToken = default) where TResponse : IResultBase @@ -51,7 +68,9 @@ public async Task ExecuteAsync( ArgumentNullException.ThrowIfNull(request); if (!PlatformOperations.IsRegistered(admission.Operation) || !admission.Operation.RunsInPipeline || !acts.TryGet(request.GetType(), out var act) || !ReferenceEquals(act.Operation, admission.Operation) - || !StronglyTypedId.IsAssigned(tenantId) || tenantId == TenantId.PlatformSentinel) + || !StronglyTypedId.IsAssigned(tenantId) || tenantId == TenantId.PlatformSentinel + || organizationId is { } organization && (!ReferenceEquals(admission.Operation, PlatformOperations.ClosureFanOut) + || !StronglyTypedId.IsAssigned(organization) || organization.Value == Guid.Empty)) { throw new InvalidOperationException("The operator act is not admissible."); } @@ -73,7 +92,7 @@ public async Task ExecuteAsync( { // Install in this async method, not a helper: an AsyncLocal write in a helper does not // flow back to this scope's later resolutions. - ITenantContext context = new OperatorTenantContext(tenantId, admission.Operator.CorrelationId); + ITenantContext context = new OperatorTenantContext(tenantId, organizationId, admission.Operator.CorrelationId); accessor.Current = context; var source = services.GetServices().OfType().Single(); diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs index fd29ad299..274a1e396 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorMetrics.cs @@ -35,6 +35,9 @@ public static class PlatformOperatorMetrics /// Federation operator calls by operation and outcome (ADR-0099 Amendment 10). public const string FederationCounterName = "learnstack_platform_operator_federation_total"; + /// Data-request operator calls by operation and outcome (ADR-0107 § 8). + public const string DataRequestCounterName = "learnstack_platform_operator_data_requests_total"; + /// Issuer metadata or key fetches that failed or were refused (no label). public const string MetadataFailureCounterName = "learnstack_platform_operator_metadata_failures_total"; @@ -58,6 +61,9 @@ public static class PlatformOperatorMetrics private static readonly Counter FederationCalls = Meter.CreateCounter(FederationCounterName, description: "Operator federation calls by operation and outcome."); + private static readonly Counter DataRequestCalls = + Meter.CreateCounter(DataRequestCounterName, description: "Operator data-request calls by operation and outcome."); + private static readonly Counter AuditFailures = Meter.CreateCounter(AuditFailureCounterName, description: "Operator acts refused because the MUST row was not durable."); @@ -141,6 +147,18 @@ public static void Federation(PlatformOperation operation, string outcome) => FederationCalls.Add(1, new KeyValuePair("operation", operation.AuditSlug), new KeyValuePair("outcome", outcome)); + /// + /// Counts one data-request call by how it ended: an inspection's ok or invalid_cursor, or a completion's + /// completed, already_completed, not_found, not_erasure, closure_fanout or + /// not_awaiting; either may end unavailable, or commit_unknown when a completion's commit may + /// have landed. A refused MUST row is audit_unavailable and an unexpected failure (answered 500) is + /// failed. A closure's fan-out counts each participant group once: fan_out_started, + /// fan_out_adopted, fan_out_waiting or fan_out_failed. + /// + public static void DataRequest(PlatformOperation operation, string outcome) => + DataRequestCalls.Add(1, new KeyValuePair("operation", operation.AuditSlug), + new KeyValuePair("outcome", outcome)); + /// Counts an act that was refused because its MUST row could not be written. public static void AuditFailed(PlatformOperation operation) => AuditFailures.Add(1, new KeyValuePair("operation", operation.AuditSlug)); diff --git a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorOperationSource.cs b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorOperationSource.cs index 2fbe33a5e..1d67b650a 100644 --- a/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorOperationSource.cs +++ b/backend/src/LearnStack.Infrastructure/PlatformOperator/PlatformOperatorOperationSource.cs @@ -22,6 +22,10 @@ namespace LearnStack.Infrastructure.PlatformOperator; /// The descriptor carries the operator attribution of the admission, which the audit composer /// records as metadata.operator and the reason slug. It carries no ticket. /// +/// +/// A frame whose context names an organization is evidence only for a closure's fan-out (ADR-0102 +/// Amendment 2), which the executor alone builds that way. +/// /// internal sealed class PlatformOperatorOperationSource( IOperationPolicyCatalog policies, @@ -72,6 +76,8 @@ internal IDisposable Enter(PlatformAdmission admission, ITenantContext context) protected override bool IsEvidenceCurrent(object? evidence) => evidence is Frame frame && ReferenceEquals(frame, _frame) && frame.IsOpen && frame.Context.HostScope is null && frame.Context.UserId is null + && (frame.Context.OrganizationId is null + || ReferenceEquals(frame.Admission.Operation, PlatformOperations.ClosureFanOut)) && frame.Context.IsResolved && frame.Context.Origin == TenantContextOrigin.Ambient && ReferenceEquals(accessor.Current, frame.Context); diff --git a/backend/src/LearnStack.SharedKernel/Audit/AuditRedaction.cs b/backend/src/LearnStack.SharedKernel/Audit/AuditRedaction.cs new file mode 100644 index 000000000..b9b3b9df4 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Audit/AuditRedaction.cs @@ -0,0 +1,323 @@ +using System.Collections.Frozen; +using System.Collections.Immutable; +using System.Data.Common; +using System.Text; +using System.Text.Json; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Platform; + +namespace LearnStack.SharedKernel.Audit; + +/// +/// The one executor of privileged audit redaction +/// (ADR-0108 § 2). +/// +/// +/// +/// One caller, one site. The platform scope's handle is the only caller, and it passes the operation's +/// admission, so the executor refuses unless that admission names the operation ADR-0108 sanctions for the plan's +/// pass: audit.redaction.apply for an erasure's, and the closure's Finalize (ADR-0107 § 7) for a closure's tenant +/// and sentinel passes. The implementation lives in +/// LearnStack.Infrastructure.Audit, is resolved by dependency injection so +/// LearnStack.Infrastructure gains no reference to it, and is the single file the append-only architecture +/// test names as a sanctioned redaction site. Modules never write audit_log; they only declare where their +/// person references live (IUserReferenceLocator). +/// +/// +/// The caller's transaction. The executor runs on the scope's own connection and work transaction, so the +/// redaction commits or rolls back with what that transaction carries: an erasure's status change and result row, or a +/// closure Finalize's intent row (ADR-0108 § 8). Its statements are fixed and parameterized, idempotent, and touch only +/// the six columns the platform role may update. +/// +/// +public interface IAuditRedactor +{ + /// Redacts the subject's audit rows for the plan and reports what changed and what survives. + /// The admission does not name a sanctioned operation. + Task RedactAsync( + AuditRedactionPlan plan, + PlatformAdmission admission, + DbConnection connection, + DbTransaction transaction, + CancellationToken cancellationToken = default); +} + +/// The closed kinds of redaction: an erasure's privileged step, and a closure's two kinds of pass. +/// Zero is deliberately undefined, so an unassigned pass is never a valid one. +public enum AuditRedactionPass +{ + /// + /// An erasure request's privileged step (complete_erasure): one group's request, reaching the whole tenant or + /// the group's organization by who asked (ADR-0108 § 4). + /// + Erasure = 1, + + /// + /// A closure's pass over one participant tenant (the closure's Finalize, ADR-0107 § 7): the whole tenant, by the + /// subject and every Membership the person holds there in any group. + /// + ClosureTenant = 2, + + /// + /// A closure's pass over the platform sentinel tenant (the closure's Finalize): the subject's global creation and its + /// failed and undetermined attempts, found by the subject key in their metadata (ADR-0108 § 4). + /// + ClosureSentinel = 3, +} + +/// +/// What one redaction concerns: an erasure request's immutable subject, group, origin and frozen Membership +/// identifiers, or one pass of a closure's Finalize (ADR-0108 § 4). +/// +/// +/// +/// One record, three closed shapes. says which; the erasure's is built from the request's +/// subject by the constructor, and a closure's two passes by and +/// , the only other ways to build one. It stays one sealed record rather than a +/// hierarchy because the executor port and the scope handle take one plan type, which test doubles implement, and an +/// erasure plan keeps exactly the members it had: a closure's pass is not one request's, so only the erasure carries a +/// , and every plan carries what the selection reads (, +/// , , , and, +/// for the sentinel pass, ). +/// +/// +/// The reach. An erasure the person filed, and the fan-out erasure of a closure, selects across the whole tenant; +/// an administrator's request selects only rows whose organization_id is the group's ( is +/// ), so an organization administrator never alters another branch's records. A row is selected +/// when its actor_user_id is the subject, its entity_id is the subject or one of the Memberships, or a +/// declared reference holds one of those identifiers. A closure's tenant pass is that whole-tenant selection with every +/// Membership the person holds in the tenant, so one pass covers all of the person's groups there; its sentinel pass +/// reaches the platform sentinel tenant, where a row is selected by the subject key in its metadata, by the subject as +/// its actor, or by the subject's User as its entity. +/// +/// +public sealed record AuditRedactionPlan +{ + private readonly UserDataSubject? _subject; + + /// The plan of an erasure request's privileged step, from the request's own subject. + /// + /// The subject is not an erasure's: an export is never redacted, and a closure's passes are built by + /// and . + /// + public AuditRedactionPlan(UserDataSubject subject) + { + ArgumentNullException.ThrowIfNull(subject); + if (subject.Kind != DataRequestKind.Erasure) + { + throw new ArgumentException( + "Only an erasure request's subject is a redaction plan: an export is never redacted, and a closure's passes are built by their own factories.", + nameof(subject)); + } + + _subject = subject; + Pass = AuditRedactionPass.Erasure; + TenantId = subject.Group.TenantId; + OrganizationId = subject.Group.OrganizationId; + WholeTenant = subject.Origin != DataRequestOrigin.Administrator; + SubjectUserId = subject.SubjectUserId; + MembershipIds = subject.MembershipIds; + } + + private AuditRedactionPlan(AuditRedactionPass pass, TenantId tenantId, UserId subjectUserId, + ImmutableArray membershipIds, IdentitySubjectKey? subjectKey) + { + Pass = pass; + TenantId = tenantId; + OrganizationId = null; + WholeTenant = true; + SubjectUserId = subjectUserId; + MembershipIds = membershipIds; + SubjectKey = subjectKey; + } + + /// + /// A closure's pass over one participant tenant: the whole tenant, by the subject and every Membership the person + /// holds there, of any status and in any group (ADR-0107 § 7, ADR-0108 § 4). + /// + /// The participant tenant; never the platform sentinel, whose pass is . + /// The closing person. + /// + /// Every Membership the person holds in the tenant, tombstones included: at least one, distinct, and at most + /// , the bound an erasure's snapshot already carries and + /// , which a closure's Begin judges before the person leaves Active. + /// A pass with that many compares each row with hundreds of identifiers; the executor's filter looks them up as a set, + /// so the pass costs what an erasure's does. + /// + /// An identifier is unassigned or a system one, or the Memberships are empty, duplicated or too many. + public static AuditRedactionPlan ForClosureTenant(TenantId tenantId, UserId subjectUserId, IEnumerable membershipIds) + { + ArgumentNullException.ThrowIfNull(membershipIds); + if (!StronglyTypedId.IsAssigned(tenantId) || tenantId == TenantId.PlatformSentinel) + { + throw new ArgumentException("A closure's tenant pass names a real participant tenant, never the platform sentinel.", nameof(tenantId)); + } + + RequirePerson(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 closure's tenant pass names the person's bounded, distinct Memberships in the tenant.", nameof(membershipIds)); + } + + return new AuditRedactionPlan(AuditRedactionPass.ClosureTenant, tenantId, subjectUserId, memberships, subjectKey: null); + } + + /// + /// A closure's pass over the platform sentinel tenant: the subject's global creation and its failed and undetermined + /// attempts, which carry the subject key in their metadata (ADR-0108 § 4). + /// + /// The closing person. + /// The person's subject key, as the users row holds it. + /// The subject is unassigned or a system one. + public static AuditRedactionPlan ForClosureSentinel(UserId subjectUserId, IdentitySubjectKey subjectKey) + { + ArgumentNullException.ThrowIfNull(subjectKey); + RequirePerson(subjectUserId); + return new AuditRedactionPlan(AuditRedactionPass.ClosureSentinel, TenantId.PlatformSentinel, subjectUserId, [], subjectKey); + } + + /// Which of the closed shapes this plan is, and so which operation may redact it. + public AuditRedactionPass Pass { get; } + + /// The erasure request's frozen subject, group, origin and Membership identifiers. + /// The plan is a closure's pass, which is not one request's. + public UserDataSubject Subject => + _subject ?? throw new InvalidOperationException("A closure's pass is not one request's and has no request subject."); + + /// The tenant the selection reaches: the request's, the participant's, or the platform sentinel. + public TenantId TenantId { get; } + + /// The erasure group's organization; for the tenant-wide group and every closure pass. + public OrganizationId? OrganizationId { get; } + + /// + /// Whether the selection spans the whole tenant (a person's own request, a closure's fan-out erasure and every + /// closure pass) rather than the group's organization alone (an administrator's request). + /// + public bool WholeTenant { get; } + + /// The person whose rows are redacted. + public UserId SubjectUserId { get; } + + /// The Membership identifiers the selection compares; empty for the sentinel pass, whose tenant has none. + public ImmutableArray MembershipIds { get; } + + /// The person's subject key; set for the sentinel pass alone, which selects by it. + public IdentitySubjectKey? SubjectKey { get; } + + /// Never prints the subject, the tenant, the Memberships or the key. + public override string ToString() => nameof(AuditRedactionPlan); + + private static void RequirePerson(UserId subjectUserId) + { + if (!StronglyTypedId.IsAssigned(subjectUserId) || subjectUserId == UserId.SystemActor) + { + throw new ArgumentException("A closure's pass redacts a real person's rows.", nameof(subjectUserId)); + } + } +} + +/// The six audit_log columns the platform role may update, and so the only ones a redaction touches. +public enum AuditRedactedColumn +{ + IpAddress = 1, + UserAgent = 2, + ActorEmail = 3, + BeforeState = 4, + AfterState = 5, + Changes = 6, +} + +/// The stored spelling of , which is the column name. +public static class AuditRedactionCodes +{ + public static ClosedCodeTable Columns { get; } = new( + (AuditRedactedColumn.IpAddress, "ip_address"), + (AuditRedactedColumn.UserAgent, "user_agent"), + (AuditRedactedColumn.ActorEmail, "actor_email"), + (AuditRedactedColumn.BeforeState, "before_state"), + (AuditRedactedColumn.AfterState, "after_state"), + (AuditRedactedColumn.Changes, "changes")); +} + +/// +/// What a redaction did and what survives it, as closed counts and never a person identifier (ADR-0108 § 3, § 6). +/// +/// +/// is a partial list: a kind absent from it is not zero. Its kinds come from ADR-0107 § 6's +/// closed vocabulary (the audit actor, entity and metadata references and the rows the selection could not reach). +/// +public sealed record AuditRedactionReport +{ + /// A count is negative or a column or kind is undefined. + public AuditRedactionReport( + long rowsSelected, + IReadOnlyDictionary redacted, + IReadOnlyCollection retained) + { + ArgumentOutOfRangeException.ThrowIfNegative(rowsSelected); + ArgumentNullException.ThrowIfNull(redacted); + ArgumentNullException.ThrowIfNull(retained); + if (redacted.Any(entry => !Enum.IsDefined(entry.Key) || entry.Value < 0) + || retained.Select(entry => entry.Kind).Distinct().Count() != retained.Count) + { + throw new ArgumentOutOfRangeException(nameof(redacted), "A redaction report holds defined columns, distinct kinds and no negative count."); + } + + RowsSelected = rowsSelected; + Redacted = Enum.GetValues().ToFrozenDictionary( + column => column, column => redacted.TryGetValue(column, out var count) ? count : 0L); + Retained = [.. retained.OrderBy(entry => entry.Kind)]; + } + + /// The rows the plan's selection matched. + public long RowsSelected { get; } + + /// The rows changed per column; every column is present, zero when none changed. + public FrozenDictionary Redacted { get; } + + /// The retained kinds and counts, ordered by kind. + public ImmutableArray Retained { get; } + + /// + /// The closed JSON a result row's after_state holds: + /// {"rows_selected":n,"redacted":{column:n,...},"retained":{kind:n,...}}, small and bounded by the two + /// closed vocabularies. + /// + public string ToClosedJson() + { + using var stream = new MemoryStream(); + using (var writer = new Utf8JsonWriter(stream)) + { + WriteTo(writer); + } + + return Encoding.UTF8.GetString(stream.ToArray()); + } + + /// Writes the closed object returns as the writer's next value. + internal void WriteTo(Utf8JsonWriter writer) + { + writer.WriteStartObject(); + writer.WriteNumber("rows_selected", RowsSelected); + writer.WriteStartObject("redacted"); + foreach (var column in Enum.GetValues()) + { + writer.WriteNumber(AuditRedactionCodes.Columns.ToCode(column), Redacted[column]); + } + + writer.WriteEndObject(); + writer.WriteStartObject("retained"); + foreach (var entry in Retained) + { + writer.WriteNumber(DataRequestCodes.RetainedKinds.ToCode(entry.Kind), entry.Count); + } + + writer.WriteEndObject(); + writer.WriteEndObject(); + } +} diff --git a/backend/src/LearnStack.SharedKernel/Audit/AuditRedactionAggregate.cs b/backend/src/LearnStack.SharedKernel/Audit/AuditRedactionAggregate.cs new file mode 100644 index 000000000..b5f17d318 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Audit/AuditRedactionAggregate.cs @@ -0,0 +1,141 @@ +using System.Collections.Frozen; +using System.Text; +using System.Text.Json; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.SharedKernel.Audit; + +/// +/// A closure Finalize's redaction summed over its passes: one report per participant tenant and one for the platform +/// sentinel tenant, as closed counts and never a person identifier +/// (ADR-0108 §§ 3, 8). +/// +/// +/// +/// Where each part goes. is the closed document the Finalize's platform-wide rows +/// carry in after_state under the platform sentinel tenant: its intent row, which is the redaction's MUST evidence, +/// and its result row. Each participant tenant's own report in is what that tenant's fan-out +/// request records as its retained audit kinds, its tenant's own evidence (ADR-0107 § 8), and the retained kinds of +/// are what the closure request records. +/// +/// +/// Bounded however many tenants. The document lists the tenant identifiers (not personal data) with the rows the +/// redaction selected in each only up to ; beyond, it carries the tenant count and the +/// totals alone (ADR-0108 § 8). A listed entry is one identifier and one count, and the platform and total reports are +/// closed objects over the two closed vocabularies, so the document stays under +/// whatever the counts: half of the 32 KiB a row's state may hold, which leaves the rest to the owner's own closed fields. +/// +/// +/// Summing. adds every pass, the platform pass included: the rows selected, the rows changed +/// per column, and each retained kind any pass reports. A closure's passes all reach their whole tenant and each reports +/// the same three kinds (the audit actor, entity and metadata references), so each total is exact; a kind that some pass +/// left out would be a lower bound, because a report's list is partial and an absent kind is not zero. +/// +/// +public sealed record AuditRedactionAggregate +{ + /// The most tenants whose rows selected the document lists by identifier (ADR-0108 § 8). + public const int MaximumListedTenants = 200; + + /// + /// The most bytes returns. At the listing's bound, each listed entry is a 36-character + /// identifier and a count of at most 19 digits (59 bytes with its quotes and separators, 11,800 for 200), and each of + /// the two reports at most about 1,000 bytes with every column and all sixteen retained kinds at 19 digits. + /// + public const int MaximumClosedJsonBytes = 16 * 1024; + + /// Sums a Finalize's passes. + /// Each participant tenant's pass, keyed by its tenant; may be empty when no group is served. + /// The pass over the platform sentinel tenant. + /// A tenant is unassigned, is the platform sentinel, or has no report. + /// A total does not fit a 64-bit count. + public AuditRedactionAggregate(IReadOnlyDictionary tenants, AuditRedactionReport platform) + { + ArgumentNullException.ThrowIfNull(tenants); + ArgumentNullException.ThrowIfNull(platform); + if (tenants.Any(entry => !StronglyTypedId.IsAssigned(entry.Key) || entry.Key == TenantId.PlatformSentinel || entry.Value is null)) + { + throw new ArgumentException( + "A closure's tenant passes are keyed by real participant tenants, never the platform sentinel, and each has its report.", + nameof(tenants)); + } + + Tenants = tenants.ToFrozenDictionary(); + Platform = platform; + Total = Sum([.. tenants.Values, platform]); + } + + /// Each participant tenant's report. + public FrozenDictionary Tenants { get; } + + /// The report of the pass over the platform sentinel tenant. + public AuditRedactionReport Platform { get; } + + /// Every pass summed, the platform pass included. + public AuditRedactionReport Total { get; } + + /// Whether lists each tenant's rows selected, which it does up to . + public bool ListsTenants => Tenants.Count <= MaximumListedTenants; + + /// + /// The closed document: + /// {"tenant_count":n,"rows_selected_by_tenant":{tenant:n,...},"platform":{report},"total":{report}}, where each + /// report is 's object and rows_selected_by_tenant, ordered by + /// tenant identifier, is present only while . + /// + public string ToClosedJson() + { + using var stream = new MemoryStream(); + using (var writer = new Utf8JsonWriter(stream)) + { + writer.WriteStartObject(); + writer.WriteNumber("tenant_count", Tenants.Count); + if (ListsTenants) + { + writer.WriteStartObject("rows_selected_by_tenant"); + foreach (var (tenant, report) in Tenants + .Select(entry => (Tenant: entry.Key.Value.ToString("D"), entry.Value)) + .OrderBy(entry => entry.Tenant, StringComparer.Ordinal)) + { + writer.WriteNumber(tenant, report.RowsSelected); + } + + writer.WriteEndObject(); + } + + writer.WritePropertyName("platform"); + Platform.WriteTo(writer); + writer.WritePropertyName("total"); + Total.WriteTo(writer); + writer.WriteEndObject(); + } + + return Encoding.UTF8.GetString(stream.ToArray()); + } + + /// Never prints a tenant. + public override string ToString() => nameof(AuditRedactionAggregate); + + private static AuditRedactionReport Sum(IReadOnlyCollection reports) + { + long selected = 0; + var redacted = Enum.GetValues().ToDictionary(column => column, _ => 0L); + var retained = new SortedDictionary(); + foreach (var report in reports) + { + selected = checked(selected + report.RowsSelected); + foreach (var (column, count) in report.Redacted) + { + redacted[column] = checked(redacted[column] + count); + } + + foreach (var entry in report.Retained) + { + retained[entry.Kind] = checked(retained.GetValueOrDefault(entry.Kind) + entry.Count); + } + } + + return new AuditRedactionReport(selected, redacted, [.. retained.Select(entry => new RetainedReferenceCount(entry.Key, entry.Value))]); + } +} diff --git a/backend/src/LearnStack.SharedKernel/Audit/IAuditStateCapture.cs b/backend/src/LearnStack.SharedKernel/Audit/IAuditStateCapture.cs index e82e21758..c53a0bcfc 100644 --- a/backend/src/LearnStack.SharedKernel/Audit/IAuditStateCapture.cs +++ b/backend/src/LearnStack.SharedKernel/Audit/IAuditStateCapture.cs @@ -92,6 +92,20 @@ void AttachAuthorization(AuthorizationAuditContext context) => void AttachProviderEvent(ProviderEventAuditEvidence evidence) => throw new InvalidOperationException("This capture has no provider evidence attachment owner."); + /// + /// Withdraws the innermost frame's one unclaimed provider observation intent, declared for the delivery + /// names, before anything is written: the mirror's subscriber refuses a person whose User + /// is no longer Active (ADR-0107 §§ 7, 9), and an observation it refuses has no row, because its row would carry + /// that person's identifier into the tenant's log after the closure began. + /// + /// + /// Only the validated mirror subscriber calls it, with the evidence it alone mints, and only while the intent is still + /// pending; the delivery's inbox row then records that the delivery ran. Every other intent, and every other + /// operation's, is untouched. + /// + void WithholdProviderEvent(ProviderEventAuditEvidence evidence) => + throw new InvalidOperationException("This capture has no provider evidence attachment owner."); + /// /// The rows are on the ambient transaction. Not durable — the transaction has /// not committed. IAuditStore.WritePendingAsync. diff --git a/backend/src/LearnStack.SharedKernel/DataProtection/ClosedCodeTable.cs b/backend/src/LearnStack.SharedKernel/DataProtection/ClosedCodeTable.cs new file mode 100644 index 000000000..40b1a352a --- /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/ClosureLimits.cs b/backend/src/LearnStack.SharedKernel/DataProtection/ClosureLimits.cs new file mode 100644 index 000000000..5cc4457bb --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/DataProtection/ClosureLimits.cs @@ -0,0 +1,50 @@ +namespace LearnStack.SharedKernel.DataProtection; + +/// +/// The size a global account closure is admitted for (ADR-0107 § 7). Begin judges it before the person's User leaves +/// Active, because every later step of the closure is bounded by it and Closing cannot be undone: a person past it is +/// refused with nothing changed, never moved to Closing and then stranded. +/// +/// +/// +/// Groups. bounds the participant groups Begin and Finalize read under the +/// person's User fence, the groups the fan-out is handed in one call, and so the tenant fences one closure holds. It counts +/// every group in which the person holds a Membership of any status, served or not, because Finalize fences and redacts +/// every participant tenant whatever its lifecycle. +/// +/// +/// Memberships. In each participant tenant the person may hold at most +/// Memberships of any status, Revoked tombstones included: the +/// bound of one group's fan-out snapshot and of one tenant pass of Finalize's redaction, and a group never holds more than +/// its tenant. +/// +/// +/// A person past either bound is served by Phase 11's data operations, not by this closure. +/// +/// +public static class ClosureLimits +{ + /// The most participant groups, served or unserved, one closure is admitted for. + public const int MaximumParticipantGroups = 256; + + /// + /// The most Memberships, of any status, the person may hold in one participant tenant: the snapshot bound one group's + /// fan-out freezes and one tenant pass of the redaction compares. + /// + public const int MaximumTenantMemberships = DataRequestLimits.MaximumSnapshotMemberships; + + /// + /// The most Memberships one admitted closure can hold across its participant tenants: every group in a tenant of its + /// own, each at the tenant bound. Finalize reads at most this many and treats more as a defect. + /// + public const int MaximumMemberships = MaximumParticipantGroups * MaximumTenantMemberships; + + /// + /// Whether a person with these participant groups and this many Memberships in their fullest tenant is within the + /// bounds a closure is admitted for. A person with no Membership is not a size question: no closure is filed for one. + /// + /// The participant groups, served or not. + /// The most Memberships of any status the person holds in one participant tenant. + public static bool Admits(int groups, int mostTenantMemberships) => + groups <= MaximumParticipantGroups && mostTenantMemberships <= MaximumTenantMemberships; +} diff --git a/backend/src/LearnStack.SharedKernel/DataProtection/DataExportTruncation.cs b/backend/src/LearnStack.SharedKernel/DataProtection/DataExportTruncation.cs new file mode 100644 index 000000000..bcef6ba10 --- /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 new file mode 100644 index 000000000..222bb2c56 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/DataProtection/DataRequestLimits.cs @@ -0,0 +1,155 @@ +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); + + /// + /// How long after it fell due a request may stay fulfilling before the operator inspection lists it as + /// stuck (ADR-0107 § 8). An export or an erasure job commits its whole run in one transaction, so a durable + /// fulfilling is a run that died, or a closure's fan-out erasure whose job has not finished. Two hours + /// outlast the job runtime's whole retry schedule (five waits totalling about 66 minutes and six attempts of at + /// most five minutes each), so a request listed here waits for no retry that is still coming. Only the inspection reads it; + /// no database check repeats it. + /// + public static readonly TimeSpan StuckFulfillingAfter = TimeSpan.FromHours(2); + + /// + /// The most unconsumed, unexpired download tickets one session binding may hold over one artifact: a download + /// in progress, a retry and one spare. The next mint in that session waits for one to be consumed by its final + /// chunk or to expire (); a ticket left open by a credential since refreshed does + /// not count against the new one. + /// + public const int MaximumOpenTicketsPerBinding = 3; + + /// + /// The most download tickets ever minted over one artifact, consumed or not. A ticket row and its MUST audit row + /// are permanent receipts, so the artifact's downloads are bounded; past the bound the artifact is downloaded no + /// more and a new export is filed. + /// + public const int MaximumTicketsPerArtifact = 20; + + /// 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 cap on the invitations a person issued inside the Identity section, newest first: unlike the + /// invitations a person accepted it grows with administrative work, so it truncates with a stated + /// truncated entry rather than fail the request with export_too_large. + /// + public const long IssuedInvitationsCollectionBytes = 4L * 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 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) => + 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 000000000..0170319f7 --- /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 000000000..4b87ce7d5 --- /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 000000000..7a7c6a305 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/DataProtection/IDataExportArtifactStore.cs @@ -0,0 +1,176 @@ +using System.Collections.Immutable; +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). +/// +/// +/// +/// 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 +/// 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); + + /// + /// Whether the store's key ring still holds the key a chunk sealed under opens with; + /// a ticket is minted only for an artifact this answers true for, so a retired key is a refusal before any read. + /// + bool CanOpen(string keyVersion); + + /// Decrypts one chunk of an available, unexpired artifact. + /// + /// 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 the store cannot + /// open (its key left the ring, or it fails authentication because the stored ciphertext is corrupt or + /// forged) is also answered , after the store records it at critical severity with + /// identifiers only: the reader meets the one uniform refusal and nothing about the failure leaves. + /// + /// The storage failed or outlived its statement budget. + 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. + /// + /// + /// 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. +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, IEnumerable? truncations = null) + { + 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); + Truncations = DataExportTruncation.Normalize(truncations); + 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; } + + /// 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, + ImmutableArray Truncations, bool IsReadable); + +/// 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/IDataExportBundleBuilder.cs b/backend/src/LearnStack.SharedKernel/DataProtection/IDataExportBundleBuilder.cs new file mode 100644 index 000000000..baad82219 --- /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/IDataRequestEligibility.cs b/backend/src/LearnStack.SharedKernel/DataProtection/IDataRequestEligibility.cs new file mode 100644 index 000000000..9b65ced3d --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/DataProtection/IDataRequestEligibility.cs @@ -0,0 +1,128 @@ +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. A closure is asked only at creation: its execution +/// re-check is its Begin's, across every participant tenant (ADR-0107 § 7), which leaves it +/// 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 000000000..5a1004586 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/DataProtection/IDataRequestHoldSource.cs @@ -0,0 +1,74 @@ +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. +/// +/// +/// A closure's query concerns the whole person. A closure is global: its Begin asks once, with +/// , the person and the group the closure was filed in, and never asks per +/// participant group, and a closure's fan-out erasures start fulfilling and ask nothing. A source therefore answers +/// a query for a hold on the person in any group, the named group being only where +/// the closure was filed. Begin asks it while it holds every participant tenant's fence, so a source answers without I/O +/// that could outlast those fences (ADR-0107 § 7). +/// +/// +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 000000000..d2203057e --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/DataProtection/IUserDataParticipant.cs @@ -0,0 +1,214 @@ +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; } + + /// + /// 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; + + /// + /// The participant's caps on single collections of its section, in bytes: a collection that can grow without a + /// bound of its own (the invitations a person issued, ) + /// truncates instead of filling the bundle. Empty by default. A record that would pass its collection's cap is + /// refused with , as for the section cap, and the participant + /// declares that collection's truncation. + /// + IReadOnlyDictionary ExportCollectionCapBytes => ImmutableDictionary.Empty; + + /// 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 (the audit section's 8 MiB, ADR-0107 § 3) or the record's collection cap is reached, + /// either at most half the bundle ceiling; the record was not written, and the participant declares that + /// collection's truncation and stops writing it. + /// + 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/LearnStack.SharedKernel/DataProtection/UserDataExportRecord.cs b/backend/src/LearnStack.SharedKernel/DataProtection/UserDataExportRecord.cs new file mode 100644 index 000000000..49309dd2e --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/DataProtection/UserDataExportRecord.cs @@ -0,0 +1,47 @@ +using System.Buffers; +using System.Text.Json; + +namespace LearnStack.SharedKernel.DataProtection; + +/// +/// Writes one export record into a section through a short-lived buffer that is overwritten with zeros afterwards. +/// +/// +/// Plaintext hygiene here is best effort: the buffer this method owns is cleared, but an +/// that grows leaves its earlier, smaller arrays to the garbage collector uncleared, +/// and the JSON writer, the participant's own strings and the runtime may hold further copies. Process and crash dumps +/// of the API therefore hold personal data and are handled as such (Data Protection § Right of Access). +/// +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 of its current array; nothing is written beyond it. + buffer.Clear(); + } + } +} diff --git a/backend/src/LearnStack.SharedKernel/DataProtection/UserDataParticipantGuard.cs b/backend/src/LearnStack.SharedKernel/DataProtection/UserDataParticipantGuard.cs new file mode 100644 index 000000000..1c170574e --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/DataProtection/UserDataParticipantGuard.cs @@ -0,0 +1,26 @@ +using LearnStack.SharedKernel.Tenancy; + +namespace LearnStack.SharedKernel.DataProtection; + +/// +/// The group check every makes before it reads: a participant reads only the +/// announced group of its request +/// (ADR-0107 § 1). +/// +public static class UserDataParticipantGuard +{ + /// + /// Refuses a subject whose group is not the ambient context's tenant and organization. The job announces the + /// request's group before it calls a participant, so a mismatch is a programming error, never a refusal. + /// + /// The subject's group is not the announced group. + public static void RequireGroup(UserDataSubject subject, ITenantContext tenant) + { + ArgumentNullException.ThrowIfNull(subject); + ArgumentNullException.ThrowIfNull(tenant); + 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/LearnStack.SharedKernel/DataProtection/UserReferenceLocator.cs b/backend/src/LearnStack.SharedKernel/DataProtection/UserReferenceLocator.cs new file mode 100644 index 000000000..f144591ee --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/DataProtection/UserReferenceLocator.cs @@ -0,0 +1,317 @@ +using System.Collections.Immutable; +using LearnStack.SharedKernel.Domain; + +namespace LearnStack.SharedKernel.DataProtection; + +/// +/// One module's declaration of where its audited entities hold a person or Membership reference in an audit row's +/// before_state, after_state and changes +/// (ADR-0108 § 7). +/// +/// +/// +/// A declaration, not an actor. A locator runs no SQL, holds no privilege and never names the audit table: the +/// Audit-owned executor behind IAuditRedactor applies every module's declarations on the platform scope. That +/// reconciles Audit Subsystem § 10 (the module knows where its references are) with Data Protection (the module never +/// reaches the log). The composition root collects the implementations, as it collects IAuditCatalogSource; +/// no module references another module's locator. +/// +/// +/// Every reference is either redactable or retained. The architecture census reads each module's mapped +/// model: every person-reference property of an audited entity, and of what that entity contains, is in exactly one +/// of the two lists; a plain that is neither, nor its entity's own single-column key, fails it unless +/// the census lists it as naming no person; and every path a module declares has a canary that embeds a reference there +/// and proves the executor removes it. +/// +/// +public interface IUserReferenceLocator +{ + /// The references the redaction replaces when they hold the request's subject or one of its Memberships. + IReadOnlyCollection Redactable { get; } + + /// The references deliberately kept, each with the reported kind that already counts it and the reason. + IReadOnlyCollection Retained { get; } +} + +/// What a declared reference holds, which fixes the identifiers it is compared with (ADR-0108 § 5). +/// Zero is deliberately undefined, so an unassigned kind is never a valid one. +public enum UserReferenceKind +{ + /// A person's UserId: compared with the request's subject. + User = 1, + + /// A Membership identifier: compared with the request's frozen Membership snapshot. + Membership = 2, +} + +/// The closed path grammar: where a reference sits inside one entity's captured snapshot. +/// +/// The three forms are what the capture writes (CapturedEntityChange, ADR-0044 Amendment 6 §§ 4, 5): a +/// property of the entity, a property of each member of a collection the entity contains (keyed by the member's own +/// key, never an array index), and a property whose stored value is an array of identifiers. A deeper or another +/// shape is not expressible, so a model that adds one fails the census until the grammar grows by decision. +/// +public enum UserReferenceShape +{ + /// Name: the entity's own property. + Property = 1, + + /// Navigation/*/Name: the property of every member of a contained collection. + Member = 2, + + /// Name/*: every element of a property whose value is an array of identifiers. + Elements = 3, +} + +/// One path of the closed grammar, built only through its three factories. +/// +/// A name is an EF model property or navigation name: an ASCII identifier, so it is one RFC 6901 reference token +/// that needs no escaping and spells the same in a snapshot key and in a changes path. +/// +public sealed record UserReferencePath +{ + /// The longest name a path accepts: an identifier, never a document. + public const int MaximumNameLength = 128; + + private UserReferencePath(UserReferenceShape shape, string? navigation, string property) + { + if (!IsName(property) || (navigation is not null && !IsName(navigation))) + { + throw new ArgumentException("A reference path names an identifier property and navigation.", nameof(property)); + } + + Shape = shape; + Navigation = navigation; + Property = property; + } + + public UserReferenceShape Shape { get; } + + /// The contained collection's navigation name; unless is . + public string? Navigation { get; } + + /// The property that holds the reference. + public string Property { get; } + + /// The entity's own property: Name. + /// The name is not an identifier. + public static UserReferencePath Of(string property) => new(UserReferenceShape.Property, null, property); + + /// The property of every member of a contained collection: Navigation/*/Name. + /// A name is not an identifier. + public static UserReferencePath Member(string navigation, string property) + { + ArgumentNullException.ThrowIfNull(navigation); + return new(UserReferenceShape.Member, navigation, property); + } + + /// Every element of a property whose value is an array of identifiers: Name/*. + /// The name is not an identifier. + public static UserReferencePath Elements(string property) => new(UserReferenceShape.Elements, null, property); + + /// The path's spelling in the grammar: Name, Navigation/*/Name or Name/*. + public override string ToString() => Shape switch + { + UserReferenceShape.Member => Navigation + "/*/" + Property, + UserReferenceShape.Elements => Property + "/*", + _ => Property, + }; + + /// Whether a value is a name the grammar accepts: an ASCII identifier of bounded length. + public static bool IsName(string? value) => + value is { Length: > 0 and <= MaximumNameLength } + && (char.IsAsciiLetter(value[0]) || value[0] == '_') + && value.All(character => char.IsAsciiLetterOrDigit(character) || character == '_'); +} + +/// One redactable reference: an audited entity, a path into its snapshot, and what it holds. +/// +/// The entity is matched by its CLR name, because that is what an audit row's entity_type and a +/// changes path carry (ADR-0044 Amendment 5 § 2), so a generic or nested name is refused. +/// +public sealed record UserReferenceDeclaration +{ + /// The entity type has no plain identifier name, or the kind is undefined. + public UserReferenceDeclaration(Type entityType, UserReferencePath path, UserReferenceKind kind) + { + ArgumentNullException.ThrowIfNull(entityType); + ArgumentNullException.ThrowIfNull(path); + if (!IsEntityName(entityType) || !Enum.IsDefined(kind)) + { + throw new ArgumentException("A reference declaration names a plain entity type and a defined kind.", nameof(entityType)); + } + + EntityType = entityType; + Path = path; + Kind = kind; + } + + public Type EntityType { get; } + + public UserReferencePath Path { get; } + + public UserReferenceKind Kind { get; } + + /// The name an audit row carries in entity_type and in each changes path. + public string EntityName => EntityType.Name; + + internal static bool IsEntityName(Type type) => + !type.IsGenericType && !type.IsNested && UserReferencePath.IsName(type.Name); +} + +/// A person reference deliberately kept by the redaction, with the reported kind that already counts it. +/// +/// Only an entity's own key qualifies, the whole of a single-column key: a payload copy of the row's entity_id, +/// which ADR-0108 § 6 retains and the report counts as . +/// Redacting the copy would hide nothing the row's own column does not still show. A part of a composite key is not +/// one: the row's entity_id is then every part joined, so the copy would survive unmatched (the census refuses it). +/// +public sealed record RetainedUserReference +{ + /// + /// The entity type has no plain name, the path is not a property, the kind is not the entity reference, or the + /// reason is blank. + /// + public RetainedUserReference(Type entityType, UserReferencePath path, RetainedReferenceKind reportedAs, string reason) + { + ArgumentNullException.ThrowIfNull(entityType); + ArgumentNullException.ThrowIfNull(path); + ArgumentException.ThrowIfNullOrWhiteSpace(reason); + if (!UserReferenceDeclaration.IsEntityName(entityType) || path.Shape != UserReferenceShape.Property + || reportedAs != RetainedReferenceKind.AuditEntityReference) + { + throw new ArgumentException("A retained reference is an entity's own key, reported as the audit entity reference.", nameof(path)); + } + + EntityType = entityType; + Path = path; + ReportedAs = reportedAs; + Reason = reason; + } + + public Type EntityType { get; } + + public UserReferencePath Path { get; } + + /// The closed kind under which the redaction report counts the rows this reference survives in. + public RetainedReferenceKind ReportedAs { get; } + + /// Why the reference is kept: one line a reviewer reads. + public string Reason { get; } + + public string EntityName => EntityType.Name; +} + +/// The shared declarations every module repeats, so none of them is written per entity by hand. +public static class UserReferenceDeclarations +{ + /// The attribution columns every carries into its snapshot. + public static readonly ImmutableArray AttributionProperties = ["CreatedBy", "UpdatedBy", "DeletedBy"]; + + /// + /// The creator, updater and deleter of each named entity as redactable + /// references: the capture keeps them in every snapshot and diff (ADR-0107 § 6 retains the table columns as + /// attribution_reference; the audit payload copies are not on ADR-0108 § 6's list of survivors). + /// + /// A named type is not an . + public static IEnumerable Attribution(params Type[] auditableEntities) + { + ArgumentNullException.ThrowIfNull(auditableEntities); + if (auditableEntities.Length == 0 || !auditableEntities.All(IsAuditable)) + { + throw new ArgumentException("Attribution is declared for auditable entities.", nameof(auditableEntities)); + } + + return + [ + .. auditableEntities.SelectMany(entity => AttributionProperties.Select(property => + new UserReferenceDeclaration(entity, UserReferencePath.Of(property), UserReferenceKind.User))), + ]; + } + + /// The entity's own key, retained because the row's entity_id carries the same value. + public static RetainedUserReference OwnKey(Type entityType) => + new(entityType, UserReferencePath.Of("Id"), RetainedReferenceKind.AuditEntityReference, + "The entity's own key is the row's entity_id, which ADR-0108 § 6 retains; redacting the payload copy hides nothing."); + + private static bool IsAuditable(Type? type) + { + for (var current = type; current is not null; current = current.BaseType) + { + if (current.IsGenericType && current.GetGenericTypeDefinition() == typeof(AuditableEntity<>)) + { + return true; + } + } + + return false; + } +} + +/// +/// Every registered locator's declarations, merged once and checked: the set the redaction applies and the census +/// reads (ADR-0108 § 7). +/// +/// +/// Construction refuses a locator that declares nothing, a path declared twice (redactable or retained, by one +/// module or two), two CLR types that share a name (a row's entity_type could not tell them apart), and an +/// entity whose navigation and property names collide, so a malformed set fails where it is built rather than at +/// the first row it misreads. +/// +public sealed class UserReferenceCatalog +{ + /// The locators' declarations are empty, duplicated or ambiguous. + public UserReferenceCatalog(IEnumerable locators) + { + ArgumentNullException.ThrowIfNull(locators); + var redactable = new List(); + var retained = new List(); + foreach (var locator in locators) + { + ArgumentNullException.ThrowIfNull(locator); + if (locator.Redactable is not { Count: > 0 } declared || locator.Retained is null + || declared.Any(declaration => declaration is null) || locator.Retained.Any(reference => reference is null)) + { + throw new ArgumentException("A user reference locator declares at least one redactable reference.", nameof(locators)); + } + + redactable.AddRange(declared); + retained.AddRange(locator.Retained); + } + + var entries = redactable.Select(declaration => (declaration.EntityType, declaration.Path)) + .Concat(retained.Select(reference => (reference.EntityType, reference.Path))) + .ToList(); + var paths = entries.Select(entry => (entry.EntityType.Name, entry.Path.Navigation, entry.Path.Property)).ToList(); + if (paths.Distinct().Count() != paths.Count) + { + throw new ArgumentException("A reference path is declared twice.", nameof(locators)); + } + + if (entries.GroupBy(entry => entry.EntityType.Name, StringComparer.Ordinal) + .Any(group => group.Select(entry => entry.EntityType).Distinct().Count() > 1)) + { + throw new ArgumentException("Two declared entity types share a name an audit row cannot tell apart.", nameof(locators)); + } + + if (entries.GroupBy(entry => entry.EntityType.Name, StringComparer.Ordinal).Any(group => + group.Where(entry => entry.Path.Navigation is not null).Select(entry => entry.Path.Navigation!) + .Intersect(group.Where(entry => entry.Path.Navigation is null).Select(entry => entry.Path.Property), + StringComparer.Ordinal) + .Any())) + { + throw new ArgumentException("A navigation and a property of one entity share a name.", nameof(locators)); + } + + Redactable = [.. redactable.OrderBy(declaration => declaration.EntityName, StringComparer.Ordinal) + .ThenBy(declaration => declaration.Path.ToString(), StringComparer.Ordinal)]; + Retained = [.. retained.OrderBy(reference => reference.EntityName, StringComparer.Ordinal) + .ThenBy(reference => reference.Path.ToString(), StringComparer.Ordinal)]; + } + + /// Every redactable reference, ordered by entity name and path. + public ImmutableArray Redactable { get; } + + /// Every retained reference, ordered by entity name and path. + public ImmutableArray Retained { get; } +} diff --git a/backend/src/LearnStack.SharedKernel/Idempotency/IdempotencyReplayTarget.cs b/backend/src/LearnStack.SharedKernel/Idempotency/IdempotencyReplayTarget.cs index c530827c5..8c49969bf 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/LearnStack.SharedKernel/Identity/IIdentityProviderAccountRemoval.cs b/backend/src/LearnStack.SharedKernel/Identity/IIdentityProviderAccountRemoval.cs new file mode 100644 index 000000000..408f768c2 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Identity/IIdentityProviderAccountRemoval.cs @@ -0,0 +1,62 @@ +namespace LearnStack.SharedKernel.Identity; + +/// How the identity provider answered a request to delete one person's account. +public enum AccountRemovalOutcome +{ + /// The provider deleted the account. + Removed = 1, + + /// + /// The provider holds no such account, which is success: the closure's goal already holds. Only the provider's own + /// answer counts; a "not found" that is not the provider's (a hop in front of it) is . + /// + Absent = 2, + + /// The provider definitively refused the deletion (a configuration or authority fault). Nothing changed. + Refused = 3, + + /// + /// The provider could not be reached, or it or a hop in front of it answered with a server fault or a throttle. No + /// deletion was confirmed: a repeat finds the account absent if one had landed. + /// + Unavailable = 4, + + /// The request may have been applied: its answer was lost. A repeat is safe, because the deletion is idempotent. + Uncertain = 5, +} + +/// +/// Deletes one person's account at the identity provider, the last effect of a global account closure +/// (ADR-0107 § 7). +/// +/// +/// +/// The port is bound to IProviderResilience<IIdentityProviderAccountRemoval>. Its default implementation +/// refuses every call, so a deployment that has not configured the adapter's confined realm client fails closed and +/// no closure finishes; the Keycloak adapter is selected at the composition root when its secret is present. The +/// adapter's client holds manage-users, which can also create and update users in the shared realm: that +/// authority is why the port has one deleting method, whose single caller is the closure's Finalize, and a pure preflight +/// that Begin asks. +/// +/// +/// A missing account is success. The raw provider subject is the provider's own user identifier; it is passed in and +/// never logged, audited or stored by the port or its adapter. +/// +/// +/// The preflight. answers, with no network or provider effect, whether a deletion of the +/// subject could be sent at all: the closure's Begin asks it before the person leaves Active, so a closure that could +/// never finish is refused while nothing has changed. +/// +/// +public interface IIdentityProviderAccountRemoval +{ + /// Deletes the account whose provider subject is . + Task RemoveAsync(string providerSubject, CancellationToken cancellationToken = default); + + /// + /// Whether this port would send the deletion of : false when the port is not + /// configured, or when it refuses the subject before any network call. A pure, local answer: nothing is sent, read + /// from the provider, logged or stored, and a true answer promises nothing about the provider's own reply. + /// + bool CanRemove(string providerSubject); +} diff --git a/backend/src/LearnStack.SharedKernel/Identity/OwnDataRequestScopeWitness.cs b/backend/src/LearnStack.SharedKernel/Identity/OwnDataRequestScopeWitness.cs new file mode 100644 index 000000000..c4b63c79c --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Identity/OwnDataRequestScopeWitness.cs @@ -0,0 +1,139 @@ +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. +/// withdraws an artifact, which ADR-0107 § 4 lets the subject do on either path. +/// +public enum OwnDataRequestPurpose { List = 1, Create = 2, Read = 3, Cancel = 4, Ticket = 5, Chunk = 6, Revoke = 7 } + +/// 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/Identity/RefusingIdentityProviderAccountRemoval.cs b/backend/src/LearnStack.SharedKernel/Identity/RefusingIdentityProviderAccountRemoval.cs new file mode 100644 index 000000000..5473131e3 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Identity/RefusingIdentityProviderAccountRemoval.cs @@ -0,0 +1,22 @@ +namespace LearnStack.SharedKernel.Identity; + +/// +/// The fail-closed default while the account-removal client is not configured: every call answers +/// without any network or provider effect, so no closure finishes on a +/// deployment that has not provisioned the confined realm client +/// (ADR-0107 § 7). +/// +/// +/// The subject is never read, logged or stored. Its preflight answers false for every subject, so the closure's Begin +/// refuses before any person is moved to Closing on a deployment whose Finalize could never finish. +/// +public sealed class RefusingIdentityProviderAccountRemoval : IIdentityProviderAccountRemoval +{ + public Task RemoveAsync(string providerSubject, CancellationToken cancellationToken = default) => + Task.FromResult(AccountRemovalOutcome.Refused); + + /// Nothing is configured, so no deletion could ever be sent. + public bool CanRemove(string providerSubject) => false; + + public override string ToString() => nameof(RefusingIdentityProviderAccountRemoval); +} diff --git a/backend/src/LearnStack.SharedKernel/Permissions/OperationPolicy.cs b/backend/src/LearnStack.SharedKernel/Permissions/OperationPolicy.cs index f94e3fc91..c94498f08 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/OperatorActGuard.cs b/backend/src/LearnStack.SharedKernel/Permissions/OperatorActGuard.cs index 931ab77fc..319afbccb 100644 --- a/backend/src/LearnStack.SharedKernel/Permissions/OperatorActGuard.cs +++ b/backend/src/LearnStack.SharedKernel/Permissions/OperatorActGuard.cs @@ -3,6 +3,7 @@ using LearnStack.SharedKernel.Identity; using LearnStack.SharedKernel.Localization; using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Platform; using LearnStack.SharedKernel.Results; using LearnStack.SharedKernel.Tenancy; @@ -45,8 +46,14 @@ internal OperatorActAdmission(OperationInvocation invocation, object request, Te /// owner, so a handler can be called only from that pipeline: the invocation is the live one for this /// exact request object and context, its policy is finite and names the operator source alone, its /// descriptor still matches, the context is the ambient one the executor installed for the tenant the -/// act names (no organization, no host scope, no user), and the transaction is the single ordinary -/// read-write owner that announced exactly that tenant. +/// act names (no host scope, no user, and no organization unless the act is a closure's fan-out), and the +/// transaction is the single ordinary read-write owner that announced exactly that tenant and organization. +/// +/// +/// The one organization. ADR-0102 Amendment 2 extends the confined announcement to a group's +/// organization for fan_out_closure alone: a context that carries an organization is admitted only +/// when the operator descriptor was minted for that operation, by reference, and the announcement names the +/// same organization. Every onboarding act still runs with none. /// /// /// It then takes the ordered locks of the plan before any read the act decides on, and @@ -77,7 +84,8 @@ public sealed class OperatorActGuard( public Result RequireLiveAct(object request) { ArgumentNullException.ThrowIfNull(request); - return context.IsResolved && HasInvocation(execution.CurrentInvocation, request) && HasOwner(context.TenantId) + var invocation = execution.CurrentInvocation; + return context.IsResolved && HasInvocation(invocation, request) && HasOwner(invocation!, context.TenantId) ? Result.Ok(None.Value) : RefusedNone(); } @@ -89,7 +97,7 @@ public async Task> AdmitAsync( ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(plan); var invocation = execution.CurrentInvocation; - if (!HasInvocation(invocation, request) || !HasOwner(plan.TenantId)) + if (!HasInvocation(invocation, request) || !HasOwner(invocation!, plan.TenantId)) { return Refused(); } @@ -115,7 +123,7 @@ public Result RequireCurrent(OperatorActAdmission admission) { ArgumentNullException.ThrowIfNull(admission); if (!ReferenceEquals(execution.CurrentInvocation, admission.Invocation) - || !HasInvocation(admission.Invocation, admission.Request) || !HasOwner(admission.TenantId)) + || !HasInvocation(admission.Invocation, admission.Request) || !HasOwner(admission.Invocation, admission.TenantId)) { return RefusedNone(); } @@ -139,12 +147,21 @@ private bool HasInvocation(OperationInvocation? invocation, object request) => i && invocation.TrustedSource is { SourceKind: AuthorizationSourceKind.PlatformOperator } source && source.Matches(request.GetType(), context); - private bool HasOwner(TenantId tenantId) => context.IsResolved && context.TenantId == tenantId - && context.OrganizationId is null && context.HostScope is null && context.UserId is null + private bool HasOwner(OperationInvocation invocation, TenantId tenantId) => context.IsResolved && context.TenantId == tenantId + && (context.OrganizationId is null || AnnouncesOrganization(invocation)) + && context.HostScope is null && context.UserId is null && unit.HasActiveTransaction && !unit.IsRollbackOnly && unit.Mode == TransactionMode.ReadWrite && unit.Transaction is not null && unit is not IGlobalIdentityUnitOfWork { IsGlobalIdentityTransaction: true } && unit.GetTenantContextAnnouncement(unit.Transaction) is { Generation: > 0 } announcement - && announcement.TenantId == tenantId; + && announcement.TenantId == tenantId && announcement.OrganizationId == context.OrganizationId; + + /// + /// Whether the act may run in an organization: only a closure's fan-out, by the operation its operator descriptor + /// was minted for (ADR-0102 Amendment 2). + /// + private static bool AnnouncesOrganization(OperationInvocation invocation) => + invocation.TrustedSource?.Operator?.Operation is { } operation + && ReferenceEquals(operation, PlatformOperations.ClosureFanOut); private static Result Refused() => Result.Fail(new Error(new LocalizedMessage("lockey_forbidden"))); diff --git a/backend/src/LearnStack.SharedKernel/Permissions/ProtectedOperationDecision.cs b/backend/src/LearnStack.SharedKernel/Permissions/ProtectedOperationDecision.cs index 14eb29d70..9d9f7e039 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 000000000..af19fd5f0 --- /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/Platform/IAccountClosureOperatorOperations.cs b/backend/src/LearnStack.SharedKernel/Platform/IAccountClosureOperatorOperations.cs new file mode 100644 index 000000000..afcbc6868 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Platform/IAccountClosureOperatorOperations.cs @@ -0,0 +1,225 @@ +using LearnStack.SharedKernel.Audit; + +namespace LearnStack.SharedKernel.Platform; + +/// How a closure's Begin ended (ADR-0107 § 7). +public enum ClosureBeginOutcome +{ + /// + /// This call moved the person's User from Active to Closing and the closure request to fulfilling in one + /// transaction with its result row, then fanned the closure out. + /// + Begun = 1, + + /// + /// The closure had begun already: the request was fulfilling, or the User was already Closing for another of the + /// person's closures and this call moved only the request. The fan-out ran again and adopted what an earlier call started. + /// + Resumed, + + /// The request's execution time has not come, by the database clock: blocked_window. + RefusedWindow, + + /// A hold source reports a hold for the closure: blocked_hold. + RefusedHold, + + /// + /// A participant tenant that allows ordinary work would be left without another eligible tenant-wide administrator: + /// blocked_last_administrator. + /// + RefusedLastAdministrator, + + /// No request has that identifier. + NotFound, + + /// The request is not a closure. + NotClosure, + + /// The closure is completed or cancelled; its stored status is returned. + NotBeginnable, + + /// The person's User is Closed: their closure has finished and nothing may begin for it. + SubjectNotAdmitted, + + /// + /// The person holds Memberships in more participant groups, served or not, or more Memberships in one participant tenant, + /// than one closure is admitted for (). Nothing changed and no refusal code + /// was recorded: the person stays Active, and Phase 11's data operations serve them. + /// + RefusedTooLarge, + + /// + /// The identity provider's account-removal port could never delete this person's account: it is not configured, or it + /// refuses the person's provider subject before any call. Nothing changed and no refusal code was recorded: the person + /// stays Active, and a Begin after the port is repaired is judged afresh. + /// + RefusedProvider, +} + +/// +/// What a Begin's fan-out did, as closed counts over the person's participant groups and never an identifier. +/// +/// The groups whose tenant allows ordinary work and whose organization, if any, is Active. +/// Served groups whose fan-out erasure this call created. +/// Served groups whose erasure an earlier call or the person had in flight, adopted as it was. +/// +/// Served groups with an erasure the person or an administrator filed that is past its window and not yet run: a repeated +/// Begin picks them up. +/// +/// Served groups whose act did not report a start or an adoption: a repeated Begin retries them. +/// +/// Groups whose tenant does not allow ordinary work or whose organization is not Active (unserved_group): no +/// fan-out runs there, their data stays, and Phase 11's offboarding owns it. +/// +public sealed record ClosureBeginTally(int Served, int Started, int Adopted, int Waiting, int Failed, int Unserved) +{ + /// Whether every served group is started or adopted, so no repeat of Begin is owed. + public bool Complete => Waiting == 0 && Failed == 0; +} + +/// The end of one closure Begin. +/// How it ended. +/// The request's stored status after the call, when a request was found. +/// +/// For a refusal, its closed code (blocked_window, blocked_hold or blocked_last_administrator), which +/// the request records as its last_refusal. +/// +/// For a Begin or a resume, what the fan-out did per group. +public sealed record ClosureBeginResult( + ClosureBeginOutcome Outcome, string? Status = null, string? Refusal = null, ClosureBeginTally? Groups = null); + +/// How a closure's Finalize ended (ADR-0107 § 7, ADR-0108 § 8). +public enum ClosureFinalizeOutcome +{ + /// + /// This call redacted the person's audit rows, removed their identity-provider account and, in its second transaction, + /// moved the User from Closing to Closed, completed the participant erasures awaiting the privileged step, the closure + /// and every other open closure of the person, and wrote the result row. + /// + Finalized = 1, + + /// The closure is completed and its person's User is Closed: an earlier call finished it. + AlreadyFinalized, + + /// No request has that identifier. + NotFound, + + /// The request is not a closure. + NotClosure, + + /// The closure was never begun (scheduled) or was cancelled; its stored status is returned. + NotFinalizable, + + /// + /// A required participant group's newest erasure of the person neither awaits the privileged step nor completed during + /// this closure: its fan-out has not finished. A group is required when it is served, or when it is unserved but still + /// holds the closure's fan-out erasure open. Repeat Begin, wait for the group's erasure job, and finalize again. + /// + GroupsPending, + + /// + /// The identity provider definitively refused the account's deletion (a configuration or authority fault). The redaction + /// committed with its intent row; the closure stays fulfilling and its User Closing, and a repeat resumes it. + /// + ProviderRefused, + + /// The identity provider could not be reached before the deletion was sent. A repeat resumes the closure. + ProviderUnavailable, + + /// + /// The deletion was sent and its answer was lost: the account may be gone. A repeat resumes the closure, and a missing + /// account is success. + /// + ProviderUncertain, +} + +/// +/// Where a Finalize found the person's participant groups, as closed counts and never an identifier. +/// +/// The groups whose tenant allows ordinary work and whose organization, if any, is Active. +/// +/// Required groups whose newest erasure of the person awaits the privileged step, or completed during this closure, and +/// covers every Membership the person holds there. Every served group is required, and so is an unserved group whose +/// fan-out erasure is still open, because its job started and nothing completes it after the person is Closed. +/// +/// Required groups that are not ready. +/// +/// Groups whose tenant does not allow ordinary work or whose organization is not Active (unserved_group): their data +/// stays and Phase 11's offboarding owns it. +/// +/// The participant erasures this call completed; zero unless it finalized. +/// The person's closure requests this call completed, this one included; zero unless it finalized. +public sealed record ClosureFinalizeTally( + int Served, int Ready, int Pending, int Unserved, int ErasuresCompleted = 0, int ClosuresCompleted = 0); + +/// The end of one closure Finalize. +/// How it ended. +/// The request's stored status after the call, when a request was found. +/// For a finalization or a group still pending, the closed counts of the participant groups. +/// +/// For a finalization, the unserved groups by tenant and organization: never a person, and the operator's list of what +/// Phase 11's offboarding owns. +/// +/// For every call that reached the provider step, this call's redaction passes, summed. +/// +/// For a finalization or an earlier one, the closure request's recorded result: the audit log's retained kinds summed over +/// every pass, and unserved_group. +/// +public sealed record ClosureFinalizeResult( + ClosureFinalizeOutcome Outcome, + string? Status = null, + ClosureFinalizeTally? Groups = null, + IReadOnlyList? UnservedGroups = null, + AuditRedactionAggregate? Redaction = null, + IReadOnlyDictionary? Retained = null); + +/// +/// The confined owner of the operator's global account closure acts (ADR-0107 §§ 7 and 8): it consumes the operator's +/// admission in the platform scope, fences the person and every participant tenant on the platform connection, judges the +/// closure, moves the person's User and the request, and then fans the closure out to every served participant group; and +/// it finalizes a begun closure in two platform transactions around the identity provider's account deletion. +/// +/// +/// A transient database fault, a fence that could not be taken within its bound included, is thrown as +/// , with its commit outcome unknown when the act's commit was already +/// sent; the scope's own refusals are thrown as the scope throws them. +/// +public interface IAccountClosureOperatorOperations +{ + /// + /// Begins one person's closure: in one platform transaction under the person's User fence and every participant + /// tenant's fence, refuses blocked_window, blocked_hold or blocked_last_administrator by recording + /// it on the request, or moves the User to Closing and the request to fulfilling; after that commit, fans the + /// closure out to every served participant group. A closure that could never finish, a person past the closure's + /// bounds or an account the provider's port could never delete, is refused before any write with no code recorded. A + /// repeat resumes: it skips what is done and fans out again. + /// + /// A MUST row could not be written; nothing changed. + /// + /// The database could not finish, a fence could not be taken in time, or the commit's outcome is unknown. + /// + /// No closure fan-out is registered: the act refuses before it enters the scope. + Task BeginAsync( + PlatformAdmission admission, Guid closureRequestId, CancellationToken cancellationToken = default); + + /// + /// Finalizes one person's begun closure (ADR-0107 § 7, ADR-0108 § 8). The first platform transaction, under the + /// person's User fence alone, finds every required group ready, redacts the person's audit rows in every participant + /// tenant and the platform sentinel tenant and commits with the intent row that carries the summed counts; no + /// participant tenant waits for it. The identity provider's account is then deleted. The second transaction, under the + /// User fence and every participant tenant's fence, judges again, moves the User from Closing to Closed with its raw + /// provider subject removed, completes every participant erasure awaiting the privileged step, the closure and every + /// other open closure of the person, and commits with the result row. Every step is idempotent: a repeat after a crash + /// or a provider failure resumes, and a missing account is success. + /// + /// + /// The entry or the intent row could not be written or committed: the provider step did not start. + /// + /// + /// The database could not finish, a fence could not be taken in time, the final commit's outcome is unknown, or the + /// result row could not be written after the provider step, when the account may already be deleted and a repeat + /// finishes the closure. + /// + Task FinalizeAsync( + PlatformAdmission admission, Guid closureRequestId, CancellationToken cancellationToken = default); +} diff --git a/backend/src/LearnStack.SharedKernel/Platform/IClosureFanOut.cs b/backend/src/LearnStack.SharedKernel/Platform/IClosureFanOut.cs new file mode 100644 index 000000000..562a4e9fd --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Platform/IClosureFanOut.cs @@ -0,0 +1,77 @@ +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.SharedKernel.Platform; + +/// One scope group a closure reaches: a tenant and one organization, or the tenant-wide group. +/// The participant tenant. +/// The organization, or for the tenant-wide group. +public sealed record ClosureParticipantGroup(TenantId TenantId, OrganizationId? OrganizationId); + +/// What the fan-out did for one participant group. +public enum ClosureGroupOutcome +{ + /// A fan-out erasure request was created and its job enqueued. + Started = 1, + + /// An erasure the group already had in flight, or already awaiting its operator step, was adopted. + Adopted = 2, + + /// + /// An erasure the person or an administrator filed is past its window and not yet run: the group is not ready and + /// a repeated Begin picks it up. + /// + Waiting = 3, + + /// The group's frame failed; nothing is recorded for it and a repeated Begin retries it. + Failed = 4, +} + +/// The fan-out's answer for one participant group. +/// The group. +/// What happened there. +public sealed record ClosureGroupReport(ClosureParticipantGroup Group, ClosureGroupOutcome Outcome); + +/// The person and the participant groups a closure's Begin hands to the fan-out. +/// The person whose account is closing; their User is already Closing. +/// The groups that allow ordinary work, in a stable order; unserved groups are not listed. +public sealed record ClosureFanOutRequest(UserId SubjectUserId, IReadOnlyList Groups); + +/// +/// Creates, in each participant group's own transaction, the fan-out erasure of a closing person and enqueues its job +/// (ADR-0107 § 7, +/// fan_out_closure). +/// +/// +/// +/// It runs after Begin's transaction has committed and released its fences: each group is one pipeline act under the +/// operator's identity, announced for that tenant and organization, which takes the person's User fence and the tenant +/// fence itself. It mints one admission of fan_out_closure per group from the operator witness it is given, so +/// the gate evaluates the grant on every act. A group that fails is reported, never thrown: Begin is repeated until +/// every group is started or adopted. +/// +/// +/// It is idempotent: a repeat adopts what an earlier call started and starts what it lacked. +/// +/// +/// Its bound is the caller's guarantee. One call names at most +/// distinct groups, none of them the platform sentinel +/// tenant's, for a real person. Begin guarantees it: it refuses a person past the closure's bounds before the User leaves +/// Active, and hands over only what it read within them. A request that breaks it is the caller's programming error and is +/// thrown before any group runs, and Begin reports every group failed rather than lose its committed transition, so a +/// caller that does not keep the bound strands the person; a group that fails is otherwise reported, never thrown. +/// +/// +public interface IClosureFanOut +{ + /// Fans the closure out to every group of and reports each group's outcome. + /// + /// The request breaks the caller's guarantee: more than + /// groups, a duplicate or invalid group, or no real person. Nothing ran. + /// + /// The operator's cancellation, after the groups that finished. + Task> FanOutAsync( + PlatformOperatorWitness operatorWitness, + string? ticket, + ClosureFanOutRequest request, + CancellationToken cancellationToken = default); +} diff --git a/backend/src/LearnStack.SharedKernel/Platform/IDataRequestOperatorOperations.cs b/backend/src/LearnStack.SharedKernel/Platform/IDataRequestOperatorOperations.cs new file mode 100644 index 000000000..c86c305e4 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Platform/IDataRequestOperatorOperations.cs @@ -0,0 +1,132 @@ +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; + +namespace LearnStack.SharedKernel.Platform; + +/// +/// Which list of the data-request work that needs a person an inspection reads (ADR-0107 § 8, ADR-0106 § 12). +/// +public enum DataRequestInspectionState +{ + /// Erasures whose tenant side finished and that wait for the operator's privileged step. + AwaitingPrivilegedStep = 1, + + /// + /// Requests still scheduled after their execution time: the window passed and nothing started them. + /// + OverdueScheduled, + + /// + /// Requests still fulfilling longer than after they + /// fell due. + /// + StuckFulfilling, + + /// + /// Export artifacts past their expiry that are still available or expired: their purge has not run. + /// + ExpiredArtifact, +} + +/// One page request of the data-request inspection. +/// The list to read. +/// +/// The opaque position a previous page of the same list returned, or null for the first page. +/// +/// The page size the route clamped; the owner clamps it again. +public sealed record DataRequestInspectionQuery(DataRequestInspectionState State, string? Cursor, int Limit); + +/// An export artifact's lifecycle metadata, without its subject, size, key version or content. +/// The artifact. +/// available or expired, as stored. +/// The instant it stopped being readable. +public sealed record DataExportArtifactInspection(Guid ArtifactId, string Status, DateTimeOffset ExpiresAt); + +/// +/// One data request in an inspection, metadata only: no subject, requester, snapshot, progress, result or person data. +/// +/// The request. +/// The request's tenant. +/// The request's organization; null for the tenant-wide group. +/// export, erasure or closure. +/// self, administrator or closure_fanout. +/// The stored status. +/// When it was filed. +/// When its window ends, for an erasure or closure filed with one. +/// When it completed, if it did. +/// The closed refusal code it recorded, if any. +/// The closed failure reason it recorded, if any. +/// +/// The request's expired artifact, on the list only. +/// +public sealed record DataRequestInspectionItem( + Guid RequestId, Guid TenantId, Guid? OrganizationId, string Kind, string Origin, string Status, DateTimeOffset CreatedAt, + DateTimeOffset? ExecuteAt, DateTimeOffset? CompletedAt, string? LastRefusal, string? FailureReason, + DataExportArtifactInspection? Artifact); + +/// How an erasure completion ended. +public enum ErasureCompletionOutcome +{ + /// The audit rows were redacted, the request completed and the result row committed, together. + Completed = 1, + + /// The request was already completed: its recorded result is returned and no second row is written. + AlreadyCompleted, + + /// No request has that identifier. + NotFound, + + /// The request is not an erasure. + NotErasure, + + /// The erasure is a closure's fan-out, which only that closure's finalization completes (ADR-0107 § 7). + ClosureFanout, + + /// The erasure is not awaiting the privileged step; its stored status is returned. + NotAwaiting, +} + +/// The end of one erasure completion. +/// How it ended. +/// The request's tenant, when one was found. +/// The request's stored status after the call, when one was found. +/// When the request completed, for a completed request. +/// +/// The request's recorded retained kinds and counts (ADR-0107 § 6) for a completed request: the tenant side's, with the +/// audit log's kinds set from the report. +/// +/// The redaction's closed report, for the call that completed the request; a repeat has none. +public sealed record ErasureCompletionResult( + ErasureCompletionOutcome Outcome, Guid? TenantId = null, string? Status = null, DateTimeOffset? CompletedAt = null, + IReadOnlyDictionary? Retained = null, AuditRedactionReport? Report = null); + +/// +/// The confined owner of the operator's data-request acts (ADR-0107 § 8, ADR-0108): it consumes the operator's +/// admission in the platform scope, reads the request tables through the platform role's column grants and completes +/// an erasure with its audit redaction, its status change and its result row in one transaction. +/// +/// +/// A malformed or foreign cursor answers null, which the route reports as a validation failure. A transient database +/// fault is thrown as , with its commit outcome unknown when the +/// completion's commit was already sent; the scope's own refusals are thrown as the scope throws them. +/// +public interface IDataRequestOperatorOperations +{ + /// Lists one page of the requested list, oldest due first; the scope's entry row is its audit. + /// The scope's entry row could not be written; nothing was read. + /// The database could not be read; nothing changed. + Task?> InspectAsync( + PlatformAdmission admission, DataRequestInspectionQuery query, CancellationToken cancellationToken = default); + + /// + /// Completes an erasure awaiting its privileged step: redacts the subject's audit rows, moves the request to + /// completed and writes the MUST result row under the request's tenant, all on one transaction + /// (ADR-0108 § 8). + /// + /// A MUST row could not be written; nothing changed. + /// + /// The database could not finish, or the commit's outcome is unknown. + /// + Task CompleteErasureAsync( + PlatformAdmission admission, Guid requestId, CancellationToken cancellationToken = default); +} diff --git a/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs b/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs index 1ea94eca2..b084d2e90 100644 --- a/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs +++ b/backend/src/LearnStack.SharedKernel/Platform/PlatformOperation.cs @@ -158,12 +158,64 @@ public static class PlatformOperations "platform.federation.disable", "federation_disable", PlatformPermissions.FederationAdmin, PlatformOperationExecutor.PlatformScope, attemptAuditSlug: "platform.federation.disable_attempt"); + /// + /// Inspect the data requests that await an operator step, overdue scheduled requests, stuck fulfilling requests + /// and expired export artifacts not yet purged: read-only in the platform scope on column grants, audited by the + /// scope's entry row (ADR-0107 § 8). + /// + public static PlatformOperation DataRequestInspect { get; } = new( + "platform.data_request.inspect", "data_request_inspect", PlatformPermissions.DataRequestRead, + PlatformOperationExecutor.PlatformScope); + + /// + /// Complete an erasure: redact the subject's audit rows, move the request from + /// awaiting_privileged_step to completed and write the result row in one platform transaction + /// (ADR-0107 § 8, ADR-0108 § 1). The audit slug names the Audit module because the operator result write refuses + /// the identity module (ADR-0044 Amendment 17). + /// + public static PlatformOperation ErasureComplete { get; } = new( + "audit.redaction.apply", "erasure_complete", PlatformPermissions.DataRequestWrite, + PlatformOperationExecutor.PlatformScope); + + /// + /// Begin a person's global account closure (begin_closure, ADR-0107 § 7): under the person's User fence and + /// every participant tenant's fence, move the User from Active to Closing and the closure request to + /// fulfilling, or record the refusal that stands, in one platform transaction whose result row names the + /// platform sentinel tenant. The slug names no module of its own because the operator result write refuses + /// identity (ADR-0044 Amendment 17, ADR-0107 § 8). + /// + public static PlatformOperation ClosureBegin { get; } = new( + "platform.closure.begin", "closure_begin", PlatformPermissions.DataRequestWrite, + PlatformOperationExecutor.PlatformScope); + + /// + /// Finalize a person's global account closure (finalize_closure, ADR-0107 § 7, ADR-0108 § 8): redact the + /// person's audit rows in every participant tenant and the platform sentinel tenant and write the intent row that + /// carries the counts, remove the provider account, then set the User Closed, complete the participant requests and + /// the closure and write the result row. Both rows name the platform sentinel tenant. It is the one operation besides + /// that may redact, and only a closure's passes. + /// + public static PlatformOperation ClosureFinalize { get; } = new( + "platform.closure.finalize", "closure_finalize", PlatformPermissions.DataRequestWrite, + PlatformOperationExecutor.PlatformScope, attemptAuditSlug: "platform.closure.finalize_attempt"); + + /// + /// Fan a begun closure out to one participant group (fan_out_closure, ADR-0107 § 7): a pipeline act on the + /// application role, announced for the group's tenant and organization (ADR-0102 Amendment 2), that creates the + /// closing person's fan-out erasure there and enqueues its job, or adopts the erasure the group already has. Begin's + /// owner mints one admission of it per group after Begin's transaction commits; it is not a routed endpoint. It is the + /// one operation whose act may announce an organization. + /// + public static PlatformOperation ClosureFanOut { get; } = new( + "identity.data_request.fan_out_closure", "closure_fan_out", PlatformPermissions.DataRequestWrite, + PlatformOperationExecutor.Pipeline); + /// Every registered operation. public static IReadOnlyList All { get; } = [ KillswitchToggle, TenantProvision, HostMap, RoleInitialize, FirstAdminCreate, AdminRecover, IdentityAuthorityRebind, DeliveryInspect, DeliveryReplay, DeliveryReset, FederationReport, FederationRemove, - FederationDisable, + FederationDisable, DataRequestInspect, ErasureComplete, ClosureBegin, ClosureFinalize, ClosureFanOut, ]; /// Whether is one of the registered instances. diff --git a/backend/src/LearnStack.SharedKernel/Platform/PlatformOperatorAttribution.cs b/backend/src/LearnStack.SharedKernel/Platform/PlatformOperatorAttribution.cs index 7b86c4a6f..754e5b6ac 100644 --- a/backend/src/LearnStack.SharedKernel/Platform/PlatformOperatorAttribution.cs +++ b/backend/src/LearnStack.SharedKernel/Platform/PlatformOperatorAttribution.cs @@ -19,18 +19,19 @@ namespace LearnStack.SharedKernel.Platform; /// public sealed class PlatformOperatorAttribution { - private PlatformOperatorAttribution(string issuer, string subjectDigest, string acr, string executor, string reasonSlug) + private PlatformOperatorAttribution(string issuer, string subjectDigest, string acr, string executor, PlatformOperation operation) { ArgumentException.ThrowIfNullOrWhiteSpace(issuer); ArgumentException.ThrowIfNullOrWhiteSpace(subjectDigest); ArgumentException.ThrowIfNullOrWhiteSpace(acr); ArgumentException.ThrowIfNullOrWhiteSpace(executor); - ArgumentException.ThrowIfNullOrWhiteSpace(reasonSlug); + ArgumentNullException.ThrowIfNull(operation); Issuer = issuer; SubjectDigest = subjectDigest; Acr = acr; Executor = executor; - ReasonSlug = reasonSlug; + Operation = operation; + ReasonSlug = operation.ReasonSlug; } /// The pinned operator issuer. @@ -48,12 +49,19 @@ private PlatformOperatorAttribution(string issuer, string subjectDigest, string /// The closed reason slug of the admitted operation. public string ReasonSlug { get; } + /// + /// The registered operation the act was admitted for, so a handler-side guard can tell one operator act from + /// another by reference rather than by text (ADR-0102 Amendment 2: only fan_out_closure announces an + /// organization). It is never written to a row. + /// + public PlatformOperation Operation { get; } + /// The attribution of an admitted act. public static PlatformOperatorAttribution From(PlatformAdmission admission) { ArgumentNullException.ThrowIfNull(admission); var op = admission.Operator; - return new(op.Issuer, op.SubjectDigest, op.Acr, op.Executor, admission.Operation.ReasonSlug); + return new(op.Issuer, op.SubjectDigest, op.Acr, op.Executor, admission.Operation); } /// diff --git a/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs b/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs index da68b0067..89d3e0918 100644 --- a/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs +++ b/backend/src/LearnStack.SharedKernel/Platform/PlatformPermissions.cs @@ -52,11 +52,25 @@ public static class PlatformPermissions public static PermissionDefinition FederationAdmin { get; } = new(PermissionScope.Platform, "platform.federation.admin"); + /// + /// Inspect the data requests that await an operator, are overdue or stuck, and the expired export artifacts not yet + /// purged (ADR-0107 § 8). + /// + public static PermissionDefinition DataRequestRead { get; } = + new(PermissionScope.Platform, "platform.data_request.read"); + + /// + /// Complete an erasure's privileged audit redaction and, in Step 3, begin and finalize a global account closure + /// (ADR-0107 § 8, ADR-0108 § 1). + /// + public static PermissionDefinition DataRequestWrite { get; } = + new(PermissionScope.Platform, "platform.data_request.write"); + /// Every registered Platform permission. public static IReadOnlyList All { get; } = [ KillswitchWrite, TenantWrite, TenantBootstrapWrite, IdentityAuthorityAdmin, DeliveryRead, DeliveryWrite, - FederationRead, FederationAdmin, + FederationRead, FederationAdmin, DataRequestRead, DataRequestWrite, ]; /// Finds a registered Platform permission by its key. diff --git a/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminScope.cs b/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminScope.cs index 923942b7d..f279ad8f2 100644 --- a/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminScope.cs +++ b/backend/src/LearnStack.SharedKernel/Tenancy/IPlatformAdminScope.cs @@ -1,5 +1,6 @@ using System.Data.Common; using System.Runtime.CompilerServices; +using LearnStack.SharedKernel.Audit; using LearnStack.SharedKernel.Identifiers; using LearnStack.SharedKernel.Platform; @@ -101,6 +102,23 @@ Task> QueryAsync( /// Task WriteIntentAsync(PlatformResult intent, CancellationToken cancellationToken = default); + /// + /// Redacts the subject's audit rows for on the work transaction, through the one + /// Audit-owned executor, and returns its closed report (ADR-0108 § 2). + /// + /// + /// The statements above cannot name audit_log, so this is the only way a scope reaches it, and only an + /// operation ADR-0108 sanctions holds it, for its own plans: complete_erasure an erasure's, and the closure's + /// Finalize a closure's tenant and sentinel passes. Any other admission or pairing is refused before anything runs. + /// It is a write like the others: it runs before the result row, a failure leaves the scope only to be abandoned, + /// and the redaction commits with what follows it on its transaction or not at all: an erasure's change and result + /// row, or the intent row a closure's Finalize writes at its checkpoint (ADR-0108 § 8). + /// + /// + /// The scope's operation may not redact the plan, the result row is already written, or no executor is registered. + /// + Task RedactAuditAsync(AuditRedactionPlan plan, CancellationToken cancellationToken = default); + /// /// Writes the act's MUST result row on the work transaction, so it commits with the /// state change or not at all. diff --git a/backend/src/LearnStack.SharedKernel/Tenancy/TenantContextFactory.cs b/backend/src/LearnStack.SharedKernel/Tenancy/TenantContextFactory.cs index 1eadec533..da96f7cc0 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 6b8e65e1d..4adb5ae09 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/Audit/LearnStack.Modules.Audit.Application/ProviderEvents/ProviderEventObservationHandler.cs b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Application/ProviderEvents/ProviderEventObservationHandler.cs index be92a2dc7..88681b92f 100644 --- a/backend/src/Modules/Audit/LearnStack.Modules.Audit.Application/ProviderEvents/ProviderEventObservationHandler.cs +++ b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Application/ProviderEvents/ProviderEventObservationHandler.cs @@ -7,6 +7,11 @@ namespace LearnStack.Modules.Audit.Application.ProviderEvents; /// The required transport-owned inbox precedes this constructor and its central MUST observation. +/// +/// A delivery whose affected person's User is no longer Active, as the fact reader judged it in the database under the +/// person's User fence, refuses the person (ADR-0107 §§ 7, 9): its observation is withheld, so the delivery completes as +/// a recorded no-op with its inbox row and no audit row, and is never retried. A replayed delivery runs the same rule. +/// public sealed class ProviderEventObservationHandler(IProviderEventAuditFactReader facts, IAuditStateCapture capture, ITenantContext context) : ProviderEventAuditEvidence.MintingSource, IIntegrationEventHandler { @@ -20,7 +25,11 @@ public async Task HandleAsync(UserProviderEventObservedIntegrationEventV1 @event cancellationToken.ThrowIfCancellationRequested(); if (fact.TargetId != @event.TargetId || fact.EventId != @event.EventId || fact.TenantId != delivery.TenantId) throw new InvalidOperationException("Provider observation does not match its retained target."); - capture.AttachProviderEvent(Observe(delivery, fact.TargetId, fact.ReceiptId, fact.ProviderEventId, fact.AuthorityId, - fact.RealmId, fact.AffectedUserId, fact.Kind, fact.SourceOccurredAt)); + var evidence = Observe(delivery, fact.TargetId, fact.ReceiptId, fact.ProviderEventId, fact.AuthorityId, + fact.RealmId, fact.AffectedUserId, fact.Kind, fact.SourceOccurredAt); + if (fact.SubjectActive) + capture.AttachProviderEvent(evidence); + else + capture.WithholdProviderEvent(evidence); } } 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 000000000..e51602b75 --- /dev/null +++ b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/DataRequests/AuditPayloadProjection.cs @@ -0,0 +1,109 @@ +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. +/// +/// +/// Property names stay distinct. Rewriting names can make two of one object's names equal (two +/// Memberships keyed by identifier both become third_party), and a JSON object with a repeated name is +/// read differently by different parsers. Within one object the first occurrence of a rewritten name keeps it; +/// each later one takes the first free of name_2, name_3, … in document order, so the output is +/// deterministic and every name in it is unique. The suffix counts names, never identifies a person. +/// +/// +/// 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(); + var names = new HashSet(StringComparer.Ordinal); + foreach (var property in element.EnumerateObject()) + { + json.WritePropertyName(Distinct(Rewrite(property.Name, own), names)); + 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; + } + } + + /// The name itself when the object has not used it, else the first free name_n from 2. + private static string Distinct(string name, HashSet used) + { + if (used.Add(name)) + { + return name; + } + + for (var suffix = 2; ; suffix++) + { + var candidate = name + "_" + suffix.ToString(System.Globalization.CultureInfo.InvariantCulture); + if (used.Add(candidate)) + { + return candidate; + } + } + } + + [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 000000000..3399dc19a --- /dev/null +++ b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/DataRequests/AuditUserDataParticipant.cs @@ -0,0 +1,493 @@ +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 narrows the reach (ADR-0108 § 4): an administrator-requested export +/// selects only rows whose organization_id is the group's (none for the tenant-wide group), a self-requested +/// one sets no organization predicate of its own. +/// +/// +/// The reach is what the row policy shows, and the bundle says so. Both read on the job's ordinary tenant +/// transaction as learnstack_app, which holds no tenant-wide read witness, so audit_log_isolation +/// still bounds what is visible: an organization group sees its own organization's rows and the tenant-level rows +/// (no organization), the tenant-wide group only the tenant-level rows. A self-requested export therefore does not +/// reach the rows recorded in the person's other organizations, which ADR-0107 § 3 and ADR-0108 § 4 describe as +/// "the whole tenant"; a tenant-wide read for the job needs its own decision. Until then the section's first +/// collection, , holds one record whose reach is a closed word +/// () and whose complete is : rows the person caused in an +/// organization they hold no Membership of reach no export of theirs, so no current reach is the person's whole +/// audit trail in the tenant. true is reserved for a sanctioned whole-tenant reach. +/// +/// +/// Index-served statements. Every statement is a union of branches, each one equality on an indexed column +/// set: the actor on ix_audit_log_actor_user_id_timestamp and the subject's User or Membership entity on +/// ix_audit_log_tenant_id_entity_type_entity_id_timestamp. A row two branches select is counted and exported +/// once (the union is on the primary key). The selection, its count and the actor and entity counts are therefore +/// exact and bounded by the subject's own rows, not by the tenant's. +/// +/// +/// The metadata count is "at least". A Membership in the authorization evidence is the acting principal's own +/// (the audit composer refuses authorization attribution whose actor is not the row's actor), so that reference is +/// read exactly inside the actor branch. The causal-actor and affected-user references cannot be index-served under +/// the row policy: PostgreSQL applies a non-leakproof qual, and every JSON operator is one, only after the policy, +/// so no expression index can carry the subject's value. They are read in the newest +/// rows carrying such a key in each branch of the reach; +/// audit_metadata_reference is exact while each branch holds at most that many such rows and a lower bound +/// beyond it, never more than the truth. Exact counting at any size needs the references as plain columns, a change +/// to the audit table's shape that needs its own decision. +/// +/// +/// The window is the reach's, not the tenant's. The reach has two branches, the group's organization +/// (organization_id = @organization) and the tenant-level rows (organization_id IS NULL, left out of +/// an administrator's organization request). Each is its own newest-first seek on its own partial index +/// (ix_audit_log_tenant_id_organization_id_person_reference, +/// ix_audit_log_tenant_id_tenant_level_person_reference), cut at the window, so a row of another +/// organization is never read only to be dropped by the row policy (a small organization in a tenant whose other +/// organizations hold millions of keyed rows reads only its own), no sort runs over a window, and one statement +/// reads at most two windows. The two branches name exactly what the policy shows the job's transaction, which +/// never holds the tenant-wide scope. +/// +/// +/// The statements run under ; a statement that cannot finish inside it rolls the job's +/// transaction back and the runtime retries the export. +/// +/// +/// 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"; + + /// The section's first collection: one record stating which audit rows the section could reach. + public const string ScopeCollection = "audit_scope"; + + /// A self-requested export in an organization group: that organization's rows and the tenant-level rows. + public const string ReachOrganizationAndTenantLevel = "organization_and_tenant_level"; + + /// An administrator-requested export in an organization group: that organization's rows only. + public const string ReachOrganizationOnly = "organization_only"; + + /// Any export in the tenant-wide group: the tenant-level rows only. + public const string ReachTenantLevelOnly = "tenant_level_only"; + + /// + /// The complete flag of the record: whether the reach is the person's whole audit + /// trail in the tenant. for every reach word above, because rows recorded in an organization + /// the person holds no Membership of reach no export of theirs; is reserved for a + /// sanctioned whole-tenant reach, which needs its own decision. + /// + public const bool ReachIsComplete = false; + + /// + /// The wall-clock budget of one audit statement. Larger than the 5-second default of the other participants' + /// reads, because the audit table is the one that grows without bound until Phase 11's retention, and still + /// bounded, so a degraded database fails the attempt for the runtime's retry rather than holding the job's + /// transaction. At 1.9 million rows of one tenant the selection statements measured about 2 ms each; at 2.3 million + /// the metadata count measured about 1 ms for an organization without keyed rows of its own and 1.2 to 1.6 s for + /// one whose branch fills a window (the Audit module's performance budget records the measurements). + /// + public static readonly TimeSpan StatementBudget = TimeSpan.FromSeconds(15); + + /// + /// How many of the newest rows carrying a causal-actor or affected-user key the metadata count examines in each + /// branch of the reach (the group's organization, the tenant-level rows). Those references cannot be index-served + /// under the row policy (the JSON operators are not leakproof, so PostgreSQL evaluates them only after the + /// policy), so the read is bounded by rows, which the index seeks per branch, and audit_metadata_reference + /// is exact up to this many such rows per branch and a lower bound beyond it. + /// + public const int MetadataScanWindow = 500_000; + + private const int Page = 200; + + // The reach every branch repeats: the tenant, and for an administrator's request the group's organization. + private const string Reach = """ + tenant_id = @tenant AND (NOT @scoped OR organization_id IS NOT DISTINCT FROM @organization) + """; + + private const string ActorBranch = "SELECT id, \"timestamp\" FROM public.audit_log WHERE " + Reach + + " AND actor_user_id = @subject"; + + private const string UserBranch = "SELECT id, \"timestamp\" FROM public.audit_log WHERE " + Reach + + " AND entity_type = 'User' AND entity_id = @subject_text"; + + private const string MembershipBranch = "SELECT id, \"timestamp\" FROM public.audit_log WHERE " + Reach + + " AND entity_type = 'Membership' AND entity_id = ANY(@memberships)"; + + // The subject as actor or entity: the union of three index-served branches, a row in two of them once. + private const string CountSql = "SELECT count(*) FROM (" + ActorBranch + " UNION " + UserBranch + " UNION " + + MembershipBranch + ") AS selected"; + + // Keyset page, newest first: each branch reads at most one page below the cursor in its own index order, and the + // union's newest page is the page of the whole selection. + private const string Below = " AND \"timestamp\" <= @after_timestamp AND (\"timestamp\", id) < (@after_timestamp, @after_id)" + + " ORDER BY \"timestamp\" DESC, id DESC LIMIT @page"; + + private const string PageSql = "WITH page AS ((" + ActorBranch + Below + ") UNION (" + UserBranch + Below + ") UNION (" + + MembershipBranch + Below + """ + )) + SELECT a.id, a."timestamp", a.module, a.operation, a.outcome, a.entity_type, a.entity_id, a.actor_user_id, + host(a.ip_address), a.user_agent, a.before_state, a.after_state, a.changes + FROM page AS p + JOIN public.audit_log AS a ON a.id = p.id AND a."timestamp" = p."timestamp" + ORDER BY a."timestamp" DESC, a.id DESC + LIMIT @page + """; + + // The actor rows, and the entity rows (the User and Membership branches are disjoint by entity type). + private const string RetainedSql = "SELECT (SELECT count(*) FROM (" + ActorBranch + ") AS actor), (SELECT count(*) FROM (" + + UserBranch + ") AS self) + (SELECT count(*) FROM (" + MembershipBranch + ") AS membership)"; + + // The partial indexes' key predicate, repeated literally by both window branches so the planner can prove each + // index applies (20261122074947_index_audit_log_data_request_selection). + private const string PersonReferenceKeys = """ + (metadata ? 'causal_actor_user_id' OR (metadata -> 'authorization') ? 'causal_actor_user_id' + OR (metadata -> 'provider_event') ? 'affected_user_id') + """; + + // The subject named as causal actor (top level or in the authorization evidence) or as a provider event's + // affected user, tested on a window's rows after the window is cut. + private const string SubjectReference = """ + 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 + """; + + // A metadata person reference: a frozen Membership in the authorization evidence, read inside the actor branch + // (exact), or a SubjectReference, read in the newest MetadataScanWindow keyed rows of each branch of the reach (a + // lower bound past the window). Each branch is its own ordered, limited seek on its partial index, so neither the + // other branch nor another organization's keyed rows are read, and no sort runs over the window: the group's + // organization (a null @organization, the tenant-wide group, matches no row), and the tenant-level rows, which an + // administrator's request reads only for the tenant-wide group. + private const string MetadataSql = "SELECT count(*) FROM (" + ActorBranch + """ + AND COALESCE(metadata -> 'authorization' -> 'memberships', '[]'::jsonb) ?| @memberships + UNION + SELECT id, "timestamp" FROM ( + SELECT id, "timestamp", metadata FROM public.audit_log + WHERE tenant_id = @tenant AND organization_id = @organization + AND + """ + " " + PersonReferenceKeys + """ + + ORDER BY "timestamp" DESC + LIMIT @window + ) AS organization_window + WHERE + """ + " " + SubjectReference + """ + + UNION + SELECT id, "timestamp" FROM ( + SELECT id, "timestamp", metadata FROM public.audit_log + WHERE tenant_id = @tenant AND organization_id IS NULL AND (NOT @scoped OR @organization IS NULL) + AND + """ + " " + PersonReferenceKeys + """ + + ORDER BY "timestamp" DESC + LIMIT @window + ) AS tenant_level_window + WHERE + """ + " " + SubjectReference + """ + + ) AS referenced + """; + + private static readonly DateTime FirstPageTimestamp = new(9999, 12, 31, 0, 0, 0, DateTimeKind.Utc); + private static readonly Guid FirstPageId = Guid.Parse("ffffffff-ffff-ffff-ffff-ffffffffffff"); + + 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); + var scope = await UserDataExportRecord.AppendAsync(writer, ScopeCollection, json => + { + json.WriteStartObject(); + json.WriteString("reach", ReachOf(subject)); + json.WriteBoolean("complete", ReachIsComplete); + json.WriteEndObject(); + }, cancellationToken).ConfigureAwait(false); + if (scope != UserDataExportAppend.Appended) + { + return; + } + + 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)) + { + command.Parameters.AddWithValue("window", MetadataScanWindow); + metadata = (long)(await ExecuteAsync(token => command.ExecuteScalarAsync(token), cancellationToken).ConfigureAwait(false))!; + } + + return + [ + new(RetainedReferenceKind.AuditActorReference, actor), + new(RetainedReferenceKind.AuditEntityReference, entity), + new(RetainedReferenceKind.AuditMetadataReference, metadata), + ]; + } + + /// + /// The closed reach of a request's audit section under the row policy: which organization's rows the job's + /// transaction can see, narrowed by who asked (ADR-0108 § 4). + /// + public static string ReachOf(UserDataSubject subject) + { + ArgumentNullException.ThrowIfNull(subject); + return subject.Group.IsTenantWide + ? ReachTenantLevelOnly + : subject.Origin == DataRequestOrigin.Self ? ReachOrganizationAndTenantLevel : ReachOrganizationOnly; + } + + /// 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("after_timestamp", NpgsqlDbType.TimestampTz, cursor?.Timestamp ?? FirstPageTimestamp); + command.Parameters.AddWithValue("after_id", cursor?.Id ?? FirstPageId); + 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 = (int)StatementBudget.TotalSeconds, + }; + 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(StatementBudget); + 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."); + } + } + + /// The shared group check, and the statements' own precondition: the announced transaction they run on. + private void RequireGroup(UserDataSubject subject) + { + UserDataParticipantGuard.RequireGroup(subject, tenant); + if (!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/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/Configurations.cs b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/Configurations.cs index 322ac64ba..98440763d 100644 --- a/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/Configurations.cs +++ b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/Configurations.cs @@ -178,6 +178,13 @@ public void Configure(EntityTypeBuilder builder) builder.HasIndex(x => new { x.ModuleName, x.Operation, x.Timestamp }) .HasDatabaseName("ix_audit_log_module_operation_timestamp") .IsDescending(false, false, true); + + // A subject's rows by entity, newest first: the data-request selection of rows about the person's User or + // Membership (ADR-0107 § 3, ADR-0108 § 4), which no other index serves. The partial person-reference index of + // the same migration is raw SQL, because the model cannot express its predicate. + builder.HasIndex(x => new { x.TenantId, x.EntityType, x.EntityId, x.Timestamp }) + .HasDatabaseName("ix_audit_log_tenant_id_entity_type_entity_id_timestamp") + .IsDescending(false, false, false, true); } } diff --git a/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/Migrations/20261122074947_index_audit_log_data_request_selection.Designer.cs b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/Migrations/20261122074947_index_audit_log_data_request_selection.Designer.cs new file mode 100644 index 000000000..3860f5832 --- /dev/null +++ b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/Migrations/20261122074947_index_audit_log_data_request_selection.Designer.cs @@ -0,0 +1,305 @@ +// +using System; +using System.Net; +using LearnStack.Modules.Audit.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.Audit.Infrastructure.Persistence.Migrations +{ + [DbContext(typeof(AuditDbContext))] + [Migration("20261122074947_index_audit_log_data_request_selection")] + partial class index_audit_log_data_request_selection + { + /// + 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.Audit.Domain.AuditConfig", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-scoped audit configuration identity, not a person identifier."); + + 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("IsEnabled") + .HasColumnType("boolean") + .HasColumnName("is_enabled") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Operation catalogue selector and coverage toggle; no person values."); + + b.Property("ModuleName") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("module") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Operation catalogue selector and coverage toggle; no person values."); + + b.Property("Operation") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("character varying(150)") + .HasColumnName("operation") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Operation catalogue selector and coverage toggle; no person values."); + + b.Property("TenantId") + .HasColumnType("uuid") + .HasColumnName("tenant_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-scoped audit configuration identity, not a person identifier."); + + 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_audit_config"); + + b.HasIndex("TenantId", "ModuleName", "Operation") + .IsUnique() + .HasDatabaseName("ux_audit_config_tenant_id_module_operation") + .HasFilter("deleted_at IS NULL"); + + b.ToTable("audit_config", (string)null); + }); + + modelBuilder.Entity("LearnStack.Modules.Audit.Domain.AuditEntry", b => + { + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Audit record identity, institution scope and subject linkage."); + + b.Property("Timestamp") + .HasColumnType("timestamp with time zone") + .HasColumnName("timestamp") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Audit record identity, institution scope and subject linkage."); + + b.Property("ActorEmail") + .HasMaxLength(320) + .HasColumnType("character varying(320)") + .HasColumnName("actor_email") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Actor identity and originating address retained as audit evidence."); + + b.Property("ActorUserId") + .HasColumnType("uuid") + .HasColumnName("actor_user_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Actor identity and originating address retained as audit evidence."); + + b.Property("AfterState") + .HasColumnType("jsonb") + .HasColumnName("after_state") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Captured operation evidence may contain personal references and redacted personal payloads."); + + b.Property("BeforeState") + .HasColumnType("jsonb") + .HasColumnName("before_state") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Captured operation evidence may contain personal references and redacted personal payloads."); + + b.Property("Changes") + .HasColumnType("jsonb") + .HasColumnName("changes") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Captured operation evidence may contain personal references and redacted personal payloads."); + + b.Property("CorrelationId") + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("correlation_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Request correlation and client evidence can link an audited act to a person."); + + b.Property("EntityId") + .HasColumnType("text") + .HasColumnName("entity_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Audit record identity, institution scope and subject linkage."); + + b.Property("EntityType") + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("entity_type") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed operation, resource-type and outcome descriptors without person values."); + + b.Property("ErrorKey") + .HasMaxLength(150) + .HasColumnType("character varying(150)") + .HasColumnName("error_key") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed operation, resource-type and outcome descriptors without person values."); + + b.Property("IpAddress") + .HasColumnType("inet") + .HasColumnName("ip_address") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Actor identity and originating address retained as audit evidence."); + + b.Property("Metadata") + .HasColumnType("jsonb") + .HasColumnName("metadata") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Captured operation evidence may contain personal references and redacted personal payloads."); + + b.Property("ModuleName") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("module") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed operation, resource-type and outcome descriptors without person values."); + + b.Property("Operation") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("character varying(150)") + .HasColumnName("operation") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed operation, resource-type and outcome descriptors without person values."); + + b.Property("OperationClass") + .IsRequired() + .HasColumnType("text") + .HasColumnName("operation_class") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed operation, resource-type and outcome descriptors without person values."); + + b.Property("OperationType") + .IsRequired() + .HasColumnType("text") + .HasColumnName("operation_type") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed operation, resource-type and outcome descriptors without person values."); + + b.Property("OrganizationId") + .HasColumnType("uuid") + .HasColumnName("organization_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Audit record identity, institution scope and subject linkage."); + + b.Property("Outcome") + .IsRequired() + .HasColumnType("text") + .HasColumnName("outcome") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed operation, resource-type and outcome descriptors without person values."); + + b.Property("Reason") + .HasMaxLength(500) + .HasColumnType("character varying(500)") + .HasColumnName("reason") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Captured operation evidence may contain personal references and redacted personal payloads."); + + b.Property("TenantId") + .HasColumnType("uuid") + .HasColumnName("tenant_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Audit record identity, institution scope and subject linkage."); + + b.Property("UserAgent") + .HasMaxLength(512) + .HasColumnType("character varying(512)") + .HasColumnName("user_agent") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Request correlation and client evidence can link an audited act to a person."); + + b.HasKey("Id", "Timestamp") + .HasName("audit_log_pkey"); + + b.HasIndex("CorrelationId") + .HasDatabaseName("ix_audit_log_correlation_id") + .HasFilter("correlation_id IS NOT NULL"); + + b.HasIndex("ActorUserId", "Timestamp") + .IsDescending(false, true) + .HasDatabaseName("ix_audit_log_actor_user_id_timestamp") + .HasFilter("actor_user_id IS NOT NULL"); + + b.HasIndex("TenantId", "Timestamp") + .IsDescending(false, true) + .HasDatabaseName("ix_audit_log_tenant_id_timestamp"); + + b.HasIndex("ModuleName", "Operation", "Timestamp") + .IsDescending(false, false, true) + .HasDatabaseName("ix_audit_log_module_operation_timestamp"); + + b.HasIndex("TenantId", "EntityType", "EntityId", "Timestamp") + .IsDescending(false, false, false, true) + .HasDatabaseName("ix_audit_log_tenant_id_entity_type_entity_id_timestamp"); + + b.ToTable("audit_log", null, t => + { + t.HasCheckConstraint("ck_audit_log_operation_class", "operation_class IN ('Must', 'Should', 'May')"); + + t.HasCheckConstraint("ck_audit_log_operation_type", "operation_type IN ('Create', 'Update', 'Delete', 'ReadSensitive', 'SecurityEvent', 'PlatformAdmin', 'Action')"); + + t.HasCheckConstraint("ck_audit_log_outcome", "outcome IN ('success', 'denied', 'failed', 'indeterminate')"); + }); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/Migrations/20261122074947_index_audit_log_data_request_selection.cs b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/Migrations/20261122074947_index_audit_log_data_request_selection.cs new file mode 100644 index 000000000..0894ec4c5 --- /dev/null +++ b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/Migrations/20261122074947_index_audit_log_data_request_selection.cs @@ -0,0 +1,91 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace LearnStack.Modules.Audit.Infrastructure.Persistence.Migrations +{ + /// + /// Serves the subject data-request statements over audit_log (ADR-0107 § 3, § 6; ADR-0108 § 4) by index: + /// the rows about the person's User or Membership, and a newest-first window per branch of the reach (the + /// group's organization, the tenant-level rows) over the rows that carry a metadata person reference. + /// + /// + /// + /// Why. The export's selection, count, retained count and metadata count ran as one OR over the + /// actor, the entity and four JSON paths, which no existing index serves: each was a scan of the tenant's rows + /// under a bounded statement budget, so a tenant with millions of rows failed every export after its retries. + /// The statements are now unions of equality branches; the actor branch already has + /// ix_audit_log_actor_user_id_timestamp. + /// + /// + /// Why no expression index. Under the row policy PostgreSQL evaluates a non-leakproof qual only after the + /// policy, and every JSON operator is non-leakproof, so an index on metadata ->> 'causal_actor_user_id' + /// can never take the subject's value as an index condition (measured: the planner used such an index only for + /// its tenant column and filtered every keyed row). The partial index here instead orders the keyed rows newest + /// first, so the metadata count reads a bounded window of them. + /// + /// + /// Why two indexes, split by organization. The window is the request's reach, which the row policy draws by + /// organization: the group's organization and the tenant-level rows. Keyed by tenant alone, one index made an + /// organization's window read every newer keyed row of the tenant's other organizations and drop it at the policy, + /// so a small organization beside a large one scanned the large one's rows (measured: 2,000,000 rows read and + /// removed for an organization with none of its own). Each reach branch now has its own index in window order: + /// (tenant_id, organization_id, "timestamp" DESC) over the organization rows, and + /// (tenant_id, "timestamp" DESC) over the tenant-level rows, because PostgreSQL derives no ordering from an + /// organization_id IS NULL index condition and would sort the whole tenant-level branch instead of stopping + /// at the window. A keyed row has an entry in exactly one of the two. + /// + /// + /// Write cost. The entity index takes an entry for every row, the one cost this table pays on every + /// insert for the data-request read. The two person-reference indexes are partial on the keys' presence and + /// disjoint on the organization, so a row carries one entry only when it names a causal actor or an affected user + /// (job, delivery and provider-event rows); every other insert pays only the key tests. + /// + /// + /// Built inside the migration's transaction, as the earlier ledger indexes were: there is no production + /// data yet, and Phase 11's partition conversion recreates the indexes on the parent. Append-only is untouched: + /// an index is no row change, and the trigger guards UPDATE, DELETE and TRUNCATE only. + /// + /// + public partial class index_audit_log_data_request_selection : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateIndex( + name: "ix_audit_log_tenant_id_entity_type_entity_id_timestamp", + table: "audit_log", + columns: new[] { "tenant_id", "entity_type", "entity_id", "timestamp" }, + descending: new[] { false, false, false, true }); + + // The key predicate is repeated literally by both window branches of AuditUserDataParticipant's metadata + // statement, which is what lets the planner prove the partial indexes apply. + migrationBuilder.Sql(""" + CREATE INDEX ix_audit_log_tenant_id_organization_id_person_reference + ON public.audit_log (tenant_id, organization_id, "timestamp" DESC) + WHERE organization_id IS NOT NULL + AND (metadata ? 'causal_actor_user_id' OR (metadata -> 'authorization') ? 'causal_actor_user_id' + OR (metadata -> 'provider_event') ? 'affected_user_id'); + """); + migrationBuilder.Sql(""" + CREATE INDEX ix_audit_log_tenant_id_tenant_level_person_reference + ON public.audit_log (tenant_id, "timestamp" DESC) + WHERE organization_id IS NULL + AND (metadata ? 'causal_actor_user_id' OR (metadata -> 'authorization') ? 'causal_actor_user_id' + OR (metadata -> 'provider_event') ? 'affected_user_id'); + """); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + // Disposable-schema reversal only; live recovery uses a forward fix. + migrationBuilder.Sql("DROP INDEX public.ix_audit_log_tenant_id_tenant_level_person_reference;"); + migrationBuilder.Sql("DROP INDEX public.ix_audit_log_tenant_id_organization_id_person_reference;"); + + migrationBuilder.DropIndex( + name: "ix_audit_log_tenant_id_entity_type_entity_id_timestamp", + table: "audit_log"); + } + } +} diff --git a/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/Migrations/AuditDbContextModelSnapshot.cs b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/Migrations/AuditDbContextModelSnapshot.cs index d322d9a45..7072af3b8 100644 --- a/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/Migrations/AuditDbContextModelSnapshot.cs +++ b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/Migrations/AuditDbContextModelSnapshot.cs @@ -2,6 +2,7 @@ using System; using System.Net; using LearnStack.Modules.Audit.Infrastructure.Persistence; +using LearnStack.SharedKernel.DataProtection; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; @@ -18,6 +19,7 @@ protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder + .HasAnnotation("LearnStack:PersonalData:Validated", true) .HasAnnotation("ProductVersion", "10.0.12") .HasAnnotation("Relational:MaxIdentifierLength", 63); @@ -27,57 +29,81 @@ protected override void BuildModel(ModelBuilder modelBuilder) { b.Property("Id") .HasColumnType("uuid") - .HasColumnName("id"); + .HasColumnName("id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-scoped audit configuration identity, not a person identifier."); b.Property("CreatedAt") .HasColumnType("timestamp with time zone") - .HasColumnName("created_at"); + .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"); + .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"); + .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"); + .HasColumnName("deleted_by") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Attribute aggregate soft deletion to its actor."); b.Property("IsEnabled") .HasColumnType("boolean") - .HasColumnName("is_enabled"); + .HasColumnName("is_enabled") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Operation catalogue selector and coverage toggle; no person values."); b.Property("ModuleName") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)") - .HasColumnName("module"); + .HasColumnName("module") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Operation catalogue selector and coverage toggle; no person values."); b.Property("Operation") .IsRequired() .HasMaxLength(150) .HasColumnType("character varying(150)") - .HasColumnName("operation"); + .HasColumnName("operation") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Operation catalogue selector and coverage toggle; no person values."); b.Property("TenantId") .HasColumnType("uuid") - .HasColumnName("tenant_id"); + .HasColumnName("tenant_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Institution-scoped audit configuration identity, not a person identifier."); b.Property("UpdatedAt") .HasColumnType("timestamp with time zone") - .HasColumnName("updated_at"); + .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"); + .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"); + .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_audit_config"); @@ -94,104 +120,148 @@ protected override void BuildModel(ModelBuilder modelBuilder) { b.Property("Id") .HasColumnType("uuid") - .HasColumnName("id"); + .HasColumnName("id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Audit record identity, institution scope and subject linkage."); b.Property("Timestamp") .HasColumnType("timestamp with time zone") - .HasColumnName("timestamp"); + .HasColumnName("timestamp") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Audit record identity, institution scope and subject linkage."); b.Property("ActorEmail") .HasMaxLength(320) .HasColumnType("character varying(320)") - .HasColumnName("actor_email"); + .HasColumnName("actor_email") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Actor identity and originating address retained as audit evidence."); b.Property("ActorUserId") .HasColumnType("uuid") - .HasColumnName("actor_user_id"); + .HasColumnName("actor_user_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Actor identity and originating address retained as audit evidence."); b.Property("AfterState") .HasColumnType("jsonb") - .HasColumnName("after_state"); + .HasColumnName("after_state") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Captured operation evidence may contain personal references and redacted personal payloads."); b.Property("BeforeState") .HasColumnType("jsonb") - .HasColumnName("before_state"); + .HasColumnName("before_state") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Captured operation evidence may contain personal references and redacted personal payloads."); b.Property("Changes") .HasColumnType("jsonb") - .HasColumnName("changes"); + .HasColumnName("changes") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Captured operation evidence may contain personal references and redacted personal payloads."); b.Property("CorrelationId") .HasMaxLength(100) .HasColumnType("character varying(100)") - .HasColumnName("correlation_id"); + .HasColumnName("correlation_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Request correlation and client evidence can link an audited act to a person."); b.Property("EntityId") .HasColumnType("text") - .HasColumnName("entity_id"); + .HasColumnName("entity_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Audit record identity, institution scope and subject linkage."); b.Property("EntityType") .HasMaxLength(200) .HasColumnType("character varying(200)") - .HasColumnName("entity_type"); + .HasColumnName("entity_type") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed operation, resource-type and outcome descriptors without person values."); b.Property("ErrorKey") .HasMaxLength(150) .HasColumnType("character varying(150)") - .HasColumnName("error_key"); + .HasColumnName("error_key") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed operation, resource-type and outcome descriptors without person values."); b.Property("IpAddress") .HasColumnType("inet") - .HasColumnName("ip_address"); + .HasColumnName("ip_address") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Identity) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Actor identity and originating address retained as audit evidence."); b.Property("Metadata") .HasColumnType("jsonb") - .HasColumnName("metadata"); + .HasColumnName("metadata") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Captured operation evidence may contain personal references and redacted personal payloads."); b.Property("ModuleName") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)") - .HasColumnName("module"); + .HasColumnName("module") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed operation, resource-type and outcome descriptors without person values."); b.Property("Operation") .IsRequired() .HasMaxLength(150) .HasColumnType("character varying(150)") - .HasColumnName("operation"); + .HasColumnName("operation") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed operation, resource-type and outcome descriptors without person values."); b.Property("OperationClass") .IsRequired() .HasColumnType("text") - .HasColumnName("operation_class"); + .HasColumnName("operation_class") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed operation, resource-type and outcome descriptors without person values."); b.Property("OperationType") .IsRequired() .HasColumnType("text") - .HasColumnName("operation_type"); + .HasColumnName("operation_type") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed operation, resource-type and outcome descriptors without person values."); b.Property("OrganizationId") .HasColumnType("uuid") - .HasColumnName("organization_id"); + .HasColumnName("organization_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Audit record identity, institution scope and subject linkage."); b.Property("Outcome") .IsRequired() .HasColumnType("text") - .HasColumnName("outcome"); + .HasColumnName("outcome") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.None) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Closed operation, resource-type and outcome descriptors without person values."); b.Property("Reason") .HasMaxLength(500) .HasColumnType("character varying(500)") - .HasColumnName("reason"); + .HasColumnName("reason") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Captured operation evidence may contain personal references and redacted personal payloads."); b.Property("TenantId") .HasColumnType("uuid") - .HasColumnName("tenant_id"); + .HasColumnName("tenant_id") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Audit record identity, institution scope and subject linkage."); b.Property("UserAgent") .HasMaxLength(512) .HasColumnType("character varying(512)") - .HasColumnName("user_agent"); + .HasColumnName("user_agent") + .HasAnnotation("LearnStack:PersonalData:Category", PersonalDataCategory.Audit) + .HasAnnotation("LearnStack:PersonalData:Purpose", "Request correlation and client evidence can link an audited act to a person."); b.HasKey("Id", "Timestamp") .HasName("audit_log_pkey"); @@ -213,6 +283,10 @@ protected override void BuildModel(ModelBuilder modelBuilder) .IsDescending(false, false, true) .HasDatabaseName("ix_audit_log_module_operation_timestamp"); + b.HasIndex("TenantId", "EntityType", "EntityId", "Timestamp") + .IsDescending(false, false, false, true) + .HasDatabaseName("ix_audit_log_tenant_id_entity_type_entity_id_timestamp"); + b.ToTable("audit_log", null, t => { t.HasCheckConstraint("ck_audit_log_operation_class", "operation_class IN ('Must', 'Should', 'May')"); 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 000000000..d5a8f5334 --- /dev/null +++ b/backend/src/Modules/Customization/LearnStack.Modules.Customization.Infrastructure/DataRequests/CustomizationUserDataParticipant.cs @@ -0,0 +1,36 @@ +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) + : DescribeOnlyUserDataParticipant(db, tenant) +{ + public override string Key => "customization"; +} + +/// Registers the Customization module's participant and user-reference locator from its own boundary (ADR-0107 § 1, ADR-0108 § 7). +public static class CustomizationDataRequestRegistration +{ + public static IServiceCollection AddCustomizationUserDataParticipant(this IServiceCollection services) + { + ArgumentNullException.ThrowIfNull(services); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + return services; + } +} diff --git a/backend/src/Modules/Customization/LearnStack.Modules.Customization.Infrastructure/DataRequests/CustomizationUserReferenceLocator.cs b/backend/src/Modules/Customization/LearnStack.Modules.Customization.Infrastructure/DataRequests/CustomizationUserReferenceLocator.cs new file mode 100644 index 000000000..938e8cfb7 --- /dev/null +++ b/backend/src/Modules/Customization/LearnStack.Modules.Customization.Infrastructure/DataRequests/CustomizationUserReferenceLocator.cs @@ -0,0 +1,20 @@ +using LearnStack.Modules.Customization.Domain; +using LearnStack.SharedKernel.DataProtection; + +namespace LearnStack.Modules.Customization.Infrastructure.DataRequests; + +/// +/// Where the Customization module's audited definitions hold a person reference in their audit snapshots: their +/// creator, updater and deleter only +/// (ADR-0108 § 7). +/// +public sealed class CustomizationUserReferenceLocator : IUserReferenceLocator +{ + public IReadOnlyCollection Redactable { get; } = + [ + .. UserReferenceDeclarations.Attribution(typeof(TenantContentType), typeof(TenantLevelTaxonomy), + typeof(TenantCustomFieldDef)), + ]; + + public IReadOnlyCollection Retained { get; } = []; +} 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 000000000..4b4337bce --- /dev/null +++ b/backend/src/Modules/Education/LearnStack.Modules.Education.Infrastructure/DataRequests/EducationUserDataParticipant.cs @@ -0,0 +1,35 @@ +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) + : DescribeOnlyUserDataParticipant(db, tenant) +{ + public override string Key => "education"; +} + +/// Registers the Education module's participant and user-reference locator from its own boundary (ADR-0107 § 1, ADR-0108 § 7). +public static class EducationDataRequestRegistration +{ + public static IServiceCollection AddEducationUserDataParticipant(this IServiceCollection services) + { + ArgumentNullException.ThrowIfNull(services); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + return services; + } +} diff --git a/backend/src/Modules/Education/LearnStack.Modules.Education.Infrastructure/DataRequests/EducationUserReferenceLocator.cs b/backend/src/Modules/Education/LearnStack.Modules.Education.Infrastructure/DataRequests/EducationUserReferenceLocator.cs new file mode 100644 index 000000000..4370a7de5 --- /dev/null +++ b/backend/src/Modules/Education/LearnStack.Modules.Education.Infrastructure/DataRequests/EducationUserReferenceLocator.cs @@ -0,0 +1,19 @@ +using LearnStack.Modules.Education.Domain; +using LearnStack.SharedKernel.DataProtection; + +namespace LearnStack.Modules.Education.Infrastructure.DataRequests; + +/// +/// Where the Education module's audited aggregates hold a person reference in their audit snapshots: the creator, +/// updater and deleter of a course or a lesson +/// (ADR-0108 § 7). +/// +public sealed class EducationUserReferenceLocator : IUserReferenceLocator +{ + public IReadOnlyCollection Redactable { get; } = + [ + .. UserReferenceDeclarations.Attribution(typeof(Course), typeof(Lesson)), + ]; + + public IReadOnlyCollection Retained { get; } = []; +} 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 000000000..04f1c23ee --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/DataExportJobContracts.cs @@ -0,0 +1,19 @@ +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; + +/// +/// The erasure job's only input: the request it fulfils once its window has passed (ADR-0107 § 2, § 5). As for the +/// export, the group, the subject and the snapshot are read from the request row, never from the job. +/// +public sealed record DataErasureJobParameters(Guid RequestId) : IBackgroundJobParameters; 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 000000000..02efad4e7 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/DataRequestOperations.cs @@ -0,0 +1,257 @@ +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Idempotency; +using LearnStack.SharedKernel.Identifiers; +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 files an erasure of their own data in the session's group (ADR-0106 § 3): scheduled, executed +/// once its 24-hour cancellable window has passed (ADR-0106 § 11, ADR-0107 § 5). +/// +public sealed record CreateOwnDataErasureCommand : IRequest>; + +/// +/// The person, and only the person, files the closure of their whole account from the session's group, its +/// originating group (ADR-0106 § 3, ADR-0107 § 7): scheduled, its execution time 24 hours later. No job is +/// queued: an operator Begins it at or after that time, and it can be cancelled until that Begin commits (ADR-0106 +/// § 11). Once begun it is irreversible, and no in-product status remains after it completes. +/// +public sealed record CreateOwnAccountClosureCommand : 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 for an export, scheduled → cancelled for an erasure before its execution time +/// and for a closure until its Begin commits, 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>; + +/// +/// A holder of identity.membership.admin covering the group files an erasure for the person whose named +/// Membership in the group is already Revoked (ADR-0106 § 3): an Active or Suspended member is revoked first, by the +/// separately audited administration act. Never for themselves. +/// +public sealed record CreateDataErasureForSubjectCommand(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 for an export, scheduled → cancelled for an erasure before its execution time, 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; + +// ---- 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>; + +/// +/// The subject files an erasure of their own data in one retained group (ADR-0106 § 3, § 9): the path of a Suspended +/// person and of one whose Membership was revoked. +/// +public sealed record CreateRetainedDataErasureCommand(OrganizationId? OrganizationId) : IRequest>; + +/// +/// The subject files the closure of their whole account from one retained group, its originating group (ADR-0106 § 3, +/// § 9; ADR-0107 § 7): the path of a Suspended person and of one whose Membership was revoked. As +/// , no job is queued. +/// +public sealed record CreateRetainedAccountClosureCommand(OrganizationId? OrganizationId) : IRequest>; + +/// +/// requested → cancelled for an export, scheduled → cancelled for an erasure before its execution time +/// and for a closure until its Begin commits, by the subject in one retained group (ADR-0106 § 8, § 11). +/// +public sealed record CancelRetainedDataRequestCommand(OrganizationId? OrganizationId, Guid RequestId, long ExpectedVersion) + : IRequest>; + +/// +/// The subject revokes an unexpired export artifact of their own request in one retained group, which purges it at +/// once (ADR-0107 § 4). +/// +public sealed record RevokeRetainedDataExportCommand(OrganizationId? OrganizationId, Guid RequestId, long ExpectedArtifactVersion) + : 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.Contracts/DataRequests/IDataExportSessionBinding.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/IDataExportSessionBinding.cs new file mode 100644 index 000000000..14e14a264 --- /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.Contracts/DataRequests/IOwnDataRequestScopeLookup.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/DataRequests/IOwnDataRequestScopeLookup.cs new file mode 100644 index 000000000..073f8f057 --- /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.Contracts/OperatorActs/OperatorIdentityCommands.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/OperatorActs/OperatorIdentityCommands.cs index b30d813c8..72ba0e9fc 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/OperatorActs/OperatorIdentityCommands.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/OperatorActs/OperatorIdentityCommands.cs @@ -1,6 +1,7 @@ using LearnStack.SharedKernel.DataProtection; using LearnStack.SharedKernel.Identifiers; using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Platform; using LearnStack.SharedKernel.Results; using MediatR; @@ -50,3 +51,19 @@ public sealed record OperatorRecoverAdminCommand( Guid MembershipId, Guid RoleId, [property: PiiSensitive] string ProviderSubject) : IRequest>; + +/// +/// Fans a begun closure out to one participant group (fan_out_closure, ADR-0107 § 7): creates the closing +/// person's fan-out erasure in the group and enqueues its job, or adopts the erasure the group already has. +/// +/// +/// Reachable only through the operator source, one admission per group, which the closure's Begin owner mints after its +/// transaction commits. The tenant is the executor's: the group's tenant, announced with +/// , which names the same group so the handler can refuse a context the executor did +/// not build for it. The answer is how the group ended; a refusal is the failure result, which the fan-out reports as +/// a failed group. +/// +/// The person whose User is Closing. +/// The group's organization, or for the tenant-wide group. +public sealed record FanOutClosureCommand(UserId SubjectUserId, OrganizationId? OrganizationId) + : IRequest>; diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/ProviderEvents/IProviderEventTargets.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/ProviderEvents/IProviderEventTargets.cs index 55aed82a3..1547e5634 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/ProviderEvents/IProviderEventTargets.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/ProviderEvents/IProviderEventTargets.cs @@ -15,9 +15,14 @@ public interface IProviderEventAuditFactReader Task ReadAsync(Guid targetId, CancellationToken cancellationToken = default); } +/// A target's immutable fact, and whether its affected person may still be mirrored. +/// +/// Whether the affected person's User is Active now, read in the database under the person's User fence held shared +/// (ADR-0107 §§ 7, 9): a person whose account is closing or closed is refused by the delayed mirror, as by intake. +/// public sealed record ProviderEventAuditFact(Guid TargetId, Guid ReceiptId, Guid EventId, TenantId TenantId, IdentityAuthorityId AuthorityId, string RealmId, Guid ProviderEventId, UserId AffectedUserId, - DateTimeOffset SourceOccurredAt, IdentityProviderEventKind Kind) + DateTimeOffset SourceOccurredAt, IdentityProviderEventKind Kind, bool SubjectActive) { public override string ToString() => nameof(ProviderEventAuditFact); } 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 c8f8c9493..cd50b9f65 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,8 @@ 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.DataRequests; using LearnStack.Modules.Identity.Application.Contracts.Seeding; using LearnStack.Modules.Identity.Application.Contracts.OperatorActs; using LearnStack.Modules.Identity.Application.Contracts.Memberships; @@ -9,6 +11,7 @@ using LearnStack.Modules.Identity.Application.Contracts.Entry; using LearnStack.Modules.Identity.Application.Contracts.Federation; using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Platform; namespace LearnStack.Modules.Identity.Application.Audit; @@ -35,6 +38,61 @@ 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)); + // ADR-0107 § 5: a tenant erasure is one row about the erasure request (a cancelled export request travels in its + // changes) and one per kind of change it makes: the Memberships of the snapshot erased, the pending invitations the + // subject issued revoked, and the subject's artifact withdrawn. The erasure designates the first instance of each; + // a blocked or no-op run writes the rows with no subject. + builder.MustAudit("identity.data_request.fulfill_erasure", OperationType.SecurityEvent, typeof(DataSubjectRequest)); + builder.MustAudit("identity.membership.erase", OperationType.SecurityEvent, typeof(Membership)); + builder.MustAudit("identity.invitation.revoke", OperationType.SecurityEvent, typeof(Invitation)); + builder.MustAudit("identity.data_export.revoke", OperationType.Delete, typeof(DataExportArtifact)); + builder.MustAudit("identity.data_request.fulfill_erasure", OperationType.SecurityEvent, typeof(DataSubjectRequest)); + builder.MustAudit("identity.membership.erase", OperationType.SecurityEvent, typeof(Membership)); + builder.MustAudit("identity.invitation.revoke", OperationType.SecurityEvent, typeof(Invitation)); + builder.MustAudit("identity.data_export.revoke", 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.create_erasure", OperationType.Create, typeof(DataSubjectRequest)); + builder.MustAudit("identity.data_request.create_erasure", OperationType.Create, typeof(DataSubjectRequest)); + // ADR-0107 § 7: the person alone files a closure; no administrator operation names the slug. + builder.MustAudit("identity.data_request.create_closure", 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(); + // 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.create_erasure", OperationType.Create, typeof(DataSubjectRequest)); + builder.MustAudit("identity.data_request.create_closure", OperationType.Create, 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.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)); @@ -44,6 +102,10 @@ public void Describe(IAuditCatalogBuilder builder) builder.MustAudit("identity.role.initialize", OperationType.SecurityEvent, typeof(Role)); builder.MustAudit("identity.membership.create_first_admin", OperationType.SecurityEvent, typeof(Membership)); builder.MustAudit("identity.membership.recover_admin", OperationType.SecurityEvent, typeof(Membership)); + // ADR-0107 §§ 7, 8: a closure's fan-out writes one row in the participant tenant, about the group's fan-out erasure it + // created or the erasure it adopted or waits for; a person's or administrator's erasure it cancelled and replaced + // travels in that row's changes. A refused group writes the row with its refusal and no subject. + builder.MustAudit(PlatformOperations.ClosureFanOut.AuditSlug, OperationType.SecurityEvent, typeof(DataSubjectRequest)); builder.Off(); builder.Off(); builder.MustAudit(IdentityOperationPolicySource.MembershipDirectoryOperation, OperationType.ReadSensitive, typeof(Membership)); 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 69de26b7e..f359e79f1 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 a0a965c1b..525752cce 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 @@ -1,5 +1,7 @@ +using System.Collections.Frozen; using System.Collections.Immutable; using LearnStack.Modules.Identity.Application.Contracts.Authorization; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; using LearnStack.SharedKernel.Permissions; using LearnStack.Modules.Tenancy.Application.Contracts.FieldConsents; @@ -8,6 +10,25 @@ 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 closed set an policy may carry: the ten live-session request + /// types, each with its one operation id, as the consent-grant arm pins its single type. A policy of this kind on any + /// other type, or under another id, is not covered, so registering one confers nothing. + /// + internal static readonly FrozenDictionary OwnDataRequestOperations = new Dictionary + { + [typeof(CreateOwnDataExportCommand)] = IdentityOperationPolicySource.OwnDataExportCreateOperation, + [typeof(CreateOwnDataErasureCommand)] = IdentityOperationPolicySource.OwnDataErasureCreateOperation, + [typeof(CreateOwnAccountClosureCommand)] = IdentityOperationPolicySource.OwnAccountClosureCreateOperation, + [typeof(ListOwnDataRequestsQuery)] = IdentityOperationPolicySource.OwnDataRequestListOperation, + [typeof(GetOwnDataRequestQuery)] = IdentityOperationPolicySource.OwnDataRequestReadOperation, + [typeof(CancelOwnDataRequestCommand)] = IdentityOperationPolicySource.OwnDataRequestCancelOperation, + [typeof(RevokeOwnDataExportCommand)] = IdentityOperationPolicySource.OwnDataExportRevokeOperation, + [typeof(MintOwnDataExportTicketCommand)] = IdentityOperationPolicySource.OwnDataExportTicketOperation, + [typeof(ReadOwnDataExportChunkCommand)] = IdentityOperationPolicySource.OwnDataExportChunkOperation, + [typeof(ReadOwnDataRequestReceiptQuery)] = IdentityOperationPolicySource.OwnDataRequestReceiptOperation, + }.ToFrozenDictionary(); + internal static IdentityPolicyAssessment Evaluate(OperationPolicy policy, AuthorizationCandidate candidate, IdentityAuthorizationResult facts, IOperationPolicyCatalog catalog) { @@ -30,6 +51,21 @@ 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 + || !OwnDataRequestOperations.TryGetValue(policy.RequestType, out var operation) + || !string.Equals(operation, policy.Id, 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.Application/DataRequests/DataErasureJobs.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataErasureJobs.cs new file mode 100644 index 000000000..acd1a4fa7 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataErasureJobs.cs @@ -0,0 +1,253 @@ +using System.Diagnostics; +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; +using Microsoft.Extensions.Logging; + +namespace LearnStack.Modules.Identity.Application.DataRequests; + +public sealed record RunTenantDataErasureCommand(DataErasureJobParameters Parameters) : IRequest>; +public sealed record RunOrganizationDataErasureCommand(DataErasureJobParameters Parameters) : IRequest>; + +/// +/// The two transactional roots of the tenant-side erasure +/// (ADR-0107 § 1, § 2, § 5): +/// 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. The request store is the one write port; every other change is +/// the participants'. +/// +/// +/// +/// Fences first, then the row. The run reads the request without a lock to learn its subject, takes the subject's +/// exclusive User fence and then the tenant key exclusively (ADR-0107 § 5, the canonical order of ADR-0074), and only +/// then locks and re-reads the request. A cancellation holds the shared tenant fence, so it either committed before the +/// run took its fences, and the run is a recorded no-op, or it waits for the run to commit. +/// +/// +/// Asked twice. A scheduled erasure becomes fulfilling only once its execution time has passed by +/// the run's clock and the database's; a run that wakes early throws, so the runtime retries it rather than drop it. +/// Eligibility is judged again once it is fulfilling (ADR-0106 § 7): a hold or a sole administrator ends it +/// blocked with its code, and that is the run's committed business outcome. +/// +/// +/// One transaction. The transactional runtime owns exactly one transaction per root attempt, so every +/// participant's erasure runs on it in the registry's ordinal order, each recorded in the request's progress as it +/// finishes; the request then records the tenant side's retained report and waits for the operator's privileged step. +/// A failure rolls every write back and the runtime's retry runs the whole erasure again, so a committed erasure is +/// complete and a half-erased group never commits. ADR-0107 § 1's transaction per participant holds while only the +/// Identity participant writes; a resumed fulfilling request skips the participants its progress records. +/// +/// +/// Recorded no-ops. The runtime has no cancel call, so a job whose request is missing, of another kind, +/// cancelled or past its tenant side completes without changing anything, and its MUST rows record that it ran. +/// +/// +/// Signals. One log line per run carries the request identifier, the outcome and the duration; never a subject, +/// a group or a participant's content. A run its host cancelled is not a failure. +/// +/// +public sealed partial class DataErasureJobHandlers(IDataRequestStore store, IDataRequestReader reader, IIdentityMutationLocks locks, + ITenantContext tenant, IAuditSubject audit, IClock clock, IDataRequestEligibility eligibility, + IUserDataParticipantRegistry participants, ILogger logger) + : IRequestHandler>, + IRequestHandler> +{ + public Task> Handle(RunTenantDataErasureCommand request, CancellationToken cancellationToken) => + ObserveAsync(request.Parameters, cancellationToken); + + public Task> Handle(RunOrganizationDataErasureCommand request, CancellationToken cancellationToken) => + ObserveAsync(request.Parameters, cancellationToken); + + /// Runs the erasure and records its outcome; a failure is recorded and rethrown unchanged. + private async Task> ObserveAsync(DataErasureJobParameters parameters, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(parameters); + var started = Stopwatch.GetTimestamp(); + string outcome; + try + { + outcome = await EraseAsync(parameters, cancellationToken).ConfigureAwait(false); + } + catch (Exception failure) when (RecordFailure(parameters.RequestId, started, failure, cancellationToken)) + { + throw; // Unreachable: the filter records and declines, so the exception propagates unwound. + } + + var duration = Stopwatch.GetElapsedTime(started); + LogFinished(logger, parameters.RequestId, outcome, duration.TotalMilliseconds); + return Result.Ok(None.Value); + } + + /// Records a failed attempt and declines the exception; a run its host cancelled records nothing. + private bool RecordFailure(Guid requestId, long started, Exception failure, CancellationToken cancellationToken) + { + if (DataExportJobHandlers.IsHostCancellation(failure, cancellationToken)) + { + return false; + } + + // The exception's type only: a message or a provider's detail is not a closed value. + var duration = Stopwatch.GetElapsedTime(started); + LogFailed(logger, requestId, failure.GetType().Name, duration.TotalMilliseconds); + return false; + } + + private async Task EraseAsync(DataErasureJobParameters parameters, CancellationToken cancellationToken) + { + _ = store.RequireCurrentJob(); + if (parameters.RequestId == Guid.Empty || parameters.RequestId.Version != 7) + { + return "noop_invalid_parameters"; + } + + var requestId = DataSubjectRequestId.From(parameters.RequestId); + var observed = await reader.FindAsync(requestId, cancellationToken).ConfigureAwait(false); + if (observed is null) + { + return "noop_missing"; + } + + audit.Designate(observed); + if (observed.Kind != DataRequestKind.Erasure) + { + return "noop_not_erasure"; + } + + if (!Runs(observed.Status)) + { + return "noop_" + DataRequestCodes.Statuses.ToCode(observed.Status); + } + + // ADR-0107 § 5: the subject's exclusive User fence, then the tenant key exclusively, before any row lock. + var plan = new IdentityMutationLockPlan([observed.SubjectUserId], tenant.TenantId, IdentityTenantLockMode.Exclusive); + await locks.AcquireAsync(plan, cancellationToken).ConfigureAwait(false); + var request = await store.FindLockedAsync(requestId, cancellationToken).ConfigureAwait(false); + if (request is null) + { + return "noop_missing"; + } + + if (!Runs(request.Status)) + { + // Cancelled, or ended by another run, while this one waited for its fences. + return "noop_" + DataRequestCodes.Statuses.ToCode(request.Status); + } + + var actor = tenant.UserId ?? UserId.SystemActor; + if (request.Status == DataRequestStatus.Scheduled) + { + var at = DataRequestTransitionTime.Of(clock, request); + if (request.ExecuteAt is not { } due || at < due) + { + // The window has not ended by this run's clock: a run that woke early is retried, never dropped. + LogNotDue(logger, request.Id.Value); + throw new InvalidOperationException("The erasure is not yet due."); + } + + locks.RequireCurrent(plan); + Require(request.StartFulfilling(at, actor)); + await store.SaveAsync(request, cancellationToken).ConfigureAwait(false); + var decision = await eligibility.EvaluateAsync(new DataRequestEligibilityQuery(request.Kind, request.Origin, + request.SubjectUserId, request.Group, DataRequestEligibilityStage.Execution, request.Id.Value), cancellationToken) + .ConfigureAwait(false); + if (!decision.IsEligible) + { + // ADR-0106 § 7: a refusal at execution ends the erasure blocked with its code, and that commits. Any other + // reason is a broken invariant here: the request's own Membership snapshot and active slot hold it. + var refusal = decision.Refusal ?? throw new InvalidOperationException("An executing erasure lost its structure."); + Require(request.Block(refusal, DataRequestTransitionTime.Of(clock, request), actor)); + await store.SaveAsync(request, cancellationToken).ConfigureAwait(false); + return DataRequestCodes.Refusals.ToCode(refusal); + } + } + + var subject = new UserDataSubject(request.Id.Value, request.Kind, request.Origin, request.SubjectUserId, request.Group, + request.SnapshotMembershipIds.Select(membership => membership.Value)); + foreach (var participant in participants.Participants) + { + if (request.Progress.ContainsKey(participant.Key)) + { + continue; + } + + await DataExportJobHandlers.ParticipateAsync(async () => + { + await participant.EraseAsync(subject, cancellationToken).ConfigureAwait(false); + return true; + }, cancellationToken).ConfigureAwait(false); + + // A participant's own reads may have refreshed the shared change tracker; the request row is still this run's. + request = await RequireAsync(requestId, cancellationToken).ConfigureAwait(false); + locks.RequireCurrent(plan); + Require(request.RecordParticipantCompleted(participant.Key, DataRequestTransitionTime.Of(clock, request), actor)); + await store.SaveAsync(request, cancellationToken).ConfigureAwait(false); + } + + // The retained report is the post-erasure state, read on the same transaction after every write (ADR-0107 § 6). + var retained = await DataExportJobHandlers.ParticipateAsync(() => DescribeRetainedAsync(subject, cancellationToken), cancellationToken) + .ConfigureAwait(false); + request = await RequireAsync(requestId, cancellationToken).ConfigureAwait(false); + locks.RequireCurrent(plan); + Require(request.RecordRetained(retained, DataRequestTransitionTime.Of(clock, request), actor)); + await store.SaveAsync(request, cancellationToken).ConfigureAwait(false); + Require(request.AwaitPrivilegedStep(DataRequestTransitionTime.Of(clock, request), actor)); + await store.SaveAsync(request, cancellationToken).ConfigureAwait(false); + return "awaiting_privileged_step"; + } + + /// + /// A scheduled erasure runs from the start; a fulfilling one, such as a closure's fan-out erasure that + /// starts there (ADR-0107 § 7), resumes past the participants its progress records. Every other status is the job's + /// recorded no-op. + /// + private static bool Runs(DataRequestStatus status) => status is DataRequestStatus.Scheduled or DataRequestStatus.Fulfilling; + + private async Task RequireAsync(DataSubjectRequestId requestId, CancellationToken cancellationToken) => + await store.FindLockedAsync(requestId, cancellationToken).ConfigureAwait(false) is { Status: DataRequestStatus.Fulfilling } request + ? request + : throw new InvalidOperationException("The fulfilling erasure request changed under its own fences."); + + /// Every participant's retained references for the subject and group, summed per closed kind (ADR-0107 § 6). + private async Task> DescribeRetainedAsync(UserDataSubject subject, + CancellationToken cancellationToken) + { + 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))]; + } + + /// A transition refused here is a programming error: every precondition was checked under the fences. + private static void Require(Result transition) + { + if (transition.IsFailure) + { + throw new InvalidOperationException("A data request transition that its own preconditions admitted was refused."); + } + } + + [LoggerMessage(EventId = 7511, Level = LogLevel.Information, + Message = "Data erasure job for request {RequestId} finished ({Outcome}) in {DurationMilliseconds} ms.")] + private static partial void LogFinished(ILogger logger, Guid requestId, string outcome, double durationMilliseconds); + + [LoggerMessage(EventId = 7512, Level = LogLevel.Warning, + Message = "Data erasure {RequestId} is not yet due; the runtime retries.")] + private static partial void LogNotDue(ILogger logger, Guid requestId); + + [LoggerMessage(EventId = 7513, Level = LogLevel.Warning, + Message = "Data erasure {RequestId} attempt failed ({FailureType}) after {DurationMilliseconds} ms; its transaction rolls back for the runtime's retry.")] + private static partial void LogFailed(ILogger logger, Guid requestId, string failureType, double durationMilliseconds); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataErasureService.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataErasureService.cs new file mode 100644 index 000000000..66cb4e78a --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataErasureService.cs @@ -0,0 +1,207 @@ +using LearnStack.Modules.Identity.Application.Abstractions; +using LearnStack.Modules.Identity.Application.Invitations; +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 Identity module's tenant-side erasure of one subject in one scope group +/// (ADR-0107 § 5, § 6), +/// which the Identity participant runs inside the erasure job's transaction. It is the one minter of the +/// the erasure domain operations require. +/// +/// +/// +/// Under the job's evidence. It mints the witness only from the subject's erasure request of the ambient group +/// while that request is fulfilling and while the database shows this transaction holding the subject's User +/// fence and the tenant key, both exclusively: the canonical fences the job took first. Nothing here acquires a fence. +/// +/// +/// In ADR-0107 § 5's order. First the subject's exports in the group: every unexpired artifact is revoked (an +/// expired one purged) and a request not yet stored is cancelled, so an export job that built its bundle before the +/// erasure began finds its own request cancelled under its fence and discards the bundle. Then each Membership of the +/// frozen snapshot loses its role assignments and its profile and becomes the Revoked tombstone; one already erased +/// is left alone, and a Membership admitted after the snapshot is not part of this request. Last, the pending +/// invitations the subject issued in the group are revoked, with the subject as the aggregate actor; offers the subject +/// accepted, or that are addressed to them, stay as the record ADR-0107 § 6 retains. +/// +/// +/// Idempotent. Every step changes only what is not yet erased, so a retried or resumed run repeats nothing. +/// +/// +/// One audit row per kind of change. The erasure may write several instances of a type (the Memberships of the +/// snapshot, the invitations), so it designates the first instance of each it changed and the others travel in that +/// row's changes under their own pointers (ADR-0044 Amendment 6); the job designates its erasure request, beside +/// which a cancelled export request travels the same way. +/// +/// +public sealed class DataErasureService(IDataRequestStore requests, IDataExportArtifactStore artifacts, IMembershipWriteStore memberships, + IInvitationAdministrationStore invitations, IAuditSubject audit, ITenantContext tenant, IClock clock) +{ + /// How many pending invitations one statement locks and revokes; the loop repeats until none is left. + internal const int InvitationPage = 100; + + /// Erases the subject's tenant-side data in the ambient group for its fulfilling erasure request. + /// + /// The subject's request is not a fulfilling erasure of the ambient group, the fences are not held, or a stored row + /// contradicts the request's snapshot: the job's attempt fails and rolls back. + /// + public async Task EraseAsync(UserDataSubject subject, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(subject); + UserDataParticipantGuard.RequireGroup(subject, tenant); + var request = await requests.FindLockedAsync(DataSubjectRequestId.From(subject.RequestId), cancellationToken).ConfigureAwait(false); + if (request is null || request.Kind != DataRequestKind.Erasure || request.Status != DataRequestStatus.Fulfilling + || request.SubjectUserId != subject.SubjectUserId || request.Group != subject.Group) + { + throw new InvalidOperationException("Erasure runs only for its own fulfilling erasure request."); + } + + if (!await requests.HoldsErasureFencesAsync(request.SubjectUserId, cancellationToken).ConfigureAwait(false)) + { + throw new InvalidOperationException("Erasure runs only under the subject's and the tenant's exclusive fences."); + } + + using var source = new FulfillingErasure(request); + var witness = source.Mint(); + var actor = tenant.UserId ?? UserId.SystemActor; + await WithdrawExportsAsync(request, actor, cancellationToken).ConfigureAwait(false); + await EraseMembershipsAsync(witness, request.SnapshotMembershipIds, actor, cancellationToken).ConfigureAwait(false); + await RevokeIssuedInvitationsAsync(witness, cancellationToken).ConfigureAwait(false); + + // The deferred graph guards (a Membership keeps its profile; the tenant keeps an eligible administrator) run now, + // inside the job, so a refusal is the attempt's failure rather than an unexplained COMMIT fault. + await memberships.ValidateGraphAsync(cancellationToken).ConfigureAwait(false); + } + + /// + /// ADR-0107 § 5.1: revokes the subject's unexpired artifacts in the group (an expired one is purged, as the artifact + /// store decides by the database clock) and cancels the export request that is not yet stored. + /// + /// + /// The partial unique index on available artifacts holds at most one per subject and group, so the artifact row of + /// the erasure's audit names its one instance without a designation. + /// + private async Task WithdrawExportsAsync(DataSubjectRequest erasure, UserId actor, CancellationToken cancellationToken) + { + foreach (var artifact in await requests.FindAvailableArtifactsAsync(erasure.SubjectUserId, cancellationToken).ConfigureAwait(false)) + { + var outcome = await artifacts.PurgeAsync(new DataExportArtifactLocator(artifact.Value, erasure.Group), + DataExportArtifactStatus.Revoked, cancellationToken).ConfigureAwait(false); + if (outcome is not (DataExportArtifactStatus.Revoked or DataExportArtifactStatus.Purged)) + { + throw new InvalidOperationException("An export artifact could not be withdrawn by the erasure."); + } + } + + if (await requests.FindActiveLockedAsync(erasure.SubjectUserId, DataRequestKind.Export, cancellationToken).ConfigureAwait(false) + is { Status: DataRequestStatus.Requested } export) + { + Require(export.Cancel(DataRequestTransitionTime.Of(clock, export), actor)); + await requests.SaveAsync(export, cancellationToken).ConfigureAwait(false); + } + } + + /// + /// ADR-0107 § 5.2: every Membership of the frozen snapshot loses its assignments and profile and becomes the Revoked + /// tombstone, each saved on its own; the snapshot is at most . + /// + private async Task EraseMembershipsAsync(DataErasureWitness witness, IEnumerable snapshot, UserId actor, + CancellationToken cancellationToken) + { + var designated = false; + foreach (var id in snapshot) + { + var membership = await memberships.FindAsync(id, cancellationToken).ConfigureAwait(false); + if (membership is null || membership.TenantId != witness.TenantId || membership.OrganizationId != witness.OrganizationId + || membership.UserId != witness.SubjectUserId) + { + throw new InvalidOperationException("A Membership of the erasure's snapshot is not the subject's in its group."); + } + + if (membership.IsErased) + { + continue; + } + + var at = clock.UtcNow; + Require(membership.RemoveAssignmentsForErasure(witness, at, actor)); + Require(membership.ClearProfileForErasure(witness, at, actor)); + Require(membership.RevokeForErasure(witness, at, actor)); + if (!designated) + { + audit.Designate(membership); + designated = true; + } + + await memberships.UpdateAsync(membership, cancellationToken).ConfigureAwait(false); + } + } + + /// + /// ADR-0107 § 5.3: the pending invitations the subject issued in the group, a bounded page at a time, each revoked with + /// the subject as the aggregate actor. A revoked page is no longer pending, so the next statement reads the next page. + /// + private async Task RevokeIssuedInvitationsAsync(DataErasureWitness witness, CancellationToken cancellationToken) + { + var designated = false; + while (true) + { + var page = await invitations.FindPendingIssuedLockedAsync(witness.SubjectUserId, InvitationPage, cancellationToken) + .ConfigureAwait(false); + if (page.Count == 0) + { + return; + } + + var at = clock.UtcNow; + foreach (var invitation in page) + { + Require(invitation.RevokeForErasure(witness, at)); + } + + if (!designated) + { + audit.Designate(page[0]); + designated = true; + } + + await invitations.UpdateAsync(page[0], cancellationToken).ConfigureAwait(false); + if (page.Count < InvitationPage) + { + return; + } + } + } + + /// A refusal here is a programming error: the witness, the snapshot and the locks were all checked. + private static void Require(Result change) + { + if (change.IsFailure) + { + throw new InvalidOperationException("An erasure operation its own preconditions admitted was refused."); + } + } + + /// + /// The one production source of : current while its erasure request is still the + /// fulfilling erasure it was minted from and until the erasure that opened it returns. + /// + private sealed class FulfillingErasure(DataSubjectRequest request) : DataErasureWitness.MintingSource, IDisposable + { + private bool _closed; + + internal DataErasureWitness Mint() => Capture(request); + + protected override bool IsEvidenceCurrent => !_closed && request.Kind == DataRequestKind.Erasure + && request.Status == DataRequestStatus.Fulfilling; + + public void Dispose() => _closed = true; + } +} 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 000000000..b0c7144e6 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataExportDownloadService.cs @@ -0,0 +1,241 @@ +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. + /// + /// + /// + /// Under the artifact's row lock, so concurrent mints count each other. An artifact that is gone, unreadable or + /// whose key the ring no longer holds is refused with data_export_unavailable: only a new export helps. A + /// ticket row and its MUST audit row are permanent receipts, so minting is bounded and a bound reached is refused + /// with data_export_ticket_limit: at most open + /// tickets per session binding (wait for one to be consumed or to expire), and at most + /// ever per artifact (final: file a new export). + /// + /// + /// Each call records one measurement. + /// + /// + public async Task> MintTicketAsync(DataRequestCaller caller, Guid requestId, + CancellationToken cancellationToken) + { + var (result, outcome) = await MintCoreAsync(caller, requestId, cancellationToken).ConfigureAwait(false); + DataExportTelemetry.Download(DataExportDownloadOperation.Mint, outcome); + return result; + } + + private async Task<(Result Result, DataExportDownloadOutcome Outcome)> MintCoreAsync(DataRequestCaller caller, + Guid requestId, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(caller); + if (caller.Role != DataRequestRole.Subject) + { + return Refused(DataRequestRules.Fail("lockey_forbidden")); + } + + var request = await DataRequestRules.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 Refused(Result.Fail(current.Error)); + } + + if (request is null || request.Kind != DataRequestKind.Export) + { + return Refused(DataRequestRules.Fail("lockey_not_found")); + } + + if (found is null || !found.Readable || found.Artifact.SubjectUserId != caller.Actor) + { + return Refused(Unavailable()); + } + + if (!artifacts.CanOpen(found.Artifact.KeyVersion)) + { + return (Unavailable(), DataExportDownloadOutcome.CustodyFailed); + } + + var binding = sessions.Capture(caller.Actor, context.TenantId, context.OrganizationId); + if (binding is null) + { + return Refused(DataRequestRules.Fail("lockey_forbidden")); + } + + var counts = await tickets.CountAsync(found.Artifact.Id, binding, cancellationToken).ConfigureAwait(false); + if (counts.OpenInBinding >= DataRequestLimits.MaximumOpenTicketsPerBinding + || counts.Minted >= DataRequestLimits.MaximumTicketsPerArtifact) + { + return (DataRequestRules.Rule("artifact", "lockey_data_export_ticket_limit"), + DataExportDownloadOutcome.Limit); + } + + var (ticket, digest) = DataExportTicketCodec.Mint(); + var minted = DataExportTicket.Mint(DataExportTicketId.From(DataRequestRules.NewId(ids)), found.Artifact, digest, binding, clock.UtcNow, caller.Actor); + if (minted.IsFailure) + { + return Refused(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)), + DataExportDownloadOutcome.Served); + } + + private static Result Unavailable() => + DataRequestRules.Rule("artifact", "lockey_data_export_unavailable"); + + private static (Result Result, DataExportDownloadOutcome Outcome) Refused(Result refusal) => + (refusal, DataExportDownloadOutcome.Refused); + + /// + /// 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; a + /// chunk the store cannot open is counted as custody_failed in + /// , every other refusal as refused. + /// + public async Task> ReadChunkAsync(DataRequestCaller caller, Guid requestId, string ticket, int index, + CancellationToken cancellationToken) + { + var (result, outcome) = await ReadChunkCoreAsync(caller, requestId, ticket, index, cancellationToken).ConfigureAwait(false); + DataExportTelemetry.Download(DataExportDownloadOperation.Chunk, outcome); + return result; + } + + private async Task<(Result Result, DataExportDownloadOutcome Outcome)> ReadChunkCoreAsync(DataRequestCaller caller, + Guid requestId, string ticket, int index, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(caller); + var digest = DataExportTicketCodec.TryDigest(ticket); + if (digest is null || index < 0 || !DataRequestRules.ValidId(requestId)) + { + return Refused(DataRequestRules.Fail("lockey_validation_failed")); + } + + if (caller.Role != DataRequestRole.Subject) + { + return Refused(DataRequestRules.Fail("lockey_forbidden")); + } + + var held = await LockTicketAsync(caller, requestId, digest, cancellationToken).ConfigureAwait(false); + if (held.IsFailure) + { + return Refused(Result.Fail(held.Error)); + } + + var (artifact, found) = held.Value; + 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 Refused(DataRequestRules.Fail("lockey_not_found")); + } + + var chunk = await artifacts.ReadChunkAsync(new DataExportArtifactLocator(artifact.Artifact.Id.Value, Group), index, cancellationToken) + .ConfigureAwait(false); + if (chunk is null) + { + // A readable artifact's chunk inside its count that the store answers as absent could not be opened: its key + // left the ring or its ciphertext fails authentication (the store logs it). The subject sees not_found. + return (DataRequestRules.Fail("lockey_not_found"), DataExportDownloadOutcome.CustodyFailed); + } + + return await ServeAsync(found, chunk, now, cancellationToken).ConfigureAwait(false); + } + + /// + /// The ticket row under its lock, with the artifact it names, once the caller's authority is rechecked: the subject's + /// own request, its readable-or-not artifact and the ticket the digest selects. Anything absent is the one + /// not_found refusal. + /// + private async Task> LockTicketAsync(DataRequestCaller caller, Guid requestId, string digest, + CancellationToken cancellationToken) + { + var request = await DataRequestRules.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<(DataRequestArtifactRow Artifact, DataExportTicket Ticket)>.Fail(current.Error); + } + + return found is null + ? DataRequestRules.Fail<(DataRequestArtifactRow Artifact, DataExportTicket Ticket)>("lockey_not_found") + : Result.Ok((artifact!, found)); + } + + /// + /// Hands the plaintext to the transport and, for the final chunk, consumes the ticket on the same transaction. Every + /// copy of the plaintext that is not returned is cleared. + /// + private async Task<(Result Result, DataExportDownloadOutcome Outcome)> ServeAsync(DataExportTicket found, + DataExportPlaintextChunk chunk, DateTimeOffset now, CancellationToken cancellationToken) + { + 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 Refused(DataRequestRules.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)), DataExportDownloadOutcome.Served); + } +} 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 000000000..9e4e63e56 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataExportJobs.cs @@ -0,0 +1,440 @@ +using System.Data.Common; +using System.Diagnostics; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Errors; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using MediatR; +using Microsoft.Extensions.Logging; + +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. +/// +/// +/// +/// Read first, then fence and write. The run reads the request without a lock and, for a requested export, +/// builds the bundle and counts the retained references with no fence held: those are reads under READ COMMITTED, +/// driven by the request's subject, group and frozen Membership snapshot, which the request guard keeps immutable. +/// Only then does it take the Identity tenant fence shared, which the request guard requires of every request +/// write, and re-read the request locked: it writes only while the request is still requested at the version +/// it read. So an operation that takes the tenant fence exclusively (a suspension, a role-grant change, ADR-0107 +/// § 5's tenant erasure) never waits behind a bundle build, and an export cancelled or ended meanwhile is a recorded +/// no-op whose built bundle is discarded; an erasure that cancels a requested export first (§ 5) therefore never +/// meets an artifact stored over it. +/// +/// +/// 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. A durable fulfilling export therefore never exists: no committed state lies between +/// requested and the terminal one, and there is no partial run to resume. +/// +/// +/// 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. +/// +/// +/// Time. Each transition is stamped at the later of the worker's clock and the request's own last stamp, so +/// a worker whose clock lags the host that filed the request still orders its transitions after it. +/// +/// +/// Signals. Each run records and one log line carrying the request or +/// artifact identifier, the kind, the outcome, the byte and chunk counts and the duration; never a subject, a +/// group, a participant's content or another person's identifier. A run cancelled by its host is not a failure: +/// the runtime keeps the job and nothing is recorded. +/// +/// +public sealed partial class DataExportJobHandlers(IDataRequestStore store, IDataRequestReader reader, IIdentityMutationLocks locks, + ITenantContext tenant, IAuditSubject audit, IClock clock, IGuidFactory ids, IDataExportBundleBuilder bundles, + IUserDataParticipantRegistry participants, IDataExportArtifactStore artifacts, IDataRequestFulfillmentScheduler scheduler, + ILogger logger) + : IRequestHandler>, + IRequestHandler>, + IRequestHandler>, + IRequestHandler> +{ + private const string ExportKind = "export"; + + public Task> Handle(RunTenantDataExportCommand request, CancellationToken cancellationToken) => + ObserveExportAsync(request.Parameters, cancellationToken); + + public Task> Handle(RunOrganizationDataExportCommand request, CancellationToken cancellationToken) => + ObserveExportAsync(request.Parameters, cancellationToken); + + public Task> Handle(PurgeTenantDataExportCommand request, CancellationToken cancellationToken) => + ObservePurgeAsync(request.Parameters, cancellationToken); + + public Task> Handle(PurgeOrganizationDataExportCommand request, CancellationToken cancellationToken) => + ObservePurgeAsync(request.Parameters, cancellationToken); + + /// Runs the export and records its outcome; a failure is recorded and rethrown unchanged. + private async Task> ObserveExportAsync(DataExportJobParameters parameters, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(parameters); + var started = Stopwatch.GetTimestamp(); + ExportRun run; + try + { + run = await ExportAsync(parameters, cancellationToken).ConfigureAwait(false); + } + catch (Exception failure) when (RecordExportFailure(parameters.RequestId, started, failure, cancellationToken)) + { + throw; // Unreachable: the filter records and declines, so the exception propagates unwound. + } + + var duration = Stopwatch.GetElapsedTime(started); + DataExportTelemetry.Export(run.Outcome, duration, run.ByteCount, run.TruncatedCollections); + switch (run.Outcome) + { + case DataExportOutcome.Completed: + LogExportCompleted(logger, parameters.RequestId, ExportKind, run.ByteCount ?? 0, run.ChunkCount ?? 0, + run.TruncatedCollections, duration.TotalMilliseconds); + break; + case DataExportOutcome.FailedTooLarge: + LogExportTooLarge(logger, parameters.RequestId, ExportKind, duration.TotalMilliseconds); + break; + default: + LogExportNoOp(logger, parameters.RequestId, ExportKind, run.NoOpReason ?? "unknown", duration.TotalMilliseconds); + break; + } + + return Done(); + } + + /// + /// Records a failed attempt and declines the exception; a run its host cancelled is not a failure and records nothing. + /// + private bool RecordExportFailure(Guid requestId, long started, Exception failure, CancellationToken cancellationToken) + { + if (IsHostCancellation(failure, cancellationToken)) + { + return false; + } + + var duration = Stopwatch.GetElapsedTime(started); + DataExportTelemetry.Export(DataExportOutcome.Failed, duration); + // The exception's type only: a message or a provider's detail is not a closed value. + LogExportFailed(logger, requestId, ExportKind, failure.GetType().Name, duration.TotalMilliseconds); + return false; + } + + private async Task ExportAsync(DataExportJobParameters parameters, CancellationToken cancellationToken) + { + _ = store.RequireCurrentJob(); + if (parameters.RequestId == Guid.Empty || parameters.RequestId.Version != 7) + { + return ExportRun.NoOp("invalid_parameters"); + } + + var requestId = DataSubjectRequestId.From(parameters.RequestId); + var observed = await reader.FindAsync(requestId, cancellationToken).ConfigureAwait(false); + if (observed is null) + { + return ExportRun.NoOp("missing"); + } + + audit.Designate(observed); + + // Only a requested export runs: a durable fulfilling export never exists (see the remarks), and every other + // status is cancelled or terminal. + if (observed.Kind != DataRequestKind.Export) + { + return ExportRun.NoOp("not_export"); + } + + if (observed.Status != DataRequestStatus.Requested) + { + return ExportRun.NoOp("not_requested"); + } + + // The bundle and the retained counts are read with no fence held (see the remarks); the bundle is disposed on + // every path below, a no-op and a failure included. + var subject = new UserDataSubject(observed.Id.Value, observed.Kind, observed.Origin, observed.SubjectUserId, + observed.Group, observed.SnapshotMembershipIds.Select(membership => membership.Value)); + var built = await ParticipateAsync(() => bundles.BuildAsync(subject, clock.UtcNow, cancellationToken), cancellationToken) + .ConfigureAwait(false); + using var bundle = built.Bundle; + IReadOnlyCollection retained = bundle is null + ? [] + : await ParticipateAsync(() => DescribeRetainedAsync(subject, cancellationToken), cancellationToken).ConfigureAwait(false); + + return await WriteAsync(observed, bundle, retained, cancellationToken).ConfigureAwait(false); + } + + /// + /// Takes the shared tenant fence, re-reads the request locked and stores the outcome of the bundle built before: + /// failed with export_too_large when is , otherwise + /// the artifact and completed; a request no longer requested is a recorded no-op. + /// + private async Task WriteAsync(DataSubjectRequest observed, IDataExportBundle? bundle, + IReadOnlyCollection retained, CancellationToken cancellationToken) + { + await locks.AcquireAsync(new IdentityMutationLockPlan([], tenant.TenantId, IdentityTenantLockMode.Shared), cancellationToken) + .ConfigureAwait(false); + var request = await store.FindLockedAsync(observed.Id, cancellationToken).ConfigureAwait(false); + if (request is null) + { + return ExportRun.NoOp("missing"); + } + + audit.Designate(request); + if (request.Status != DataRequestStatus.Requested) + { + return ExportRun.NoOp("not_requested"); + } + + if (request.Version != observed.Version) + { + // A requested export admits no transition that keeps it requested, so this is a guard or storage fault: + // the attempt rolls back and the runtime's retry reads afresh. + throw new InvalidOperationException("A requested export changed between its read and its write."); + } + + var actor = tenant.UserId ?? UserId.SystemActor; + var at = DataRequestTransitionTime.Of(clock, request); + Require(request.StartFulfilling(at, actor)); + await store.SaveAsync(request, cancellationToken).ConfigureAwait(false); + if (bundle is null) + { + Require(request.Fail(DataRequestFailureReason.ExportTooLarge, at, actor)); + await store.SaveAsync(request, cancellationToken).ConfigureAwait(false); + return new ExportRun(DataExportOutcome.FailedTooLarge, null, null, 0, null); + } + + await StoreAsync(request, bundle, at, cancellationToken).ConfigureAwait(false); + foreach (var participant in participants.Participants) + { + var before = request.Version; + Require(request.RecordParticipantCompleted(participant.Key, at, actor)); + if (request.Version != before) + { + await store.SaveAsync(request, cancellationToken).ConfigureAwait(false); + } + } + + Require(request.Complete(WithStoredArtifact(retained), at, actor)); + await store.SaveAsync(request, cancellationToken).ConfigureAwait(false); + return new ExportRun(DataExportOutcome.Completed, bundle.ByteCount, bundle.ChunkCount, bundle.Truncations.Length, null); + } + + /// + /// The retained counts read before the artifact existed, with the artifact this run stores added as one + /// request_receipt: the export's own receipt is retained like every other. + /// + internal static IReadOnlyCollection WithStoredArtifact(IReadOnlyCollection retained) + { + ArgumentNullException.ThrowIfNull(retained); + var receipts = retained.Where(count => count.Kind == RetainedReferenceKind.RequestReceipt).Sum(count => count.Count); + return + [ + .. retained.Where(count => count.Kind != RetainedReferenceKind.RequestReceipt), + new RetainedReferenceCount(RetainedReferenceKind.RequestReceipt, checked(receipts + 1)), + ]; + } + + /// + /// 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(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(UserDataSubject subject, + CancellationToken cancellationToken) + { + 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))]; + } + + /// + /// A participant read that failed in the database, or outlived a statement budget, is the retryable + /// (dependency_unavailable) rather than an unexplained fault; a + /// participant's own refusal (a broken invariant) propagates unchanged. Nothing of the failure travels on. + /// + internal static async Task ParticipateAsync(Func> read, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(read); + try + { + return await read().ConfigureAwait(false); + } + catch (Exception failure) when (failure is DbException or TimeoutException + || failure is OperationCanceledException && !cancellationToken.IsCancellationRequested) + { + throw new InfrastructureException("Data export participant read unavailable."); + } + } + + private async Task> ObservePurgeAsync(DataExportPurgeParameters parameters, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(parameters); + var started = Stopwatch.GetTimestamp(); + DataExportPurgeOutcome outcome; + try + { + outcome = await PurgeAsync(parameters, cancellationToken).ConfigureAwait(false); + } + catch (Exception failure) when (RecordPurgeFailure(parameters.ArtifactId, started, failure, cancellationToken)) + { + throw; // Unreachable: the filter records and declines, so the exception propagates unwound. + } + + DataExportTelemetry.Purge(outcome); + var duration = Stopwatch.GetElapsedTime(started); + if (outcome == DataExportPurgeOutcome.NotDue) + { + LogPurgeNotDue(logger, parameters.ArtifactId, duration.TotalMilliseconds); + + // 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. + throw new InvalidOperationException("The export artifact is not yet due for purge."); + } + + var label = DataExportTelemetry.Label(outcome); + LogPurged(logger, parameters.ArtifactId, label, duration.TotalMilliseconds); + return Done(); + } + + /// Records a failed purge attempt and declines the exception; a host cancellation records nothing. + private bool RecordPurgeFailure(Guid artifactId, long started, Exception failure, CancellationToken cancellationToken) + { + if (IsHostCancellation(failure, cancellationToken)) + { + return false; + } + + var duration = Stopwatch.GetElapsedTime(started); + DataExportTelemetry.Purge(DataExportPurgeOutcome.Failed); + LogPurgeFailed(logger, artifactId, failure.GetType().Name, duration.TotalMilliseconds); + return false; + } + + private async Task PurgeAsync(DataExportPurgeParameters parameters, CancellationToken cancellationToken) + { + _ = store.RequireCurrentJob(); + if (parameters.ArtifactId == Guid.Empty || parameters.ArtifactId.Version != 7) + { + return DataExportPurgeOutcome.NoOp; + } + + var group = new DataRequestScopeGroup(tenant.TenantId, tenant.OrganizationId); + var outcome = await artifacts.PurgeAsync(new DataExportArtifactLocator(parameters.ArtifactId, group), + DataExportArtifactStatus.Purged, cancellationToken).ConfigureAwait(false); + + // Absent or revoked: nothing is left to purge; purged: no chunk is left, by this run or an earlier one. + return outcome switch + { + DataExportArtifactStatus.Available => DataExportPurgeOutcome.NotDue, + DataExportArtifactStatus.Purged => DataExportPurgeOutcome.Purged, + _ => DataExportPurgeOutcome.NoOp, + }; + } + + /// + /// The host stopped the run (its token is cancelled): the runtime keeps the job for a later attempt, so this is + /// not a failed attempt. A cancellation the host did not ask for is an ordinary failure. + /// + internal static bool IsHostCancellation(Exception failure, CancellationToken cancellationToken) => + failure is OperationCanceledException && cancellationToken.IsCancellationRequested; + + /// 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); + + [LoggerMessage(EventId = 7501, Level = LogLevel.Information, + Message = "Data export {RequestId} ({Kind}) completed: {ByteCount} bytes in {ChunkCount} chunks, {TruncatedCollections} truncated collections, in {DurationMilliseconds} ms.")] + private static partial void LogExportCompleted(ILogger logger, Guid requestId, string kind, long byteCount, int chunkCount, + int truncatedCollections, double durationMilliseconds); + + [LoggerMessage(EventId = 7502, Level = LogLevel.Information, + Message = "Data export job for request {RequestId} ({Kind}) completed as a recorded no-op ({Reason}) in {DurationMilliseconds} ms.")] + private static partial void LogExportNoOp(ILogger logger, Guid requestId, string kind, string reason, double durationMilliseconds); + + [LoggerMessage(EventId = 7503, Level = LogLevel.Warning, + Message = "Data export {RequestId} ({Kind}) failed with export_too_large after {DurationMilliseconds} ms; nothing was stored.")] + private static partial void LogExportTooLarge(ILogger logger, Guid requestId, string kind, double durationMilliseconds); + + [LoggerMessage(EventId = 7504, Level = LogLevel.Warning, + Message = "Data export {RequestId} ({Kind}) attempt failed ({FailureType}) after {DurationMilliseconds} ms; its transaction rolls back for the runtime's retry.")] + private static partial void LogExportFailed(ILogger logger, Guid requestId, string kind, string failureType, double durationMilliseconds); + + [LoggerMessage(EventId = 7505, Level = LogLevel.Information, + Message = "Data export artifact {ArtifactId} purge finished ({Outcome}) in {DurationMilliseconds} ms.")] + private static partial void LogPurged(ILogger logger, Guid artifactId, string outcome, double durationMilliseconds); + + [LoggerMessage(EventId = 7506, Level = LogLevel.Warning, + Message = "Data export artifact {ArtifactId} is not yet due for purge after {DurationMilliseconds} ms; the runtime retries.")] + private static partial void LogPurgeNotDue(ILogger logger, Guid artifactId, double durationMilliseconds); + + [LoggerMessage(EventId = 7507, Level = LogLevel.Warning, + Message = "Data export artifact {ArtifactId} purge attempt failed ({FailureType}) after {DurationMilliseconds} ms; its transaction rolls back for the runtime's retry.")] + private static partial void LogPurgeFailed(ILogger logger, Guid artifactId, string failureType, double durationMilliseconds); + + /// What one export run reached: the outcome, and for a stored bundle its size, chunks and truncations. + private sealed record ExportRun(DataExportOutcome Outcome, long? ByteCount, int? ChunkCount, int TruncatedCollections, string? NoOpReason) + { + public static ExportRun NoOp(string reason) => new(DataExportOutcome.NoOp, null, null, 0, reason); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataExportTelemetry.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataExportTelemetry.cs new file mode 100644 index 000000000..a41a5f6c3 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataExportTelemetry.cs @@ -0,0 +1,179 @@ +using System.Diagnostics.Metrics; + +namespace LearnStack.Modules.Identity.Application.DataRequests; + +/// How one export job run ended inside its transaction, the closed label set of the export counter. +public enum DataExportOutcome +{ + /// The request reached completed with a stored artifact. + Completed = 1, + + /// The bundle passed DataExport:MaxBytes; the request reached failed with export_too_large. + FailedTooLarge = 2, + + /// A missing, foreign-kind, cancelled or already terminal request: a recorded no-op. + NoOp = 3, + + /// The attempt threw; its transaction rolls back and the runtime retries or quarantines it. + Failed = 4, +} + +/// How one purge job run ended, the closed label set of the purge counter. +public enum DataExportPurgeOutcome +{ + /// The artifact holds no chunk and is recorded purged (by this run or an earlier one). + Purged = 1, + + /// The artifact is absent or was revoked: nothing was left to purge. + NoOp = 2, + + /// The database clock has not reached the expiry; the attempt throws and the runtime retries. + NotDue = 3, + + /// The attempt threw; its transaction rolls back and the runtime retries or quarantines it. + Failed = 4, +} + +/// Which download operation a download measurement is about, the closed operation label. +public enum DataExportDownloadOperation +{ + /// A ticket mint. + Mint = 1, + + /// A chunk read through a ticket. + Chunk = 2, +} + +/// How one download operation ended, the closed outcome label of the download counter. +public enum DataExportDownloadOutcome +{ + /// A ticket was minted, or a chunk was served. + Served = 1, + + /// Refused for any reason but the two below: absent, unreadable, foreign, unbound or invalid. + Refused = 2, + + /// A mint refused by a ticket bound (data_export_ticket_limit). + Limit = 3, + + /// The artifact's key is no longer in the ring, or a stored chunk could not be opened. + CustodyFailed = 4, +} + +/// +/// The export workflow's metrics (Standard 10, +/// ADR-0107 § 2–§ 4). +/// +/// +/// +/// Names follow the platform convention (learnstack_*_total, _bytes, _seconds), the meter is +/// covered by the host's learnstack.* subscription, and every label is a closed word from the enumerations +/// above: never a tenant, organization, request, artifact, person or collection name. +/// +/// +/// Recorded inside the transaction. The job runtime owns the commit, so an outcome here is what the handler +/// reached; a commit that then fails is the runtime's learnstack_job_failed_total, and the retry records again. +/// A download outcome is likewise what the handler reached before its request's MUST audit row and commit. +/// +/// +public static class DataExportTelemetry +{ + /// The meter name; covered by the host's learnstack.* subscription. + public const string MeterName = "learnstack.data_export"; + + /// Export job runs by outcome (completed, failed_too_large, noop, failed). + public const string ExportCounterName = "learnstack_data_export_total"; + + /// The plaintext size of each stored bundle (no label). + public const string BundleBytesHistogramName = "learnstack_data_export_bundle_bytes"; + + /// Export job run duration by outcome. + public const string DurationHistogramName = "learnstack_data_export_duration_seconds"; + + /// Collections a stored bundle states as truncated at their cap (no label). + public const string TruncationCounterName = "learnstack_data_export_truncations_total"; + + /// Purge job runs by outcome (purged, noop, not_due, failed). + public const string PurgeCounterName = "learnstack_data_export_purges_total"; + + /// + /// Download operations by operation (mint, chunk) and outcome (served, + /// refused, limit, custody_failed). + /// + public const string DownloadCounterName = "learnstack_data_export_downloads_total"; + + private static readonly Meter Meter = new(MeterName); + + private static readonly Counter Exports = + Meter.CreateCounter(ExportCounterName, description: "Data export job runs by outcome."); + + private static readonly Histogram BundleBytes = + Meter.CreateHistogram(BundleBytesHistogramName, unit: "By", description: "Plaintext size of each stored export bundle."); + + private static readonly Histogram Durations = + Meter.CreateHistogram(DurationHistogramName, unit: "s", description: "Data export job run duration by outcome."); + + private static readonly Counter Truncations = + Meter.CreateCounter(TruncationCounterName, description: "Collections stored export bundles state as truncated."); + + private static readonly Counter Purges = + Meter.CreateCounter(PurgeCounterName, description: "Data export purge job runs by outcome."); + + private static readonly Counter Downloads = + Meter.CreateCounter(DownloadCounterName, description: "Data export ticket mints and chunk reads by operation and outcome."); + + /// The closed label of an export outcome. + public static string Label(DataExportOutcome outcome) => outcome switch + { + DataExportOutcome.Completed => "completed", + DataExportOutcome.FailedTooLarge => "failed_too_large", + DataExportOutcome.NoOp => "noop", + _ => "failed", + }; + + /// The closed label of a purge outcome. + public static string Label(DataExportPurgeOutcome outcome) => outcome switch + { + DataExportPurgeOutcome.Purged => "purged", + DataExportPurgeOutcome.NoOp => "noop", + DataExportPurgeOutcome.NotDue => "not_due", + _ => "failed", + }; + + /// The closed label of a download operation. + public static string Label(DataExportDownloadOperation operation) => operation == DataExportDownloadOperation.Mint ? "mint" : "chunk"; + + /// The closed label of a download outcome. + public static string Label(DataExportDownloadOutcome outcome) => outcome switch + { + DataExportDownloadOutcome.Served => "served", + DataExportDownloadOutcome.Limit => "limit", + DataExportDownloadOutcome.CustodyFailed => "custody_failed", + _ => "refused", + }; + + /// Records one export run; the size and truncations only for a stored bundle. + public static void Export(DataExportOutcome outcome, TimeSpan duration, long? bundleBytes = null, int truncatedCollections = 0) + { + var label = new KeyValuePair("outcome", Label(outcome)); + Exports.Add(1, label); + Durations.Record(duration.TotalSeconds, label); + if (outcome == DataExportOutcome.Completed && bundleBytes is { } bytes) + { + BundleBytes.Record(bytes); + if (truncatedCollections > 0) + { + Truncations.Add(truncatedCollections); + } + } + } + + /// Records one purge run. + public static void Purge(DataExportPurgeOutcome outcome) => + Purges.Add(1, new KeyValuePair("outcome", Label(outcome))); + + /// Records one download operation, as the handler reached it inside the request's transaction. + public static void Download(DataExportDownloadOperation operation, DataExportDownloadOutcome outcome) => + Downloads.Add(1, new KeyValuePair("operation", Label(operation)), + new KeyValuePair("outcome", Label(outcome))); +} 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 000000000..0a1da734a --- /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 000000000..a78f710ca --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestAuthorization.cs @@ -0,0 +1,69 @@ +using LearnStack.Modules.Identity.Application.Authorization; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +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 DataRequestRules.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 DataRequestRules.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 DataRequestRules.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 DataRequestRules.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 CreateDataErasureForSubjectCommand or ListDataRequestsQuery or GetDataRequestQuery or CancelDataRequestCommand + or RevokeDataExportCommand or ReadDataRequestReceiptQuery; + + /// The subject's request types: exactly the closed set an policy may carry. + private static bool IsOwn(object request) => + request is not null && IdentityPolicyEvaluation.OwnDataRequestOperations.ContainsKey(request.GetType()); + + 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); +} 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 000000000..dfa2d11e8 --- /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 000000000..ae684e1bb --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestEligibility.cs @@ -0,0 +1,76 @@ +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; an erasure of the tenant-wide group is refused while the subject is the tenant's only eligible +/// tenant-wide administrator; and the registered reports no hold. It reads on the +/// caller's announced group transaction as learnstack_app and confers no authority. +/// +/// +/// Only the tenant-wide group can remove an administrator. A tenant administrator Membership is tenant-wide, so an +/// organization group's erasure never touches one and is never refused for it. +/// +/// +/// 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. +/// +/// +/// A closure is judged here only at its creation (ADR-0107 § 7): the subject holds a Membership of any status in +/// the originating group, no other closure of the subject is active in that group, and no hold applies. It is never +/// refused for the last administrator here: that check is its Begin's, across every participant tenant, which this +/// port cannot read. For the same reason a closure's execution is not judged here: asked at +/// about that 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.Closure && query.Stage != DataRequestEligibilityStage.Creation) + { + throw new InvalidOperationException("A closure's execution is judged by its Begin across every participant tenant (ADR-0107 § 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); + } + + if (query.Kind == DataRequestKind.Erasure && query.Group.IsTenantWide + && await store.IsSoleEligibleTenantAdministratorAsync(query.SubjectUserId, cancellationToken).ConfigureAwait(false)) + { + return DataRequestEligibilityDecision.Refused(DataRequestIneligibility.BlockedLastAdministrator); + } + + 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 new file mode 100644 index 000000000..45f52d32d --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestFailureReconciler.cs @@ -0,0 +1,146 @@ +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 and a dead erasure's scheduled: +/// each transactional job rolled every write back, and neither commits fulfilling on its own +/// (, ). It takes → fulfilling and then +/// fulfilling → failed as two saves, because the request guard admits one arrow per UPDATE; both are the +/// aggregate's own transitions. An erasure takes the first only once its execution time has passed, as the aggregate and +/// the guard require, so a dead erasure job is stored failed from then on. It runs on the caller's tenant transaction +/// under the 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 EffectiveStatus(request.Kind, request.Status, phase); + } + + /// The same answer from a receipt's kind and stored status, for a page that never loads the aggregate. + public static DataRequestStatus EffectiveStatus(DataRequestKind kind, DataRequestStatus status, DataRequestJobPhase phase) => + !DataRequestCodes.IsTerminal(status) && phase == DataRequestJobPhase.Dead && CanFail(kind, status) + ? DataRequestStatus.Failed + : 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 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.Kind, request.Status) || request.TenantId != tenant.TenantId + || request.OrganizationId != tenant.OrganizationId) + { + return false; + } + + // Never before the request's own last stamp: a host whose clock lags the one that filed it still orders. + var now = DataRequestTransitionTime.Of(clock, request); + if (request.ExecuteAt is { } due && now < due) + { + // A scheduled erasure cannot start before its window ends (ADR-0106 § 11), so it cannot be failed either. + return false; + } + + if (await phases.ReadAsync(request.Id, request.Kind, cancellationToken).ConfigureAwait(false) != DataRequestJobPhase.Dead) + { + return 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 actor = tenant.UserId ?? UserId.SystemActor; + 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; + } + + /// + /// Whether a request of this kind and stored status can have a dead job that left it there: a requested export or a + /// scheduled erasure, because each job commits fulfilling only together with the status it ends in. A closure + /// has no job (ADR-0107 § 7), so it is never failed: its execution is the operator's Begin. + /// + internal static bool CanFail(DataRequestKind kind, DataRequestStatus status) => (kind, status) is + (DataRequestKind.Export, DataRequestStatus.Requested) or (DataRequestKind.Erasure, DataRequestStatus.Scheduled); + + private static void Require(bool admitted) + { + if (!admitted) + { + throw new InvalidOperationException("A failure transition its own preconditions admitted was refused."); + } + } +} + +/// +/// When a data request transition is stamped: the later of the clock and the request's own last stamp, so a host whose +/// clock lags the one that filed or last changed the request still orders its transition after it, which the aggregate +/// and the request guard both require. Shared by the export and erasure jobs and the failure reconciler. +/// +internal static class DataRequestTransitionTime +{ + internal static DateTimeOffset Of(IClock clock, DataSubjectRequest request) + { + ArgumentNullException.ThrowIfNull(clock); + ArgumentNullException.ThrowIfNull(request); + var now = clock.UtcNow; + var floor = request.UpdatedAt ?? request.CreatedAt; + return now > floor ? now : floor; + } +} 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 000000000..68affb225 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestFulfillmentScheduler.cs @@ -0,0 +1,146 @@ +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +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). +/// +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; + } +} + +/// +/// The two transactional definitions of the tenant-side erasure, one per scope group +/// (ADR-0107 § 2, § 5). +/// +public static class DataErasureJobKeys +{ + public static BackgroundJobKey TenantErasure { get; } = new("identity.data_erasure_tenant.v1"); + public static BackgroundJobKey OrganizationErasure { get; } = new("identity.data_erasure_organization.v1"); + + /// The erasure definition of a group. + public static BackgroundJobKey ErasureFor(DataRequestScopeGroup group) + { + ArgumentNullException.ThrowIfNull(group); + return group.IsTenantWide ? TenantErasure : OrganizationErasure; + } +} + +/// +/// What a new request's fulfilment needs, as values rather than the aggregate: submitting a job writes no request, and +/// the aggregate write port stays the one the census counts. +/// +/// +/// When a scheduled request may execute; for an export, which runs at once, and for a closure's +/// fan-out erasure, which is born fulfilling. +/// +/// Who filed the request: the person, an administrator, or a closure's fan-out. +public sealed record DataRequestFulfillment(Guid RequestId, DataRequestKind Kind, DataRequestStatus Status, DataRequestScopeGroup Group, + DateTimeOffset? ExecuteAt, DataRequestOrigin Origin); + +/// +/// 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: a requested export's at once, a scheduled erasure's at its + /// execution time, the end of the cancellable window (ADR-0107 § 2), and a closure's fan-out erasure's at once, because + /// it is born fulfilling and its job resumes it from there (ADR-0107 § 7). A scheduled closure is accepted and + /// submits nothing: it has no job, because its execution is the operator's Begin (ADR-0107 § 7). + /// + /// + /// A fan-out erasure's job is submitted again when a repeated Begin finds the request still fulfilling with no + /// job in flight; the job runs a fulfilling request past the participants its progress records, and a second job + /// of a request the first one finished is a recorded no-op. + /// + /// + /// The request is not a requested export, a scheduled erasure or closure with its execution time, or a + /// fulfilling fan-out erasure without one, of the announced group: a programming error, because the creation + /// path decides the kind and the group before it submits. + /// + ValueTask SubmitAsync(DataRequestFulfillment fulfillment, CancellationToken cancellationToken); + + /// Schedules the purge of an artifact's chunks at , its expiry (ADR-0107 § 4). + 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(DataRequestFulfillment fulfillment, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(fulfillment); + var group = fulfillment.Group ?? throw new ArgumentException("A fulfilment names its group.", nameof(fulfillment)); + if (fulfillment.RequestId == Guid.Empty || fulfillment.RequestId.Version != 7 + || group.TenantId != tenant.TenantId || group.OrganizationId != tenant.OrganizationId) + { + throw new InvalidOperationException("A fulfilment job is submitted only for a request of the announced group."); + } + + switch (fulfillment) + { + case { Kind: DataRequestKind.Export, Status: DataRequestStatus.Requested, ExecuteAt: null }: + await scheduler.EnqueueAsync(DataExportJobKeys.ExportFor(group), new DataExportJobParameters(fulfillment.RequestId), + cancellationToken).ConfigureAwait(false); + return; + case + { + Kind: DataRequestKind.Erasure, Status: DataRequestStatus.Scheduled, ExecuteAt: { } due, + Origin: not DataRequestOrigin.ClosureFanout + } when due != default: + // ADR-0107 § 2: due when the window ends, so no recurrence is introduced; the runtime has no cancel call, + // and a job whose request was cancelled meanwhile completes as a recorded no-op. + await scheduler.ScheduleAsync(DataErasureJobKeys.ErasureFor(group), new DataErasureJobParameters(fulfillment.RequestId), + due, cancellationToken).ConfigureAwait(false); + return; + case { Kind: DataRequestKind.Closure, Status: DataRequestStatus.Scheduled, ExecuteAt: { } begins } when begins != default: + // ADR-0107 § 7: a closure is executed by the operator's Begin, an act in the platform scope that no job + // holds the authority for; filing one submits nothing. + return; + case { Kind: DataRequestKind.Erasure, Status: DataRequestStatus.Fulfilling, ExecuteAt: null, Origin: DataRequestOrigin.ClosureFanout }: + // ADR-0107 § 7: a closure's fan-out erasure has no window; its job runs now, on the producer transaction + // that created or adopted the request, so the two commit together or not at all. + await scheduler.EnqueueAsync(DataErasureJobKeys.ErasureFor(group), new DataErasureJobParameters(fulfillment.RequestId), + cancellationToken).ConfigureAwait(false); + return; + default: + throw new InvalidOperationException( + "Only a requested export, a scheduled erasure or closure, or a closure's fulfilling fan-out erasure, of the announced group is a fulfilment."); + } + } + + public async ValueTask SchedulePurgeAsync(Guid artifactId, DateTimeOffset dueAt, CancellationToken cancellationToken) + { + 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), 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 000000000..7810ecca3 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestHandlers.cs @@ -0,0 +1,218 @@ +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 CreateOwnDataErasureCommandHandler(LiveDataRequestAdmission admission, DataRequestService service) + : IRequestHandler> +{ + public async Task> Handle(CreateOwnDataErasureCommand request, CancellationToken cancellationToken) + { + var caller = await admission.AdmitAsync(request, cancellationToken).ConfigureAwait(false); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.CreateErasureAsync(caller.Value, caller.Value.Actor, cancellationToken).ConfigureAwait(false); + } +} + +/// The person files the closure of their account from the session's group (ADR-0107 § 7); an administrator never does. +public sealed class CreateOwnAccountClosureCommandHandler(LiveDataRequestAdmission admission, DataRequestService service) + : IRequestHandler> +{ + public async Task> Handle(CreateOwnAccountClosureCommand request, CancellationToken cancellationToken) + { + var caller = await admission.AdmitAsync(request, cancellationToken).ConfigureAwait(false); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.CreateClosureAsync(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 CreateDataErasureForSubjectCommandHandler(LiveDataRequestAdmission admission, DataRequestService service) + : IRequestHandler> +{ + public async Task> Handle(CreateDataErasureForSubjectCommand request, CancellationToken cancellationToken) + { + var caller = await admission.AdmitAsync(request, cancellationToken).ConfigureAwait(false); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.CreateErasureForMembershipAsync(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/DataRequestRules.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestRules.cs new file mode 100644 index 000000000..35d6e94e7 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestRules.cs @@ -0,0 +1,56 @@ +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Localization; +using LearnStack.SharedKernel.Results; + +namespace LearnStack.Modules.Identity.Application.DataRequests; + +/// +/// What the data-request executors and admissions share: which requests a caller reaches and mutates, how an identifier +/// is minted and judged, and how a refusal is spelled. +/// +internal static class DataRequestRules +{ + /// 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. + internal 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; + + 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; + + internal 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/DataRequestService.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestService.cs new file mode 100644 index 000000000..31b40c3ee --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestService.cs @@ -0,0 +1,531 @@ +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.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 (ADR-0106 § 7, § 8, § 10; ADR-0107 + /// § 2). The subject's own export withdraws their previous artifact when it stores its own; an administrator's is + /// refused while the subject holds a readable artifact in the group. + /// + public Task> CreateExportAsync(DataRequestCaller caller, UserId subject, + CancellationToken cancellationToken) => CreateAsync(caller, subject, DataRequestKind.Export, cancellationToken); + + /// + /// Files an erasure of 's data in the announced group: scheduled, its job due when the + /// 24-hour cancellable window ends (ADR-0106 § 7, § 11; ADR-0107 § 2, § 5). An administrator files one only for a + /// person whose Membership in the group is already Revoked (ADR-0106 § 3). + /// + public Task> CreateErasureAsync(DataRequestCaller caller, UserId subject, + CancellationToken cancellationToken) => CreateAsync(caller, subject, DataRequestKind.Erasure, cancellationToken); + + /// + /// The person files the closure of their whole account from the announced group, its originating group (ADR-0106 + /// § 3, § 11; ADR-0107 § 7): scheduled, its execution time when the 24-hour window ends. The person alone files + /// it, so an administrator caller is refused before anything is read. No job is submitted: the closure is executed by + /// the operator's Begin, at or after its execution time, and can be cancelled until that Begin commits. + /// + public Task> CreateClosureAsync(DataRequestCaller caller, UserId subject, + CancellationToken cancellationToken) => CreateAsync(caller, subject, DataRequestKind.Closure, cancellationToken); + + /// + /// Files a request of under the subject's exclusive User fence and the shared tenant fence, + /// with the frozen Membership snapshot, and submits its fulfilment on the same transaction (ADR-0106 § 7, § 8, § 10; + /// ADR-0107 § 2): an export's job at once, an erasure's at its execution time, and a closure none. + /// + private async Task> CreateAsync(DataRequestCaller caller, UserId subject, DataRequestKind kind, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(caller); + if (kind == DataRequestKind.Closure && caller.Role != DataRequestRole.Subject) + { + // ADR-0106 § 3, ADR-0107 § 7: no administrator creates a closure. + return DataRequestRules.Fail("lockey_forbidden"); + } + + 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 DataRequestRules.Rule("$", + caller.Role == DataRequestRole.Administrator && subject == caller.Actor + ? "lockey_subject_is_requester" + : "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 request's job died is never locked out. + if (await store.FindActiveLockedAsync(subject, kind, cancellationToken).ConfigureAwait(false) is { } existing) + { + await reconciler.ReconcileAsync(existing, plan, cancellationToken).ConfigureAwait(false); + } + + var memberships = await CheckCreationAsync(caller, subject, kind, cancellationToken).ConfigureAwait(false); + if (memberships.IsFailure) + { + return Result.Fail(memberships.Error); + } + + var created = File(caller, subject, kind, memberships.Value); + if (created.IsFailure) + { + return Result.Fail(created.Error); + } + + var request = created.Value; + audit.Designate(request); + locks.RequireCurrent(plan); + var insertion = await store.TryAddAsync(request, cancellationToken).ConfigureAwait(false); + if (insertion != DataRequestInsertion.Added) + { + // ADR-0107 § 7: a subject not admitted is a person whose account began closing after this filing was + // admitted, or for whom an administrator filed while it closes. A closed refusal, never a storage fault. + return insertion == DataRequestInsertion.SubjectNotAdmitted + ? DataRequestRules.Rule("$", "lockey_subject_not_admitted") + : DataRequestRules.AlreadyActive(); + } + + await scheduler.SubmitAsync(new DataRequestFulfillment(request.Id.Value, request.Kind, request.Status, request.Group, + request.ExecuteAt, request.Origin), cancellationToken).ConfigureAwait(false); + return Result.Ok(new DataRequestMutationResult(request.Id.Value, request.Version)); + } + catch (IdentityMutationLockException) + { + return DataRequestRules.Fail("lockey_dependency_unavailable"); + } + } + + /// + /// The creation guards, judged under the fences: the subject's eligibility (for a closure the structure of its + /// originating group and the hold port; the last-administrator check is its Begin's); an administrator's export refused while + /// the subject holds a readable artifact, and an administrator's erasure refused unless the subject's Membership in + /// the group is Revoked; and the Membership snapshot to freeze. A refusal is the failed result and writes nothing. + /// + private async Task>> CheckCreationAsync(DataRequestCaller caller, UserId subject, + DataRequestKind kind, CancellationToken cancellationToken) + { + var origin = caller.Role == DataRequestRole.Subject ? DataRequestOrigin.Self : DataRequestOrigin.Administrator; + var decision = await eligibility.EvaluateAsync(new DataRequestEligibilityQuery(kind, origin, subject, + Group, DataRequestEligibilityStage.Creation), cancellationToken).ConfigureAwait(false); + if (!decision.IsEligible) + { + return decision.Reason switch + { + DataRequestIneligibility.NoMembership => DataRequestRules.Fail>("lockey_not_found"), + DataRequestIneligibility.RequestAlreadyActive => DataRequestRules.AlreadyActive>(), + DataRequestIneligibility.BlockedHold => DataRequestRules.Rule>("$", "lockey_blocked_hold"), + _ => DataRequestRules.Rule>("$", "lockey_blocked_last_administrator"), + }; + } + + // An administrator's export never replaces the subject's own readable artifact (a new export withdraws the + // previous one): while the subject holds one in the group, of any origin, it is refused. One active export + // per subject and group means no export can store an artifact between this read and the insert that follows. + if (caller.Role == DataRequestRole.Administrator && kind == DataRequestKind.Export + && await store.HoldsReadableArtifactAsync(subject, cancellationToken).ConfigureAwait(false)) + { + return DataRequestRules.Rule>("$", "lockey_subject_export_available"); + } + + // ADR-0106 § 3: an administrator erases only a person whose Membership of the group is Revoked, so no + // administrator destroys a working member's data in one step; revoking the Membership is the separately audited + // act that comes first. The group holds at most one current row (ux_memberships_current_scope); it is read under + // the subject's User fence, which every admission of the subject also takes, so none appears meanwhile. + if (caller.Role == DataRequestRole.Administrator && kind == DataRequestKind.Erasure + && await store.HoldsCurrentMembershipAsync(subject, cancellationToken).ConfigureAwait(false)) + { + return DataRequestRules.Rule>("$", "lockey_subject_membership_current"); + } + + var memberships = await store.ReadSubjectMembershipsAsync(subject, cancellationToken).ConfigureAwait(false); + if (memberships.Count == 0) + { + return DataRequestRules.Fail>("lockey_not_found"); + } + + return memberships.Count > DataRequestLimits.MaximumSnapshotMemberships + ? DataRequestRules.Rule>("$", "lockey_snapshot_too_large") + : Result.Ok(memberships); + } + + /// A new request in its initial state, with the frozen Membership snapshot, filed by the caller's role. + private Result File(DataRequestCaller caller, UserId subject, DataRequestKind kind, + IReadOnlyList memberships) + { + var id = DataRequestRules.NewId(ids); + var now = clock.UtcNow; + return caller.Role == DataRequestRole.Subject + ? DataSubjectRequest.FileForSelf(DataSubjectRequestId.From(id), kind, subject, Group, memberships, now) + : DataSubjectRequest.FileForSubject(DataSubjectRequestId.From(id), kind, caller.Actor, subject, Group, memberships, now); + } + + /// + /// 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 Task> CreateExportForMembershipAsync(DataRequestCaller caller, Guid membershipId, + CancellationToken cancellationToken) => CreateForMembershipAsync(caller, membershipId, DataRequestKind.Export, cancellationToken); + + /// + /// An administrator files an erasure for the person whose in the announced group is + /// Revoked (ADR-0106 § 3). This is the erasure's own target authorization: the membership administration + /// authorization refuses a Revoked target, and the creation guard here refuses every other one, because a person who + /// still holds an Active or Suspended Membership of the group is a working member. + /// + public Task> CreateErasureForMembershipAsync(DataRequestCaller caller, Guid membershipId, + CancellationToken cancellationToken) => CreateForMembershipAsync(caller, membershipId, DataRequestKind.Erasure, cancellationToken); + + private async Task> CreateForMembershipAsync(DataRequestCaller caller, Guid membershipId, + DataRequestKind kind, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(caller); + if (caller.Role != DataRequestRole.Administrator) + { + return DataRequestRules.Fail("lockey_forbidden"); + } + + if (!DataRequestRules.ValidId(membershipId)) + { + return DataRequestRules.Fail("lockey_validation_failed"); + } + + var subject = await reader.FindMembershipSubjectAsync(MembershipId.From(membershipId), cancellationToken).ConfigureAwait(false); + return subject is { } person + ? await CreateAsync(caller, person, kind, cancellationToken).ConfigureAwait(false) + : DataRequestRules.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 DataRequestRules.Fail>("lockey_validation_failed"); + } + + if (cursor is not null) + { + if (!DataRequestCursorCodec.TryDecode(cursor, scope, out var anchor)) + { + return DataRequestRules.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 DataRequestRules.FindVisibleAsync(reader, caller, requestId, cancellationToken).ConfigureAwait(false); + if (request is null) + { + return DataRequestRules.Fail("lockey_not_found"); + } + + audit.Designate(request); + var view = (await ViewsAsync(caller, [DataRequestReceiptRow.From(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 DataRequestRules.FindVisibleAsync(reader, caller, requestId, cancellationToken).ConfigureAwait(false); + var current = await caller.RecheckAsync(cancellationToken).ConfigureAwait(false); + if (current.IsFailure) + { + return current; + } + + if (request is null || !DataRequestRules.Mutates(caller, request)) + { + return DataRequestRules.Fail("lockey_not_found"); + } + + audit.Designate(request); + 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, under the shared tenant fence the request guard requires (ADR-0106 § 8, + /// § 11). A running erasure holds the tenant fence exclusively, so a cancellation never meets one half-done; a + /// closure's Begin holds the fence of every tenant where the person holds a Membership, its originating tenant + /// included, so a cancellation either commits before the Begin or finds the closure fulfilling. + /// + public async Task> CancelAsync(DataRequestCaller caller, Guid requestId, long expectedVersion, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(caller); + if (!DataRequestRules.ValidId(requestId) || expectedVersion < 0) + { + return DataRequestRules.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 || !DataRequestRules.Mutates(caller, request)) + { + return DataRequestRules.Fail("lockey_not_found"); + } + + audit.Designate(request); + if (request.Version != expectedVersion) + { + return DataRequestRules.Fail("lockey_concurrency_conflict"); + } + + var cancelled = request.Cancel(clock.UtcNow, caller.Actor); + if (cancelled.IsFailure) + { + // Two closed reasons a person can act on: the window ended (the erasure runs now), or the request is no + // longer one a cancellation admits (it already ended, an export already started, or a closure's Begin + // committed). A scheduled closure is always cancellable, so it never reaches this refusal. + return DataRequestRules.Rule("$", + request.Status == DataRequestStatus.Scheduled && request.ExecuteAt is { } due && clock.UtcNow >= due + ? "lockey_data_request_window_ended" + : "lockey_data_request_not_cancellable"); + } + + locks.RequireCurrent(plan); + await store.SaveAsync(request, cancellationToken).ConfigureAwait(false); + return Result.Ok(new DataRequestMutationResult(request.Id.Value, request.Version)); + } + catch (IdentityMutationLockException) + { + return DataRequestRules.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 (!DataRequestRules.ValidId(requestId) || expectedArtifactVersion < 0) + { + return DataRequestRules.Fail("lockey_validation_failed"); + } + + var request = await DataRequestRules.FindVisibleAsync(reader, caller, requestId, cancellationToken).ConfigureAwait(false); + var found = request is not null && request.Kind == DataRequestKind.Export && DataRequestRules.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 DataRequestRules.Fail("lockey_not_found"); + } + + var artifact = found.Artifact; + audit.Designate(artifact); + if (artifact.Version != expectedArtifactVersion) + { + return DataRequestRules.Fail("lockey_concurrency_conflict"); + } + + if (!found.Readable) + { + return DataRequestRules.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)) + : DataRequestRules.Fail("lockey_not_found"); + } + + private async Task ViewsAsync(DataRequestCaller caller, DataRequestReceiptRow[] requests, + CancellationToken cancellationToken) + { + if (requests.Length == 0) + { + return []; + } + + // Only a stored requested export or scheduled erasure can be displayed failed + // (DataRequestFailureReconciler.EffectiveStatus): every other status is never changed by its job, so the job is + // not read. + var phase = new Dictionary(); + foreach (var kind in new[] { DataRequestKind.Export, DataRequestKind.Erasure }) + { + var pending = requests.Where(request => request.Kind == kind && DataRequestFailureReconciler.CanFail(kind, request.Status)) + .Select(request => request.Id).ToArray(); + if (pending.Length == 0) + { + continue; + } + + foreach (var (id, read) in await phases.ReadManyAsync(pending, kind, cancellationToken).ConfigureAwait(false)) + { + phase[id] = read; + } + } + + 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, DataRequestReceiptRow request, DataRequestJobPhase phase, + DataRequestArtifactRow? artifact) + { + var status = DataRequestFailureReconciler.EffectiveStatus(request.Kind, request.Status, 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, + DataRequestDocuments.ReadResult(request.ResultJson) + .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 + ? DataRequestDocuments.ReadMemberships(request.MembershipSnapshotJson + ?? throw new InvalidOperationException("An administrator's receipt reads its Membership snapshot.")) + .Select(member => member.Value).ToArray() + : null); + } +} 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 000000000..4da62e517 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/DataRequestValidators.cs @@ -0,0 +1,123 @@ +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 CreateDataErasureForSubjectValidator : AbstractValidator +{ + public CreateDataErasureForSubjectValidator() => + 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/IClosureGroupLifecycleReader.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/IClosureGroupLifecycleReader.cs new file mode 100644 index 000000000..4780e0c85 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/IClosureGroupLifecycleReader.cs @@ -0,0 +1,57 @@ +using LearnStack.Modules.Tenancy.Application.Contracts.IdentityLifecycle; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Tenancy; + +namespace LearnStack.Modules.Identity.Application.DataRequests; + +/// +/// What a participant group's tenant and organization allow, as the closure's operator acts judge it: the three facts of +/// Tenancy's lifecycle that decide whether the group is served. +/// +/// The tenant exists and is Trial or Active. +/// The group's organization belongs to the tenant; false for a tenant-wide group. +/// The group's organization is Active; false for a tenant-wide group. +public readonly record struct ClosureGroupLifecycle( + bool TenantAllowsOrdinaryWork, bool OrganizationBelongsToTenant, bool OrganizationAllowsOrdinaryWork); + +/// +/// The closure's read of each participant group's lifecycle on an entered platform scope (ADR-0107 § 7: through Tenancy's +/// own port, so no cross-module join exists). It is this module's own port over the Tenancy contract, because an +/// Infrastructure assembly names no other module's contract +/// (ModuleInfrastructure_References_Only_Its_Own_Layers_And_Core_Infrastructure); the Application layer may. +/// +public interface IClosureGroupLifecycleReader +{ + /// + /// The most groups one read answers: Tenancy's platform read bound. A closure reads at most + /// groups, which is within it. + /// + public const int MaximumGroups = IIdentityScopeLifecycleReader.MaximumPlatformScopes; + + /// + /// The lifecycle of each of , in their order, in one statement on the entered scope's own + /// transaction. It announces nothing and needs no announcement. + /// + /// The list is empty or longer than . + Task> ReadAsync( + IPlatformAdminScopeHandle handle, IReadOnlyList<(TenantId TenantId, OrganizationId? OrganizationId)> groups, + CancellationToken cancellationToken = default); +} + +/// The default reader: Tenancy's platform-scope lifecycle read, narrowed to the facts the closure judges. +public sealed class ClosureGroupLifecycleReader(IIdentityScopeLifecycleReader lifecycle) : IClosureGroupLifecycleReader +{ + /// + public async Task> ReadAsync( + IPlatformAdminScopeHandle handle, IReadOnlyList<(TenantId TenantId, OrganizationId? OrganizationId)> groups, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(handle); + ArgumentNullException.ThrowIfNull(groups); + var facts = await lifecycle.ReadOnPlatformScopeAsync( + handle, [.. groups.Select(group => new IdentityLifecycleScope(group.TenantId, group.OrganizationId))], + cancellationToken); + return [.. facts.Select(fact => new ClosureGroupLifecycle( + fact.TenantAllowsOrdinaryWork, fact.OrganizationBelongsToTenant, fact.OrganizationAllowsOrdinaryWork))]; + } +} 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 000000000..b26071ef7 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/IDataRequestStore.cs @@ -0,0 +1,236 @@ +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; + +/// +/// The data request rows of the ambient group, read and written on the ambient tenant transaction as +/// 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 : IAggregateWriteStore +{ + /// The executing data-request job: refuses a caller that is not one of the module's export or erasure job roots. + BackgroundJobId RequireCurrentJob(); + + /// The request in the ambient group, locked for update; when absent. + Task FindLockedAsync(DataSubjectRequestId requestId, CancellationToken cancellationToken); + + /// The subject's artifacts in the ambient group that are still stored available. + Task> FindAvailableArtifactsAsync(UserId subject, CancellationToken cancellationToken); + + /// + /// Whether the subject holds a readable artifact in the ambient group, of any origin: stored available and + /// before its expiry by the database clock (ADR-0107 § 4). + /// + Task HoldsReadableArtifactAsync(UserId subject, CancellationToken cancellationToken); + + /// 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); + + /// + /// Whether the subject holds an Active or Suspended Membership in the ambient group: the current row an administrator's + /// erasure is refused for (ADR-0106 § 3). Read under the subject's User fence, which every admission also takes. + /// + Task HoldsCurrentMembershipAsync(UserId subject, CancellationToken cancellationToken); + + /// + /// Whether the subject is the tenant's only eligible tenant-wide administrator (ADR-0106 § 7, ADR-0107 § 7): they hold + /// an Active, undeleted, tenant-wide Membership with a tenant administrator Role that keeps every kernel grant, and no + /// other person does. The same predicate the deferred complete-graph guard enforces at commit. + /// + /// + /// The guard also requires the administrator's User to be Active, which the application role cannot read for another + /// person (the users policy admits only the session's own subject); no path moves a User out of Active before + /// P03-10 Step 3's closure, which owns extending this read. + /// + Task IsSoleEligibleTenantAdministratorAsync(UserId subject, CancellationToken cancellationToken); + + /// + /// Whether this transaction holds the subject's User fence and the ambient tenant's fence, both exclusively, as the + /// database sees them: the canonical fences an erasure runs under (ADR-0107 § 5). + /// + Task HoldsErasureFencesAsync(UserId subject, CancellationToken cancellationToken); + + /// + /// Whether the subject holds, in the ambient group, a closure's fan-out erasure that is completed. Only that + /// closure's Finalize completes one, in the transaction that moves the person to Closed, so its presence says the group's + /// part of the closure is done (ADR-0107 § 7). + /// + Task HoldsCompletedFanOutAsync(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. Any answer but leaves the + /// transaction rollback-only with nothing stored: the one-active partial unique index refused it (ADR-0106 § 7), or the + /// request guard refused its subject because the person's User is not in the one status the request's origin allows + /// (ADR-0107 § 7). + /// + Task TryAddAsync(DataSubjectRequest request, CancellationToken cancellationToken); + + /// + Task IAggregateWriteStore.UpdateAsync(DataSubjectRequest aggregate, + CancellationToken cancellationToken) => SaveAsync(aggregate, cancellationToken); +} + +/// How the insertion of a new request ended; every refusal stored nothing. +public enum DataRequestInsertion +{ + /// The request is stored. + Added = 1, + + /// A request of the kind is already active for the subject in the group (ADR-0106 § 7). + AlreadyActive = 2, + + /// + /// The request guard refused the subject, judged under the subject's User fence: Closing for a closure's fan-out + /// erasure, Active for every other request (ADR-0107 § 7). A filing admitted while the person was Active meets it when + /// a closure's Begin or Finalize committed first, and an administrator's when the person's account is closing. + /// + SubjectNotAdmitted = 3, +} + +/// +/// 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); + + /// + /// The artifact's tickets in one statement: those of that are neither + /// consumed nor past their expiry by the database clock, and every ticket ever minted over it. The caller holds + /// the artifact's row lock, so concurrent mints are counted one after the other. + /// + Task CountAsync(DataExportArtifactId artifactId, string sessionBindingDigest, CancellationToken cancellationToken); +} + +/// An artifact's tickets: those open in one session binding, and all ever minted. +public sealed record DataExportTicketCounts(int OpenInBinding, int Minted); + +/// +/// 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). + /// + /// + /// A page reads only the columns its receipt shows: never the progress document, and the Membership snapshot only + /// for the administrator's page (no ), the one view that displays it. + /// + 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); + +/// +/// The columns a request's receipt shows, read without the aggregate: a page projects these and nothing more. +/// is when the read did not select it (the subject's own +/// pages, which never display it). +/// +public sealed record DataRequestReceiptRow(DataSubjectRequestId Id, DataRequestKind Kind, DataRequestOrigin Origin, + DataRequestStatus Status, UserId SubjectUserId, UserId? RequesterUserId, DateTimeOffset CreatedAt, DateTimeOffset? UpdatedAt, + DateTimeOffset? CompletedAt, DateTimeOffset? ExecuteAt, DataRequestRefusal? LastRefusal, DataRequestFailureReason? FailureReason, + string ResultJson, string? MembershipSnapshotJson, long Version) +{ + /// The receipt columns of a loaded request, its snapshot included. + public static DataRequestReceiptRow From(DataSubjectRequest request) + { + ArgumentNullException.ThrowIfNull(request); + return new(request.Id, request.Kind, request.Origin, request.Status, request.SubjectUserId, request.RequesterUserId, + request.CreatedAt, request.UpdatedAt, request.CompletedAt, request.ExecuteAt, request.LastRefusal, request.FailureReason, + request.ResultJson, request.MembershipSnapshotJson, request.Version); + } + + public override string ToString() => nameof(DataRequestReceiptRow); +} + +/// +/// 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. +/// +/// +/// 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 +{ + /// 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 requests of one kind in one statement; a request with no job, or of a kind with no + /// fulfilment job, is . + /// + Task> ReadManyAsync(IReadOnlyCollection requestIds, + DataRequestKind kind, 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 000000000..86d4a51cb --- /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/DataRequests/RetainedDataRequestHandlers.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/RetainedDataRequestHandlers.cs new file mode 100644 index 000000000..ec5a97d33 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/RetainedDataRequestHandlers.cs @@ -0,0 +1,222 @@ +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 and a person whose Membership was revoked are served alike; the +// cores still confine every row to the announced group and to the subject. A group the definer proved only by a +// request, with no Membership of any status, would be readable but answer not_found on create (the creation core +// needs a Membership for the snapshot); that case is unreachable today because Memberships are never deleted, only +// Revoked, so every group with a request also holds the subject's Membership tombstone. + +/// +/// 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 CreateRetainedDataErasureCommand or CreateRetainedAccountClosureCommand or CancelRetainedDataRequestCommand + or RevokeRetainedDataExportCommand 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 DataRequestRules.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) : DataRequestRules.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, KeyedPurposes) is { Group: { } group } + ? Admit(request, group.OrganizationId, KeyedPurposes) + : DataRequestRules.Fail("lockey_forbidden"); + + /// The retained entry's keyed purposes, whose replay reads the original request's receipt. + private static readonly OwnDataRequestPurpose[] KeyedPurposes = + [OwnDataRequestPurpose.Create, OwnDataRequestPurpose.Cancel, OwnDataRequestPurpose.Revoke]; +} + +/// 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(DataRequestRules.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(DataRequestRules.Fail("lockey_forbidden")); + var items = page.Items.ToArray(); + if (!ReferenceEquals(admission.For(request, OwnDataRequestPurpose.List), witness)) + return Task.FromResult(DataRequestRules.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 DataRequestRules.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 CreateRetainedDataErasureCommandHandler(RetainedDataRequestAdmission admission, DataRequestService service) + : IRequestHandler> +{ + public async Task> Handle(CreateRetainedDataErasureCommand request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + var caller = admission.Admit(request, request.OrganizationId, OwnDataRequestPurpose.Create); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.CreateErasureAsync(caller.Value, caller.Value.Actor, cancellationToken).ConfigureAwait(false); + } +} + +/// +/// ADR-0107 § 7: the subject files the closure of their account from one retained group, the path of a Suspended person +/// and of one whose Membership was revoked. +/// +public sealed class CreateRetainedAccountClosureCommandHandler(RetainedDataRequestAdmission admission, DataRequestService service) + : IRequestHandler> +{ + public async Task> Handle(CreateRetainedAccountClosureCommand request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + var caller = admission.Admit(request, request.OrganizationId, OwnDataRequestPurpose.Create); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.CreateClosureAsync(caller.Value, caller.Value.Actor, cancellationToken).ConfigureAwait(false); + } +} + +/// +/// ADR-0107 § 4: the subject revokes an artifact of their own request through the retained path as through a live +/// session; a person whose Membership is Suspended or gone is not left holding a readable artifact they cannot withdraw. +/// +public sealed class RevokeRetainedDataExportCommandHandler(RetainedDataRequestAdmission admission, DataRequestService service) + : IRequestHandler> +{ + public async Task> Handle(RevokeRetainedDataExportCommand request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + var caller = admission.Admit(request, request.OrganizationId, OwnDataRequestPurpose.Revoke); + return caller.IsFailure ? Result.Fail(caller.Error) + : await service.RevokeAsync(caller.Value, request.RequestId, request.ExpectedArtifactVersion, 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 2051c3594..052af6d12 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/IdentityOperationPolicySource.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/IdentityOperationPolicySource.cs @@ -6,8 +6,10 @@ 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; using LearnStack.SharedKernel.Permissions; namespace LearnStack.Modules.Identity.Application; @@ -40,6 +42,38 @@ 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 OwnDataErasureCreateOperation = "identity.data_request.create_own_erasure"; + public const string OwnAccountClosureCreateOperation = "identity.data_request.create_own_closure"; + 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 DataErasureCreateOperation = "identity.data_request.create_erasure"; + 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"; + // 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 RetainedDataErasureCreateOperation = "identity.data_request.create_retained_erasure"; + public const string RetainedAccountClosureCreateOperation = "identity.data_request.create_retained_closure"; + public const string RetainedDataExportRevokeOperation = "identity.data_request.revoke_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"); @@ -60,6 +94,39 @@ 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.ForTrusted("identity.data_request.fulfill_tenant_erasure", AuthorizationSourceKind.BackgroundJob), + OperationPolicy.ForTrusted("identity.data_request.fulfill_organization_erasure", AuthorizationSourceKind.BackgroundJob), + OperationPolicy.ForOwnDataRequest(OwnDataExportCreateOperation), + OperationPolicy.ForOwnDataRequest(OwnDataErasureCreateOperation), + OperationPolicy.ForOwnDataRequest(OwnAccountClosureCreateOperation), + OperationPolicy.ForOwnDataRequest(OwnDataRequestListOperation), + OperationPolicy.ForOwnDataRequest(OwnDataRequestReadOperation), + OperationPolicy.ForOwnDataRequest(OwnDataRequestCancelOperation), + OperationPolicy.ForOwnDataRequest(OwnDataExportRevokeOperation), + OperationPolicy.ForOwnDataRequest(OwnDataExportTicketOperation), + OperationPolicy.ForOwnDataRequest(OwnDataExportChunkOperation), + OperationPolicy.ForOwnDataRequest(OwnDataRequestReceiptOperation), + OperationPolicy.ForOwnDataRequestEntry(RetainedDataRequestScopesOperation), + OperationPolicy.ForOwnDataRequestEntry(RetainedDataRequestListOperation), + OperationPolicy.ForOwnDataRequestEntry(RetainedDataExportCreateOperation), + OperationPolicy.ForOwnDataRequestEntry(RetainedDataErasureCreateOperation), + OperationPolicy.ForOwnDataRequestEntry(RetainedAccountClosureCreateOperation), + OperationPolicy.ForOwnDataRequestEntry(RetainedDataExportRevokeOperation), + OperationPolicy.ForOwnDataRequestEntry(RetainedDataRequestCancelOperation), + OperationPolicy.ForOwnDataRequestEntry(RetainedDataExportTicketOperation), + OperationPolicy.ForOwnDataRequestEntry(RetainedDataExportChunkOperation), + OperationPolicy.ForOwnDataRequestEntry(RetainedDataRequestReceiptOperation), + OperationPolicy.ForProtected(DataExportCreateOperation, [new([MembershipAdministration]), new([OrganizationMembershipAdministration])]), + OperationPolicy.ForProtected(DataErasureCreateOperation, [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])]), @@ -128,6 +195,8 @@ public sealed class IdentityOperationPolicySource : IOperationPolicySource OperationPolicy.ForTrusted("identity.operator.initialize_role", AuthorizationSourceKind.PlatformOperator), OperationPolicy.ForTrusted("identity.operator.create_first_admin", AuthorizationSourceKind.PlatformOperator), OperationPolicy.ForTrusted("identity.operator.recover_admin", AuthorizationSourceKind.PlatformOperator), + // ADR-0107 § 7: a closure's per-group fan-out, admitted per group by the operator's grant and nothing else. + OperationPolicy.ForTrusted("identity.operator.fan_out_closure", AuthorizationSourceKind.PlatformOperator), ]; private static OperationPolicy Federation(string id) => diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Invitations/IInvitationAdministrationStore.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Invitations/IInvitationAdministrationStore.cs index d98b5c09d..bf3909ca3 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Invitations/IInvitationAdministrationStore.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Invitations/IInvitationAdministrationStore.cs @@ -1,4 +1,5 @@ using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Identifiers; using LearnStack.SharedKernel.Persistence; namespace LearnStack.Modules.Identity.Application.Invitations; @@ -9,4 +10,11 @@ public interface IInvitationAdministrationStore : IAggregateWriteStore FindLockedAsync(InvitationId id, CancellationToken cancellationToken); Task> ListAsync(InvitationId? after, int take, CancellationToken cancellationToken); Task> ReadRolesAsync(CancellationToken cancellationToken); + + /// + /// At most pending invitations issued in the ambient group, oldest + /// identifier first, locked and tracked: the offers a tenant erasure revokes (ADR-0107 § 5). A fresh read, as + /// is. + /// + Task> FindPendingIssuedLockedAsync(UserId inviter, int take, CancellationToken cancellationToken); } diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/OperatorActs/FanOutClosureCommandHandler.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/OperatorActs/FanOutClosureCommandHandler.cs new file mode 100644 index 000000000..3fce41781 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/OperatorActs/FanOutClosureCommandHandler.cs @@ -0,0 +1,203 @@ +using LearnStack.Modules.Identity.Application.Contracts.OperatorActs; +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.Modules.Identity.Application.Seeding; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Tenancy.Application.Contracts.IdentityLifecycle; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using MediatR; + +namespace LearnStack.Modules.Identity.Application.OperatorActs; + +/// +/// One participant group's half of a closure (fan_out_closure, ADR-0107 § 7): in the group's own announced +/// transaction, under the closing person's exclusive User fence and the group tenant's shared fence, it creates the +/// person's fan-out erasure and enqueues its job, or adopts the erasure the group already has. +/// +/// +/// +/// What the group holds decides. The active erasure of the person in the group is read under the fences, after a +/// dead job's request has been stored failed the way every creation path stores it (ADR-0106 § 8): +/// +/// +/// none, and a completed fan-out erasure of the person: the group's part of the closure is done, because only +/// the closure's Finalize completes one, in the transaction that moves the person to Closed. A repeated Begin that reaches +/// the group after that adopts it with nothing written and nothing designated, so its row names no one +/// (); +/// none otherwise, or only terminal ones: a fan-out erasure is created, fulfilling, with no window, the system actor's, +/// and its job is enqueued on the same transaction (); +/// a fan-out still fulfilling: adopted, and its job enqueued again unless one is still in flight, so a job that +/// died is retried by repeating Begin (); +/// any erasure awaiting the operator's privileged step: adopted as it is (); +/// the person's or an administrator's erasure still in its window: cancelled by the system actor, then replaced by +/// the fan-out in the same transaction, the cancellation saved first so the one-active index sees it +/// (); +/// such an erasure past its window: its own job runs it, so the group waits for a repeated Begin +/// (). +/// +/// +/// The database is the witness. The request guard admits the fan-out's birth in fulfilling only for a subject +/// whose User is Closing, read under the User fence this act holds; a refused insertion rolls the whole group back, the +/// cancellation of an erasure it replaced included. The frozen snapshot is every Membership the person holds in the group, +/// of any status, which the guard also demands. +/// +/// +/// Refusals are the group's failure. A group whose tenant or organization no longer allows ordinary work, a +/// person not Closing, a lock that cannot be taken in time and a lost race each return a failure result, which the +/// fan-out reports as a failed group and a repeated Begin retries. One MUST row names the created or adopted request; an +/// erasure the fan-out cancelled travels in that row's changes. +/// +/// +internal sealed class FanOutClosureCommandHandler( + IDataRequestStore store, + IDataRequestJobPhaseReader phases, + DataRequestFailureReconciler reconciler, + IDataRequestFulfillmentScheduler scheduler, + IIdentityScopeLifecycleReader lifecycle, + ITenantContext context, + IAuditSubject audit, + OperatorActGuard guard, + IGuidFactory ids, + IClock clock) : IRequestHandler> +{ + public async Task> Handle(FanOutClosureCommand request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + + // The group is the context the executor built for this act: its tenant, and exactly the organization the command + // names, so an act sent into another group's context refuses before it reads anything. + if (!context.IsResolved || context.OrganizationId != request.OrganizationId || !SeedFoundationGate.ValidUser(request.SubjectUserId)) + return DataRequestRules.Rule("$", "lockey_validation_failed"); + if (!await SeedFoundationGate.AllowsCurrentLifecycleAsync(context, lifecycle, cancellationToken).ConfigureAwait(false)) + return DataRequestRules.Fail("lockey_not_found"); + + // ADR-0107 § 7: the person's exclusive User fence, which the request guard requires for the insertion, then the + // group tenant's fence, shared as every creation takes it; a running erasure holds it exclusively. + var subject = request.SubjectUserId; + var plan = new IdentityMutationLockPlan([subject], context.TenantId, IdentityTenantLockMode.Shared); + var admission = await guard.AdmitAsync(request, plan, cancellationToken).ConfigureAwait(false); + if (admission.IsFailure) + return Result.Fail(admission.Error); + try + { + if (!await SeedFoundationGate.AllowsCurrentLifecycleAsync(context, lifecycle, cancellationToken).ConfigureAwait(false)) + return DataRequestRules.Fail("lockey_not_found"); + + var active = await store.FindActiveLockedAsync(subject, DataRequestKind.Erasure, cancellationToken).ConfigureAwait(false); + if (active is not null && await reconciler.ReconcileAsync(active, plan, cancellationToken).ConfigureAwait(false)) + { + // A person's erasure whose job died past its window is now stored failed, which frees the group's slot. + active = null; + } + + if (active is null && await store.HoldsCompletedFanOutAsync(subject, cancellationToken).ConfigureAwait(false)) + { + // Finalize completed this group's fan-out and closed the person: a Begin repeated across that commit finds + // the group done. Nothing is designated, so the act's row names neither the person nor a request. + guard.MarkReplayed(); + return Result.Ok(ClosureGroupOutcome.Adopted); + } + + switch (active) + { + case null: + return await StartAsync(request, admission.Value, null, cancellationToken).ConfigureAwait(false); + case { Status: DataRequestStatus.AwaitingPrivilegedStep }: + audit.Designate(active); + guard.MarkReplayed(); + return Result.Ok(ClosureGroupOutcome.Adopted); + case { Origin: DataRequestOrigin.ClosureFanout, Status: DataRequestStatus.Fulfilling }: + return await ResumeAsync(active, admission.Value, cancellationToken).ConfigureAwait(false); + case { Origin: not DataRequestOrigin.ClosureFanout, Status: DataRequestStatus.Scheduled, ExecuteAt: { } due } + when DataRequestTransitionTime.Of(clock, active) < due: + return await StartAsync(request, admission.Value, active, cancellationToken).ConfigureAwait(false); + default: + // A person's or an administrator's erasure that its own job runs now: once it awaits its privileged step, + // a repeated Begin adopts it. + audit.Designate(active); + guard.MarkReplayed(); + return Result.Ok(ClosureGroupOutcome.Waiting); + } + } + catch (IdentityMutationLockException) + { + return DataRequestRules.Fail("lockey_dependency_unavailable"); + } + } + + /// + /// Creates the group's fan-out erasure and enqueues its job, after cancelling when the group + /// held a person's or an administrator's erasure still in its window. + /// + private async Task> StartAsync(FanOutClosureCommand request, OperatorActAdmission admission, + DataSubjectRequest? replaced, CancellationToken cancellationToken) + { + var subject = request.SubjectUserId; + var memberships = await store.ReadSubjectMembershipsAsync(subject, cancellationToken).ConfigureAwait(false); + if (memberships.Count == 0) + return DataRequestRules.Fail("lockey_not_found"); + if (memberships.Count > DataRequestLimits.MaximumSnapshotMemberships) + return DataRequestRules.Rule("$", "lockey_snapshot_too_large"); + + var created = DataSubjectRequest.FanOutErasure(DataSubjectRequestId.From(DataRequestRules.NewId(ids)), subject, + new DataRequestScopeGroup(context.TenantId, context.OrganizationId), memberships, clock.UtcNow); + if (created.IsFailure) + return Result.Fail(created.Error); + var fanOut = created.Value; + audit.Designate(fanOut); + + if (replaced is not null) + { + // The system actor cancels the erasure the closure supersedes; it is saved before the insertion so the one-active + // index frees the group's slot first (ADR-0107 § 7). + if (replaced.Cancel(DataRequestTransitionTime.Of(clock, replaced), UserId.SystemActor).IsFailure) + return DataRequestRules.Rule("$", "lockey_data_request_not_cancellable"); + if (guard.RequireCurrent(admission) is { IsFailure: true } lost) + return Result.Fail(lost.Error); + await store.SaveAsync(replaced, cancellationToken).ConfigureAwait(false); + } + + if (guard.RequireCurrent(admission) is { IsFailure: true } changed) + return Result.Fail(changed.Error); + var insertion = await store.TryAddAsync(fanOut, cancellationToken).ConfigureAwait(false); + if (insertion != DataRequestInsertion.Added) + { + return insertion == DataRequestInsertion.SubjectNotAdmitted + ? DataRequestRules.Rule("$", "lockey_subject_not_admitted") + : DataRequestRules.AlreadyActive(); + } + + await scheduler.SubmitAsync(Fulfillment(fanOut), cancellationToken).ConfigureAwait(false); + return Result.Ok(ClosureGroupOutcome.Started); + } + + /// + /// Adopts the group's fan-out erasure that is still fulfilling, and enqueues its job again unless one is still + /// queued, running or retrying: a job that died is how a group's erasure stays fulfilling. + /// + private async Task> ResumeAsync(DataSubjectRequest fanOut, OperatorActAdmission admission, + CancellationToken cancellationToken) + { + audit.Designate(fanOut); + if (await phases.ReadAsync(fanOut.Id, DataRequestKind.Erasure, cancellationToken).ConfigureAwait(false) == DataRequestJobPhase.Pending) + { + guard.MarkReplayed(); + return Result.Ok(ClosureGroupOutcome.Adopted); + } + + if (guard.RequireCurrent(admission) is { IsFailure: true } changed) + return Result.Fail(changed.Error); + await scheduler.SubmitAsync(Fulfillment(fanOut), cancellationToken).ConfigureAwait(false); + return Result.Ok(ClosureGroupOutcome.Adopted); + } + + private static DataRequestFulfillment Fulfillment(DataSubjectRequest request) => + new(request.Id.Value, request.Kind, request.Status, request.Group, request.ExecuteAt, request.Origin); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataErasureWitness.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataErasureWitness.cs new file mode 100644 index 000000000..4b719791f --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataErasureWitness.cs @@ -0,0 +1,80 @@ +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.Modules.Identity.Domain; + +/// +/// The erasure witness of +/// ADR-0107 § 5: +/// one subject's data in one scope group may be erased because that subject's erasure request for that group +/// is fulfilling. The erasure operations of and run only +/// under it, and they leave every ordinary method's rules as they are. +/// +/// +/// +/// Privately constructed. Only a captures one, from the fulfilling erasure request +/// itself, and the architecture census pins its one production deriver, so no other caller holds the authority the +/// erasure operations require. +/// +/// +/// Live only with its evidence. A witness answers only while its source still holds what +/// it was minted from; a witness kept past the erasure that minted it erases nothing. +/// +/// +public sealed class DataErasureWitness +{ + private readonly MintingSource _source; + + private DataErasureWitness(MintingSource source, DataSubjectRequest request) + { + _source = source; + RequestId = request.Id; + SubjectUserId = request.SubjectUserId; + TenantId = request.TenantId; + OrganizationId = request.OrganizationId; + } + + /// The fulfilling erasure request the witness was minted from. + public DataSubjectRequestId RequestId { get; } + + /// The person whose data the witness lets the erasure operations change. + public UserId SubjectUserId { get; } + + public TenantId TenantId { get; } + + /// The group's organization, or for the tenant-wide group. + public OrganizationId? OrganizationId { get; } + + public bool IsActive => _source.IsCurrent; + + /// Whether the witness is live and covers a row of exactly this tenant, group and person. + internal bool Covers(TenantId tenant, OrganizationId? organization, UserId person) => + IsActive && TenantId == tenant && OrganizationId == organization && SubjectUserId == person; + + public override string ToString() => nameof(DataErasureWitness); + +#pragma warning disable CA1034 // A closed source census owns the sole production minter. + /// The only way to capture a witness: from an erasure request that is fulfilling. + public abstract class MintingSource +#pragma warning restore CA1034 + { + internal bool IsCurrent => IsEvidenceCurrent; + + /// Whether the evidence the witness was minted from still holds. + protected abstract bool IsEvidenceCurrent { get; } + + /// + /// The request is not a fulfilling erasure: a programming error, because the source decides that before it captures. + /// + protected DataErasureWitness Capture(DataSubjectRequest request) + { + ArgumentNullException.ThrowIfNull(request); + if (request.Kind != DataRequestKind.Erasure || request.Status != DataRequestStatus.Fulfilling || request.IsDeleted) + { + throw new InvalidOperationException("An erasure witness is captured only from a fulfilling erasure request."); + } + + return new DataErasureWitness(this, request); + } + } +} 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 000000000..797e2aeb8 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataExportArtifact.cs @@ -0,0 +1,148 @@ +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; + +/// +/// 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; } + + /// + /// 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) => + 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); + 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 + || 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, + TruncationJson = truncation, + 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. + /// + /// No Step 1 path calls it: expiry is a time check (), receipts display expired + /// without a write, and the purge job moves an expired artifact straight to purged. It is kept because the + /// stored lifecycle of ADR-0107 § 4 and the artifact guard admit the arrow, so the aggregate and the database stay + /// one machine; the operator inspection of P03-10 Step 2 (ADR-0107 § 8, the expired artifacts not yet purged) is + /// the first caller that may record an observed expiry, and Phase 11's retention owns the rest. + /// + 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 000000000..779e2d9cc --- /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 000000000..9e2d1fc39 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataRequestDocuments.cs @@ -0,0 +1,225 @@ +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(); + } + } + + /// + /// 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.Domain/DataSubjectRequest.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/DataSubjectRequest.cs new file mode 100644 index 000000000..6a1602922 --- /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 27a695d3a..b1e4dd879 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 36680822e..0ad8e189b 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.Domain/Invitation.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/Invitation.cs index e09470ff2..059271ed4 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/Invitation.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/Invitation.cs @@ -113,6 +113,17 @@ public Result Revoke(DateTimeOffset at, UserId actor) return Result.Ok(None.Value); } + /// + /// ADR-0107 § 5: revokes a pending offer the erasure's subject issued in its group. The subject is the aggregate actor, + /// because this aggregate refuses the system actor; the erasure job remains the audit actor. Idempotent: an offer no + /// longer pending changes nothing, and an accepted one stays the record of the authority it granted. + /// + public Result RevokeForErasure(DataErasureWitness witness, DateTimeOffset at) + { + if (witness is null || !witness.Covers(TenantId, OrganizationId, InviterUserId)) return IdentityFailures.BusinessRule(); + return Status == InvitationStatus.Pending ? Revoke(at, witness.SubjectUserId) : Result.Ok(None.Value); + } + /// Caller proves fresh provider/delegation/locks; this method enforces the actual result graph. public Result Accept(Membership membership, InvitationAcceptanceDisposition disposition, string digest, DateTimeOffset databaseNow, UserId actor) diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/Membership.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/Membership.cs index 860360631..e2459cead 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/Membership.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/Membership.cs @@ -123,6 +123,68 @@ public Result Revoke(DateTimeOffset at, UserId actor) Status = MembershipStatus.Revoked; return Result.Ok(None.Value); } + + /// + /// Whether nothing is left for an erasure to change: the Membership is the Revoked tombstone, holds no role + /// assignment and its profile is cleared (ADR-0107 § 5, § 6). + /// + public bool IsErased => Status == MembershipStatus.Revoked && _roleAssignments.Count == 0 && Profile.IsCleared; + + /// + /// ADR-0107 § 5: deletes every role assignment, of a Membership of any status, under the erasure witness. Idempotent: + /// a Membership with no assignment changes nothing. + /// + public Result RemoveAssignmentsForErasure(DataErasureWitness witness, DateTimeOffset at, UserId actor) + { + if (!Erasable(witness)) return IdentityFailures.BusinessRule(); + if (_roleAssignments.Count == 0) return Result.Ok(None.Value); + StampErasure(at, actor); + _roleAssignments.Clear(); + return Result.Ok(None.Value); + } + + /// + /// ADR-0107 § 5: clears the display name and locale to and the custom values to [], of a + /// Membership of any status, under the erasure witness. Idempotent: a cleared profile changes nothing. + /// + public Result ClearProfileForErasure(DataErasureWitness witness, DateTimeOffset at, UserId actor) + { + if (!Erasable(witness)) return IdentityFailures.BusinessRule(); + if (Profile.IsCleared) return Result.Ok(None.Value); + StampErasure(at, actor); + Profile.Clear(); + return Result.Ok(None.Value); + } + + /// + /// ADR-0107 § 5: an Active or Suspended Membership becomes the Revoked tombstone that keeps its , + /// under the erasure witness. Idempotent: a Revoked one changes nothing, so its row, which admits no UPDATE, is never + /// written. + /// + public Result RevokeForErasure(DataErasureWitness witness, DateTimeOffset at, UserId actor) + { + if (!Erasable(witness)) return IdentityFailures.BusinessRule(); + if (Status == MembershipStatus.Revoked) return Result.Ok(None.Value); + SoftDelete(at, actor); + Status = MembershipStatus.Revoked; + return Result.Ok(None.Value); + } + + /// + /// The witness covers this Membership's tenant, group and person, and the stored lifecycle is coherent: deleted + /// exactly when Revoked, as ck_memberships_lifecycle requires. + /// + private bool Erasable(DataErasureWitness? witness) => witness is not null && witness.Covers(TenantId, OrganizationId, UserId) + && IsDeleted == (Status == MembershipStatus.Revoked); + + /// + /// The root is stamped as every ordinary change stamps it, except a Revoked tombstone's: the contextual guard admits no + /// UPDATE of a Revoked row, so its contained rows change alone and the change is recorded in the erasure's audit row. + /// + private void StampErasure(DateTimeOffset at, UserId actor) + { + if (Status != MembershipStatus.Revoked) MarkUpdated(at, actor); + } } [TenantOwned] @@ -163,6 +225,19 @@ internal void Set(string? displayName, string? preferredLocale) } internal void SetCustomFields(string json) => CustomFieldsJson = json; + + /// The three personal columns hold nothing: the state ADR-0107 § 5's clearing leaves. + public bool IsCleared => DisplayName is null && PreferredLocale is null && CustomFieldsJson == EmptyCustomFields; + + /// The clearing the contextual guard admits on a Membership of any status under the erasure witness. + internal void Clear() + { + DisplayName = null; + PreferredLocale = null; + CustomFieldsJson = EmptyCustomFields; + } + + private const string EmptyCustomFields = "[]"; } [TenantOwned] 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 197736abb..ddd9b4d88 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/Bindings/IdentityFoundationRegistration.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityFoundationRegistration.cs index d431a42e3..45b941a95 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,13 @@ 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.Modules.Identity.Application.Contracts.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; @@ -62,15 +68,60 @@ public static IServiceCollection AddIdentityContextualFoundation(this IServiceCo // The operator's port (Amendment 10) is its own: the tenant runner never holds it, and it too fails closed. services.TryAddSingleton(); services.TryAddSingleton(); + services.TryAddSingleton(); services.AddSingleton(new ExplicitReadOnlyRequest(typeof(GetFederationConnectionQuery))); services.AddSingleton(new ExplicitReadOnlyRequest(typeof(GetOwnMembershipProfileQuery))); 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; } + /// + /// ADR-0107 § 1–§ 5: the request store, the default artifact store, the export, purge and erasure job roots, the + /// fulfilment scheduler, the failure reconciler, the erasure service 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.TryAddSingleton(); + 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()); + // ADR-0107 § 5: the erasure job's two roots, and the Identity participant's erasure it runs. + services.TryAddScoped(); + services.TryAddScoped>>(provider => provider.GetRequiredService()); + services.TryAddScoped>>(provider => provider.GetRequiredService()); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + // 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(); + services.TryAddScoped(); + } + /// 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/AccountClosureOperatorOperations.Begin.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/AccountClosureOperatorOperations.Begin.cs new file mode 100644 index 000000000..23ed6f4b3 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/AccountClosureOperatorOperations.Begin.cs @@ -0,0 +1,420 @@ +using System.Globalization; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; + +namespace LearnStack.Modules.Identity.Infrastructure.DataRequests; + +/// The closure's Begin (ADR-0107 § 7, begin_closure). +/// +/// +/// One transaction, then the fan-out. The request is read to find the person, with the raw provider subject the +/// identity provider's port is asked about; the person's User fence is taken, the participant groups and their Membership +/// counts are read under it and every participant tenant's fence is taken, ascending; the request is locked and read again +/// with the User's status; the closure is judged; and either the refusal is recorded or the User moves Active to Closing +/// and the request scheduled to fulfilling. The result row names the platform sentinel tenant and commits +/// with it. The fences end with that transaction, which is the nonadmitting transition they order, and only then is the +/// closure fanned out to the served groups, each in its own transaction. +/// +/// +/// What could never finish is refused first. A closure whose account the port could never delete +/// () and a person past the closure's bounds +/// () are refused before any write and before the person leaves Active: +/// no refusal code is recorded on the request, because neither is the person's to act on, and the scope ends by disposal +/// with its entry row the record. A person past the bounds takes no tenant fence. +/// +/// +/// Judging. blocked_window by the database clock, which the request guard asks again; blocked_hold +/// from the hold source for the closure; blocked_last_administrator when the person is the only eligible tenant-wide +/// administrator of a participant tenant that allows ordinary work. The last rule protects the transition from Active: a +/// person already Closing for another closure is no eligible administrator anywhere, so that closure's Begin judged it. +/// +/// +/// Resuming. A closure already fulfilling is not judged and not fenced: its User is Closing, which no +/// Membership is admitted for, so its participants cannot change. Its scope reads them and their lifecycle, changes nothing +/// and ends by disposal, its entry row the record, and the fan-out runs again and adopts what an earlier call started. +/// +/// +public sealed partial class AccountClosureOperatorOperations +{ + /// + /// For each tenant of @tenants, whether the person and whether anybody else is an eligible tenant-wide + /// administrator: the administrator predicate of the deferred complete-graph guard (fn_identity_complete_graph_guard + /// with fn_identity_admin_admission_state), which the application role's DataRequestStore reads less the + /// User status. On the platform connection the User status is readable, so an administrator whose User is Closing or + /// Closed is not eligible here either; the Membership's deleter column is not read, because + /// ck_memberships_lifecycle makes it NULL beside an Active status, and the User's deletion columns are not read, + /// because ck_users_no_soft_delete makes them NULL always. A tenant with no eligible administrator has no row. + /// It is exposed so that a test can run it over the same fixtures as the guard. + /// + public static string AdministratorStandingSql { get; } = $""" + SELECT member.tenant_id, bool_or(member.user_id = @subject), bool_or(member.user_id <> @subject) + FROM public.memberships AS member + JOIN public.membership_role_assignments AS assignment + ON assignment.tenant_id = member.tenant_id AND assignment.membership_id = member.id + JOIN public.roles AS role ON role.tenant_id = assignment.tenant_id AND role.id = assignment.role_id + JOIN public.users AS person ON person.id = member.user_id + WHERE member.tenant_id = ANY(@tenants) AND member.organization_id IS NULL + AND member.status = 'Active' AND member.deleted_at IS NULL + AND role.built_in_key = 'TenantAdmin' AND role.permission_scope = 'Tenant' + AND role.deleted_at IS NULL AND role.deleted_by IS NULL + AND NOT EXISTS (SELECT 1 FROM (VALUES {IdentityFoundationManifest.Version1.KernelSqlValues}) AS kernel(scope,permission_key) + WHERE NOT EXISTS (SELECT 1 FROM public.role_permission_grants AS grant_row + WHERE grant_row.tenant_id = role.tenant_id AND grant_row.role_id = role.id + AND grant_row.permission_scope = kernel.scope AND grant_row.permission_key = kernel.permission_key)) + AND person.status = 'Active' + GROUP BY member.tenant_id + """; + + /// + /// The participant groups and the Memberships each holds, read under the person's User fence in one grouped statement + /// through ix_memberships_user_id: what Begin judges the closure's bounds by. Exposed so that a test can ask for + /// its plan. + /// + public static string ParticipantsSql => PlatformIdentityFences.ParticipantsSql; + + // The refusal record (ADR-0106 § 7): the request stays scheduled with its closed code. The guard's platform arm stamps + // the update time and the system actor, and refuses a code equal to the one standing. + private const string RecordRefusal = """ + UPDATE data_subject_requests SET last_refusal = @refusal, row_version = row_version + 1 + WHERE id = @id AND kind = 'closure' AND status = 'scheduled' AND row_version = @version + """; + + // The nonadmitting transition: the users trigger exception admits it only for this session, under the fences. + private const string CloseUser = "UPDATE users SET status = 'Closing' WHERE id = @subject AND status = 'Active'"; + + // The closure's Begin arrow: the guard asks again for the window, the Closing User and every fence. + private const string Fulfil = """ + UPDATE data_subject_requests SET status = 'fulfilling', row_version = row_version + 1 + WHERE id = @id AND kind = 'closure' AND status = 'scheduled' AND row_version = @version + """; + + /// + public async Task BeginAsync( + PlatformAdmission admission, Guid closureRequestId, CancellationToken cancellationToken = default) + { + RequireOperation(admission, PlatformOperations.ClosureBegin); + if (closureRequestId == Guid.Empty) + { + throw new ArgumentException("A closure Begin names a request.", nameof(closureRequestId)); + } + + // Before anything is entered or written: a deployment that cannot fan out never moves a person to Closing. + var fanOut = RequireFanOut(); + var commitSent = false; + BeginDecision decision; + try + { + decision = await BeginCoreAsync(admission, closureRequestId, () => commitSent = true, cancellationToken); + } + catch (Exception failure) when (commitSent && !IsFatal(failure)) + { + // The commit was sent: it may have landed, so this is never "nothing changed, repeat it". A repeat after a + // landed commit finds the closure fulfilling and resumes, which is how the operator finds out. + throw new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true, cause: failure); + } + catch (Exception failure) when (!commitSent && IsRetryable(failure, cancellationToken)) + { + // Nothing committed, so a repeat is safe: a fence another act held past the bound, or a transient fault. + throw new OperatorRecoveryUnavailableException(cause: failure); + } + + if (decision.Result is { } ended) + { + return ended; + } + + var groups = await FanOutAsync(fanOut, admission, decision, cancellationToken); + return new ClosureBeginResult(decision.Outcome, StatusCode(DataRequestStatus.Fulfilling), Groups: groups); + } + + private async Task BeginCoreAsync( + PlatformAdmission admission, Guid requestId, Action sendingCommit, CancellationToken cancellationToken) + { + await using var handle = await scope.EnterAsync(admission, cancellationToken); + var id = new PlatformSqlParameter("id", requestId); + + // 1. The request as it stands, unlocked: what it is and whose it is. + var found = await handle.QueryAsync(ReadRequest, [id], ClosureRequest.Read, cancellationToken); + if (found.Count == 0) + { + return BeginDecision.Ended(new ClosureBeginResult(ClosureBeginOutcome.NotFound)); + } + + var request = found[0]; + if (request.Kind != DataRequestKind.Closure) + { + return BeginDecision.Ended(new ClosureBeginResult(ClosureBeginOutcome.NotClosure, StatusCode(request.Status))); + } + + if (request.Status is not (DataRequestStatus.Scheduled or DataRequestStatus.Fulfilling)) + { + return BeginDecision.Ended(new ClosureBeginResult(ClosureBeginOutcome.NotBeginnable, StatusCode(request.Status))); + } + + if (request.Account == UserAccount.Closed) + { + return BeginDecision.Ended( + new ClosureBeginResult(ClosureBeginOutcome.SubjectNotAdmitted, StatusCode(request.Status))); + } + + if (request.Status == DataRequestStatus.Fulfilling) + { + // 2. A closure that began: no fence, no judgment, no write. Its scope ends by disposal. + return await ResumeAsync(handle, request.Subject, request.Account, cancellationToken); + } + + if (!ProviderAccepts(request.ProviderSubject)) + { + // Finalize could never delete this account (the port is not configured, or refuses the subject before any + // call), so the person is never moved to a Closing they could not leave. Nothing is written. + return BeginDecision.Ended(new ClosureBeginResult(ClosureBeginOutcome.RefusedProvider, StatusCode(request.Status))); + } + + // 3. The fences, the participants and their size read under the User fence among them. + var fences = await PlatformIdentityFences.AcquireAsync(handle, request.Subject, request.Tenant, cancellationToken); + if (!fences.WithinBounds) + { + // Every later step is bounded by the closure's size, so a person past it is refused while still Active; only the + // User key was taken, and nothing is written. + return BeginDecision.Ended(new ClosureBeginResult(ClosureBeginOutcome.RefusedTooLarge, StatusCode(request.Status))); + } + + // 4. The request again, locked, and the User status, both under the fences: what was read above may have moved. + var locked = await handle.QueryAsync(LockRequest, [id], LockedClosure.Read, cancellationToken); + if (locked.Count != 1 || locked[0].Kind != DataRequestKind.Closure || locked[0].Subject != request.Subject) + { + // A request's kind and person are immutable and it is never deleted. + throw new InvalidOperationException("The closure request changed its kind or person; the act is abandoned."); + } + + var closure = locked[0]; + var account = ParseAccount((await handle.QueryAsync( + ReadUserStatus, [new PlatformSqlParameter("subject", request.Subject.Value)], reader => reader.GetString(0), + cancellationToken)).SingleOrDefault()); + if (closure.Status is not (DataRequestStatus.Scheduled or DataRequestStatus.Fulfilling)) + { + // Cancelled by the person while this act waited for the fences. + return BeginDecision.Ended(new ClosureBeginResult(ClosureBeginOutcome.NotBeginnable, StatusCode(closure.Status))); + } + + if (account == UserAccount.Closed) + { + return BeginDecision.Ended( + new ClosureBeginResult(ClosureBeginOutcome.SubjectNotAdmitted, StatusCode(closure.Status))); + } + + var participants = await ClassifyAsync(handle, fences.Groups, cancellationToken); + if (closure.Status == DataRequestStatus.Fulfilling) + { + // Another operator's Begin committed while this one waited: nothing is left to judge or write. + return BeginDecision.FanOut(ClosureBeginOutcome.Resumed, request.Subject, participants); + } + + // 5. The judgment, in the ADR's order; the first refusal stands. + var refusal = await JudgeAsync(handle, request, closure, account, participants, cancellationToken); + if (refusal is { } refused) + { + return await RefuseAsync(handle, requestId, closure, refused, sendingCommit, cancellationToken); + } + + // 6. The transition: the User first, because the request's Begin arrow requires it Closing. + var before = State(("status", StatusCode(DataRequestStatus.Scheduled)), ("account", Account(account))); + if (account == UserAccount.Active) + { + var closed = await handle.ExecuteAsync( + CloseUser, [new PlatformSqlParameter("subject", request.Subject.Value)], cancellationToken); + if (closed != 1) + { + throw new InvalidOperationException("The fenced Active User did not move to Closing in exactly one row; the act is abandoned."); + } + } + + var fulfilled = await handle.ExecuteAsync( + Fulfil, [id, new PlatformSqlParameter("version", closure.Version)], cancellationToken); + if (fulfilled != 1) + { + throw new InvalidOperationException("The locked closure did not begin in exactly one row; the act is abandoned."); + } + + // 7. The MUST row, under the platform sentinel: the closure spans tenants, so no tenant's trail holds it, and it + // carries the operator's ticket. Closed counts only, never a person or a tenant. + await handle.WriteResultAsync( + new PlatformResult( + TenantId.PlatformSentinel, EntityType, requestId.ToString("D", CultureInfo.InvariantCulture), before, + State( + ("status", StatusCode(DataRequestStatus.Fulfilling)), ("account", Account(UserAccount.Closing)), + ("served_groups", participants.Served.Count), ("unserved_groups", participants.Unserved))), + cancellationToken); + + // Past the point where the caller's abort matters: a cancelled commit leaves its outcome unknown. + sendingCommit(); + await handle.CommitAsync(CancellationToken.None); + return BeginDecision.FanOut( + account == UserAccount.Active ? ClosureBeginOutcome.Begun : ClosureBeginOutcome.Resumed, request.Subject, participants); + } + + private async Task ResumeAsync( + IPlatformAdminScopeHandle handle, UserId subject, UserAccount account, CancellationToken cancellationToken) + { + if (account != UserAccount.Closing) + { + // The request guard admits a closure's Begin only for a Closing User, and nothing returns a User to Active. + throw new InvalidOperationException("A fulfilling closure's person is not Closing; the act is abandoned."); + } + + var read = await PlatformIdentityFences.ReadParticipantsAsync(handle, subject, cancellationToken); + if (!read.WithinBounds) + { + // Begin refused such a person while Active, and a Closing User is admitted to no Membership. + throw new InvalidOperationException("A begun closure's person is past the closure's bounds; the act is abandoned."); + } + + var participants = await ClassifyAsync(handle, read.Groups, cancellationToken); + return BeginDecision.FanOut(ClosureBeginOutcome.Resumed, subject, participants); + } + + /// The first refusal that stands, or none. + private async Task JudgeAsync( + IPlatformAdminScopeHandle handle, ClosureRequest request, LockedClosure closure, UserAccount account, + ClosureParticipants participants, CancellationToken cancellationToken) + { + if (!closure.Due) + { + return DataRequestRefusal.BlockedWindow; + } + + // The closure's own hold query: the person and the request's originating group, read from the row. Eligibility's + // execution stage is not asked, because a closure's execution re-check spans tenants and is this act's. + if (await holds.HasHoldAsync( + new DataRequestHoldQuery(DataRequestKind.Closure, request.Subject, request.Group), cancellationToken)) + { + return DataRequestRefusal.BlockedHold; + } + + if (account == UserAccount.Active && participants.OperableTenants.Count > 0) + { + var standings = await handle.QueryAsync( + AdministratorStandingSql, + [ + new PlatformSqlParameter("subject", request.Subject.Value), + new PlatformSqlParameter("tenants", participants.OperableTenants.Select(tenant => tenant.Value).ToArray()), + ], + reader => (Subject: reader.GetBoolean(1), Other: reader.GetBoolean(2)), + cancellationToken); + if (standings.Any(standing => standing.Subject && !standing.Other)) + { + return DataRequestRefusal.BlockedLastAdministrator; + } + } + + return null; + } + + /// + /// Records a refusal on the request with its MUST row, or, when the same code already stands, changes nothing and ends + /// by disposal: the guard refuses recording the standing code again, and the request already shows it. + /// + private static async Task RefuseAsync( + IPlatformAdminScopeHandle handle, Guid requestId, LockedClosure closure, DataRequestRefusal refusal, + Action sendingCommit, CancellationToken cancellationToken) + { + var code = DataRequestCodes.Refusals.ToCode(refusal); + var ended = new ClosureBeginResult( + refusal switch + { + DataRequestRefusal.BlockedWindow => ClosureBeginOutcome.RefusedWindow, + DataRequestRefusal.BlockedHold => ClosureBeginOutcome.RefusedHold, + _ => ClosureBeginOutcome.RefusedLastAdministrator, + }, + StatusCode(DataRequestStatus.Scheduled), + code); + if (closure.LastRefusal == refusal) + { + return BeginDecision.Ended(ended); + } + + var recorded = await handle.ExecuteAsync( + RecordRefusal, + [ + new PlatformSqlParameter("id", requestId), new PlatformSqlParameter("version", closure.Version), + new PlatformSqlParameter("refusal", code), + ], + cancellationToken); + if (recorded != 1) + { + throw new InvalidOperationException("The locked closure did not record its refusal in exactly one row; the act is abandoned."); + } + + await handle.WriteResultAsync( + new PlatformResult( + TenantId.PlatformSentinel, EntityType, requestId.ToString("D", CultureInfo.InvariantCulture), + State( + ("status", StatusCode(DataRequestStatus.Scheduled)), + ("last_refusal", closure.LastRefusal is { } standing ? DataRequestCodes.Refusals.ToCode(standing) : null)), + State(("status", StatusCode(DataRequestStatus.Scheduled)), ("last_refusal", code))), + cancellationToken); + sendingCommit(); + await handle.CommitAsync(CancellationToken.None); + return BeginDecision.Ended(ended); + } + + /// + /// Hands the served groups to the fan-out and counts its reports. The Begin has committed: a group the fan-out did not + /// report as started, adopted or waiting is failed, and a fan-out that throws fails every group, so the answer always + /// says a repeat is owed rather than lose the committed Begin. + /// + private async Task FanOutAsync( + IClosureFanOut fanOut, PlatformAdmission admission, BeginDecision decision, CancellationToken cancellationToken) + { + var participants = decision.Participants!; + var served = participants.Served; + var outcomes = new Dictionary(); + if (served.Count > 0) + { + try + { + var reports = await fanOut.FanOutAsync( + admission.Operator, admission.Ticket, new ClosureFanOutRequest(decision.Subject!.Value, served), cancellationToken); + foreach (var report in reports ?? []) + { + if (report is not null && served.Contains(report.Group) && Enum.IsDefined(report.Outcome)) + { + outcomes.TryAdd(report.Group, report.Outcome); + } + } + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } + catch (Exception failure) when (!IsFatal(failure)) + { + LogFanOutFailed(logger, failure); + outcomes.Clear(); + } + } + + int Count(ClosureGroupOutcome outcome) => outcomes.Values.Count(value => value == outcome); + var started = Count(ClosureGroupOutcome.Started); + var adopted = Count(ClosureGroupOutcome.Adopted); + var waiting = Count(ClosureGroupOutcome.Waiting); + return new ClosureBeginTally( + served.Count, started, adopted, waiting, served.Count - started - adopted - waiting, participants.Unserved); + } + + /// Where the platform transaction left the act: ended with a result, or due a fan-out. + private sealed record BeginDecision( + ClosureBeginResult? Result, ClosureBeginOutcome Outcome, UserId? Subject, ClosureParticipants? Participants) + { + internal static BeginDecision Ended(ClosureBeginResult result) => new(result, result.Outcome, null, null); + + internal static BeginDecision FanOut(ClosureBeginOutcome outcome, UserId subject, ClosureParticipants participants) => + new(null, outcome, subject, participants); + + /// Never prints the person. + public override string ToString() => nameof(BeginDecision); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/AccountClosureOperatorOperations.Finalize.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/AccountClosureOperatorOperations.Finalize.cs new file mode 100644 index 000000000..76ef9741f --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/AccountClosureOperatorOperations.Finalize.cs @@ -0,0 +1,713 @@ +using System.Collections.Frozen; +using System.Data.Common; +using System.Globalization; +using System.Text.Json.Nodes; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.Extensions.Logging; + +namespace LearnStack.Modules.Identity.Infrastructure.DataRequests; + +/// The closure's Finalize (ADR-0107 § 7, ADR-0108 § 8, finalize_closure). +/// +/// +/// Two transactions around the provider. The first takes the person's User fence alone, reads the participant groups +/// under it, locks the closure and reads the person's account, finds every required group ready, redacts the person's +/// audit rows in every participant tenant and then the platform sentinel tenant, and commits with the intent row that +/// carries the summed counts, which is the redaction's MUST evidence. It changes no User and no request, which is what the +/// tenant fences order, so no participant tenant's identity writes wait for its redaction; the User fence keeps the +/// participants fixed while it runs. The fence ends with that commit. The identity provider's account is deleted next, +/// before any other statement, so the transaction the checkpoint opened holds nothing while the call runs. The second +/// transaction takes the User fence and every participant tenant's fence, re-reads and re-judges everything the first +/// judged, moves the User from Closing to Closed with the raw provider subject removed, completes every participant erasure +/// awaiting the privileged step, this closure and every other open closure of the person, and commits with the result row. +/// +/// +/// Ready. A required group is ready when its newest erasure of the person (an open one first, of any origin) awaits +/// the privileged step, or completed at or after this closure's Begin, and its frozen Memberships include every Membership +/// the person holds in the group. Every served group is required; so is an unserved one whose newest erasure is the +/// closure's own fan-out and still open, because its job began before the group stopped allowing ordinary work, and once the +/// person is Closed nothing completes a fan-out erasure. The Begin moment is the closure's own update stamp: the guard's +/// Begin arrow wrote it from the database clock and no arrow writes the row again until this act. An erasure completed +/// before the closure began, by a person admitted again since, never stands in for a fan-out that did not run. +/// +/// +/// Another act may complete a participant's erasure meanwhile. The operator's erasure completion takes no closure +/// fence and may complete the person's or an administrator's own erasure while this act runs. The second transaction locks +/// the erasures it is about to complete and leaves one already completed as it found it: it is ready, and its own +/// completion redacted its tenant. +/// +/// +/// Every attempt is recorded. A refusal before the checkpoint changes nothing and ends by disposal, its entry row the +/// record. Every attempt that reaches the checkpoint writes its own intent row, a repeat's included, whose redaction then +/// finds nothing left to change; and every such attempt that ends without a fault writes its own result row saying how it +/// ended: finalized, or stopped at the provider, or a group found pending again, or another call's finalization found. +/// +/// +/// The provider subject. The one passed to the port is the one read under the User fence; the request's first read, +/// shared with Begin, returns it too and Finalize does not use that copy. It is never logged, audited, metered or +/// returned, and the second transaction removes it from the row. +/// +/// +public sealed partial class AccountClosureOperatorOperations +{ + /// + /// The most Memberships of the person one Finalize reads for its tenant passes: what an admitted closure can hold + /// (). Begin refused a person past it, so one beyond is a defect, never + /// redacted partially. + /// + internal const int MaximumMemberships = ClosureLimits.MaximumMemberships; + + /// The budget a result row recording a stop at the provider is written on, detached from the caller. + private static readonly TimeSpan CompletionBudget = TimeSpan.FromSeconds(3); + + /// The audit log's four retained kinds, the only ones a redaction report may set (ADR-0107 § 6). + private static readonly FrozenSet AuditKinds = new[] + { + RetainedReferenceKind.AuditActorReference, RetainedReferenceKind.AuditEntityReference, + RetainedReferenceKind.AuditMetadataReference, RetainedReferenceKind.UnscopedAuditRows, + }.ToFrozenSet(); + + private static readonly string Underway = State(("status", "fulfilling"), ("account", "closing")); + + // The closure, locked, with its Begin moment (the update stamp) and its recorded result, by primary key. + private const string LockClosure = """ + SELECT kind, subject_user_id, status, row_version, updated_at, result::text + FROM data_subject_requests WHERE id = @id FOR UPDATE + """; + + // The person's account by primary key, through the four granted columns: the status, the raw subject the provider + // deletes, and the key the sentinel pass selects by. The User fence serializes every writer of the row. + private const string ReadAccount = "SELECT status, provider_subject, subject_key FROM users WHERE id = @subject"; + + private const string ReadRecorded = "SELECT result::text FROM data_subject_requests WHERE id = @id"; + + // The users trigger exception admits it only for this session, from Closing, with every fence held. + private const string CloseAccount = "UPDATE users SET status = 'Closed', provider_subject = NULL WHERE id = @subject AND status = 'Closing'"; + + // A participant erasure's privileged step: Step 2's arm for the person's or an administrator's own erasure, the closure + // arm for a fan-out one; either admits a result change in the audit log's kinds alone and stamps the completion time. + private const string CompleteErasure = """ + UPDATE data_subject_requests SET status = 'completed', result = @result::jsonb, row_version = row_version + 1 + WHERE id = @id AND kind = 'erasure' AND status = 'awaiting_privileged_step' AND row_version = @version + """; + + // A closure of the person, from fulfilling or never begun; the guard admits either only for a Closed person, under + // every fence, with a result change in the audit log's kinds and the unserved groups alone. + private const string CompleteClosure = """ + UPDATE data_subject_requests SET status = 'completed', result = @result::jsonb, row_version = row_version + 1 + WHERE id = @id AND kind = 'closure' AND status = @status AND row_version = @version + """; + + /// + /// For each of the person's groups, the newest erasure of the person there: the open one if there is one (at most one, + /// by ux_data_subject_requests_active), else the newest terminal one, with its origin, whether it completed at or + /// after the closure's Begin and whether its frozen Memberships include every Membership the person holds in the group. + /// It reads the person's requests through ix_data_subject_requests_subject_user_id and each group's Memberships + /// through ix_memberships_user_id, so its cost is the person's own rows. Exposed so that a test can ask for its plan. + /// + public static string ReadinessSql { get; } = """ + SELECT DISTINCT ON (r.tenant_id, r.organization_id) + r.tenant_id, r.organization_id, r.id, r.status, r.row_version, r.result::text, + COALESCE(r.completed_at >= @began, false), + NOT EXISTS (SELECT 1 FROM public.memberships AS member + WHERE member.user_id = r.subject_user_id AND member.tenant_id = r.tenant_id + AND member.organization_id IS NOT DISTINCT FROM r.organization_id + AND NOT r.membership_snapshot @> jsonb_build_array(member.id::text)), + r.origin + FROM public.data_subject_requests AS r + WHERE r.subject_user_id = @subject AND r.kind = 'erasure' + ORDER BY r.tenant_id, r.organization_id, + r.status IN ('scheduled', 'fulfilling', 'awaiting_privileged_step') DESC, r.created_at DESC, r.id DESC + """; + + /// + /// Every Membership the person holds, of any status, by tenant: the identifiers each tenant pass compares. Read through + /// ix_memberships_user_id and bounded by . Exposed so that a test can ask for its plan. + /// + /// Begin admitted the closure only within , so each tenant's list fits one pass. + public static string MembershipsSql { get; } = """ + SELECT member.tenant_id, member.id FROM public.memberships AS member + WHERE member.user_id = @subject + ORDER BY member.tenant_id, member.id + LIMIT @limit + """; + + /// + /// The participant erasures the second transaction completes, locked by primary key in one order, so an erasure the + /// operator's erasure completion is finishing meanwhile is read as that act committed it. + /// + private const string LockErasures = """ + SELECT id, status, row_version FROM public.data_subject_requests WHERE id = ANY(@ids) ORDER BY id FOR UPDATE + """; + + /// + /// The person's other open closures, locked: at most one a group by ux_data_subject_requests_active, so bounded by + /// the closure's group bound, and read through ix_data_subject_requests_subject_user_id. Exposed so that a + /// test can ask for its plan. + /// + public static string OpenClosuresSql { get; } = """ + SELECT id, status, row_version, result::text FROM public.data_subject_requests + WHERE subject_user_id = @subject AND kind = 'closure' AND status IN ('scheduled', 'fulfilling') AND id <> @id + ORDER BY id + LIMIT @limit + FOR UPDATE + """; + + /// + public async Task FinalizeAsync( + PlatformAdmission admission, Guid closureRequestId, CancellationToken cancellationToken = default) + { + RequireOperation(admission, PlatformOperations.ClosureFinalize); + if (closureRequestId == Guid.Empty) + { + throw new ArgumentException("A closure Finalize names a request.", nameof(closureRequestId)); + } + + var commitSent = false; + var providerStepped = false; + try + { + return await FinalizeCoreAsync( + admission, closureRequestId, () => providerStepped = true, () => commitSent = true, cancellationToken); + } + catch (Exception failure) when (commitSent && !IsFatal(failure)) + { + // The final commit was sent: it may have landed, so this is never "nothing changed, repeat it". A repeat after + // a landed commit finds the closure completed and its person Closed, which is how the operator finds out. + throw new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true, cause: failure); + } + catch (Exception failure) when (!commitSent && IsRetryable(failure, cancellationToken)) + { + // Nothing of the closure's state committed. A redaction that committed with its intent row is idempotent, and + // a deleted account is found absent by the repeat, which is success. + throw new OperatorRecoveryUnavailableException(cause: failure); + } + catch (AuditWriteFailedException failure) when (providerStepped && !commitSent) + { + // The result row of the second transaction could not be written after the provider deleted the account, or + // found it absent: the closure's state rolled back with it, so the act is safe to repeat and the repeat finishes + // it, but "nothing changed" would be false. It is the retryable unavailable, never the audit refusal that says + // the provider was not asked. + throw new OperatorRecoveryUnavailableException(cause: failure); + } + } + + private async Task FinalizeCoreAsync( + PlatformAdmission admission, Guid requestId, Action providerStepped, Action sendingCommit, + CancellationToken cancellationToken) + { + await using var handle = await scope.EnterAsync(admission, cancellationToken); + var id = new PlatformSqlParameter("id", requestId); + var entity = requestId.ToString("D", CultureInfo.InvariantCulture); + + // 1. The request as it stands, unlocked: what it is, whose it is and where it stands. + var found = await handle.QueryAsync(ReadRequest, [id], ClosureRequest.Read, cancellationToken); + if (found.Count == 0) + { + return new ClosureFinalizeResult(ClosureFinalizeOutcome.NotFound); + } + + var request = found[0]; + if (request.Kind != DataRequestKind.Closure) + { + return new ClosureFinalizeResult(ClosureFinalizeOutcome.NotClosure, StatusCode(request.Status)); + } + + if (Judge(request.Status, request.Account) is { } early) + { + // Nothing is written: the scope ends by disposal and its entry row is the record. + return await EndedAsync(handle, id, early, cancellationToken); + } + + // 2. The first transaction: the User fence alone, and the participants read under it. It moves no User and no request, + // so no participant tenant's fence is taken: their identity writes do not wait for the redaction. + var fences = await PlatformIdentityFences.AcquireUserAsync(handle, request.Subject, cancellationToken); + if (fences.Groups.Count > PlatformIdentityFences.MaximumGroups) + { + // Begin refused a person in more groups, and a Closing User is admitted to no Membership. + throw Defect("participants_beyond_bound"); + } + + var (closure, account) = await LockAsync(handle, id, request.Subject, cancellationToken); + if (Judge(closure.Status, account.Status) is { } judged) + { + // Another operator's Finalize committed while this one waited for the fences. + return await EndedAsync(handle, id, judged, cancellationToken); + } + + // 3. Ready: every required group's erasure has run and covers the group. The Begin moment is the closure's own stamp. + var began = closure.BegunAt ?? throw Defect("fulfilling_closure_without_begin_stamp"); + var readiness = await ReadinessAsync(handle, request.Subject, began, fences.Groups, cancellationToken); + if (readiness.Tally.Pending > 0) + { + return new ClosureFinalizeResult(ClosureFinalizeOutcome.GroupsPending, StatusCode(closure.Status), readiness.Tally); + } + + var providerSubject = account.ProviderSubject is { Length: > 0 } held + ? held + : throw Defect("closing_account_without_provider_subject"); + + // 4. The redaction, every participant tenant then the sentinel, on this transaction, and the checkpoint that + // commits it with its evidence. Nothing here is undone by what follows. + var redaction = await RedactAsync(handle, request.Subject, account.Key, fences.Groups, cancellationToken); + await handle.WriteIntentAsync( + new PlatformResult(TenantId.PlatformSentinel, EntityType, entity, Underway, redaction.ToClosedJson()), cancellationToken); + + // 5. The provider, before any other statement: the new transaction holds nothing while it runs. + var removal = await RemoveAccountAsync(providerSubject, cancellationToken); + if (removal is not (AccountRemovalOutcome.Removed or AccountRemovalOutcome.Absent)) + { + var (outcome, token) = removal switch + { + AccountRemovalOutcome.Refused => (ClosureFinalizeOutcome.ProviderRefused, "provider_refused"), + AccountRemovalOutcome.Unavailable => (ClosureFinalizeOutcome.ProviderUnavailable, "provider_unavailable"), + _ => (ClosureFinalizeOutcome.ProviderUncertain, "provider_uncertain"), + }; + LogProviderStopped(logger, token); + await RecordEndingAsync(handle, entity, token, State(("outcome", token), ("status", "fulfilling"), ("account", "closing"))); + return new ClosureFinalizeResult(outcome, StatusCode(DataRequestStatus.Fulfilling), Redaction: redaction); + } + + // From here the account may already be gone: a result row that cannot be written is no longer "the provider was not + // asked". + providerStepped(); + var provider = removal == AccountRemovalOutcome.Removed ? "removed" : "absent"; + + // 6. The second transaction: the User fence and every participant tenant's fence, which its changes need and the + // first transaction did not take, and every judgment again under them. + var again = await PlatformIdentityFences.AcquireAsync(handle, request.Subject, request.Tenant, cancellationToken); + var (current, person) = await LockAsync(handle, id, request.Subject, cancellationToken); + if (current.Status == DataRequestStatus.Completed && person.Status == UserAccount.Closed) + { + // Another operator's Finalize finished the closure while this one called the provider. + const string Token = "already_finalized"; + await RecordEndingAsync(handle, entity, Token, + State(("outcome", Token), ("status", "completed"), ("account", "closed"), ("provider", provider))); + return new ClosureFinalizeResult( + ClosureFinalizeOutcome.AlreadyFinalized, StatusCode(DataRequestStatus.Completed), Redaction: redaction, + Retained: Counts(current.Result)); + } + + if (current.Status != DataRequestStatus.Fulfilling || person.Status != UserAccount.Closing || current.Version != closure.Version + || current.BegunAt != began || !again.WithinBounds || !again.Groups.SequenceEqual(fences.Groups)) + { + // Nothing returns a User to Active, admits a Membership for a Closing one or writes a fulfilling closure but this + // act, so a change between the two transactions is a broken invariant. + throw Defect("closure_changed_between_transactions"); + } + + var ready = await ReadinessAsync(handle, request.Subject, began, again.Groups, cancellationToken); + if (ready.Tally.Pending > 0) + { + const string Token = "groups_pending"; + await RecordEndingAsync(handle, entity, Token, + State(("outcome", Token), ("status", "fulfilling"), ("account", "closing"), ("provider", provider), + ("groups", Tally(ready.Tally)))); + return new ClosureFinalizeResult( + ClosureFinalizeOutcome.GroupsPending, StatusCode(DataRequestStatus.Fulfilling), ready.Tally, Redaction: redaction); + } + + // 7. The account first, because the closure arrows require it Closed; then the participants' erasures, this closure + // and the person's other open closures; then the result row, all on this one transaction. + var subject = new PlatformSqlParameter("subject", request.Subject.Value); + if (await handle.ExecuteAsync(CloseAccount, [subject], cancellationToken) != 1) + { + throw Defect("account_not_closed"); + } + + var erasuresCompleted = await CompleteErasuresAsync(handle, ready.Awaiting, redaction, cancellationToken); + + var unserved = ready.Tally.Unserved; + var closureResult = Merge(current.Result, redaction.Total, unserved); + await CompleteClosureAsync(handle, requestId, DataRequestStatus.Fulfilling, current.Version, closureResult, cancellationToken); + var others = await handle.QueryAsync( + OpenClosuresSql, + [subject, id, new PlatformSqlParameter("limit", PlatformIdentityFences.MaximumGroups + 1)], + reader => (Id: reader.GetGuid(0), Status: DataRequestCodes.Statuses.Parse(reader.GetString(1)), Version: reader.GetInt64(2), + Result: reader.GetString(3)), + cancellationToken); + if (others.Count > PlatformIdentityFences.MaximumGroups) + { + throw Defect("open_closures_beyond_bound"); + } + + foreach (var other in others) + { + await CompleteClosureAsync( + handle, other.Id, other.Status, other.Version, Merge(other.Result, redaction.Total, unserved), cancellationToken); + } + + var groups = ready.Tally with { ErasuresCompleted = erasuresCompleted, ClosuresCompleted = others.Count + 1 }; + await handle.WriteResultAsync( + new PlatformResult( + TenantId.PlatformSentinel, EntityType, entity, Underway, + State( + ("outcome", "finalized"), ("status", "completed"), ("account", "closed"), ("provider", provider), + ("groups", Tally(groups)), ("retained", Document(closureResult)))), + cancellationToken); + + // Past the point where the caller's abort matters: a cancelled commit leaves its outcome unknown. + sendingCommit(); + await handle.CommitAsync(CancellationToken.None); + return new ClosureFinalizeResult( + ClosureFinalizeOutcome.Finalized, StatusCode(DataRequestStatus.Completed), groups, + [.. again.Groups.Where(group => !ready.Served.Contains(group))], redaction, Counts(closureResult)); + } + + /// + /// The judgment of where the closure stands: nothing to say while it is fulfilling with its person Closing, an + /// earlier finalization, a closure never begun or cancelled, or a state no admitted path writes. + /// + private ClosureFinalizeResult? Judge(DataRequestStatus status, UserAccount account) => status switch + { + DataRequestStatus.Fulfilling when account == UserAccount.Closing => null, + DataRequestStatus.Fulfilling => throw Defect("fulfilling_closure_account_not_closing"), + DataRequestStatus.Completed when account == UserAccount.Closed => + new ClosureFinalizeResult(ClosureFinalizeOutcome.AlreadyFinalized, StatusCode(status)), + DataRequestStatus.Completed => throw Defect("completed_closure_account_not_closed"), + _ => new ClosureFinalizeResult(ClosureFinalizeOutcome.NotFinalizable, StatusCode(status)), + }; + + /// An ending before the checkpoint: nothing is written, and an earlier finalization answers what it recorded. + private static async Task EndedAsync( + IPlatformAdminScopeHandle handle, PlatformSqlParameter id, ClosureFinalizeResult ended, CancellationToken cancellationToken) + { + if (ended.Outcome != ClosureFinalizeOutcome.AlreadyFinalized) + { + return ended; + } + + var recorded = await handle.QueryAsync(ReadRecorded, [id], reader => reader.GetString(0), cancellationToken); + return ended with { Retained = Counts(recorded.Single()) }; + } + + /// The closure locked and the person's account read, both under the fences this transaction holds. + private static async Task<(FinalizingClosure Closure, ClosingAccount Account)> LockAsync( + IPlatformAdminScopeHandle handle, PlatformSqlParameter id, UserId subject, CancellationToken cancellationToken) + { + var locked = await handle.QueryAsync(LockClosure, [id], FinalizingClosure.Read, cancellationToken); + if (locked.Count != 1 || locked[0].Kind != DataRequestKind.Closure || locked[0].Subject != subject) + { + // A request's kind and person are immutable and it is never deleted. + throw new InvalidOperationException("The closure request changed its kind or person; the act is abandoned."); + } + + var accounts = await handle.QueryAsync( + ReadAccount, [new PlatformSqlParameter("subject", subject.Value)], ClosingAccount.Read, cancellationToken); + return (locked[0], accounts.Count == 1 + ? accounts[0] + : throw new InvalidOperationException("A closure's person has no readable User; the act is abandoned.")); + } + + /// + /// Where each participant group stands: the required groups that are ready and the participant erasures awaiting the + /// privileged step, which the second transaction completes. Every served group is required. An unserved group needs no + /// erasure unless its newest one is the closure's own fan-out and still open: its job began before the group stopped + /// allowing ordinary work, and once the person is Closed nothing completes it, so the group stays required until it + /// awaits the privileged step. One that reached the privileged step, whatever its origin, is completed with the others, + /// since its job ran and its tenant is redacted. + /// + private async Task ReadinessAsync( + IPlatformAdminScopeHandle handle, UserId subject, DateTimeOffset began, IReadOnlyList groups, + CancellationToken cancellationToken) + { + var participants = await ClassifyAsync(handle, groups, cancellationToken); + var newest = (await handle.QueryAsync( + ReadinessSql, + [new PlatformSqlParameter("subject", subject.Value), new PlatformSqlParameter("began", began)], + GroupErasure.Read, + cancellationToken)) + .ToDictionary(erasure => erasure.Group); + var served = participants.Served.ToHashSet(); + var required = groups.Where(group => served.Contains(group) + || (newest.TryGetValue(group, out var erasure) && erasure.Origin == DataRequestOrigin.ClosureFanout && erasure.Open)).ToList(); + var ready = required.Count(group => newest.TryGetValue(group, out var erasure) && erasure.Covers + && (erasure.Status == DataRequestStatus.AwaitingPrivilegedStep + || (erasure.Status == DataRequestStatus.Completed && erasure.CompletedDuringClosure))); + var awaiting = groups.Where(group => newest.TryGetValue(group, out var erasure) + && erasure.Status == DataRequestStatus.AwaitingPrivilegedStep) + .Select(group => newest[group]).ToList(); + return new Readiness( + new ClosureFinalizeTally(served.Count, ready, required.Count - ready, groups.Count - served.Count), served, awaiting); + } + + /// + /// Completes the participant erasures awaiting the privileged step, each locked first: one still awaiting at the version + /// read is completed with its tenant's retained audit kinds; one the operator's erasure completion finished meanwhile is + /// left as it completed, ready and redacted by its own act. Any other state is one no admitted path writes. + /// + /// How many erasures this call completed. + private async Task CompleteErasuresAsync( + IPlatformAdminScopeHandle handle, IReadOnlyList awaiting, AuditRedactionAggregate redaction, + CancellationToken cancellationToken) + { + if (awaiting.Count == 0) + { + return 0; + } + + var locked = (await handle.QueryAsync( + LockErasures, + [new PlatformSqlParameter("ids", awaiting.Select(erasure => erasure.Id).ToArray())], + reader => (Id: reader.GetGuid(0), Status: DataRequestCodes.Statuses.Parse(reader.GetString(1)), Version: reader.GetInt64(2)), + cancellationToken)) + .ToDictionary(row => row.Id); + var completed = 0; + foreach (var erasure in awaiting) + { + if (!locked.TryGetValue(erasure.Id, out var now)) + { + throw Defect("erasure_not_completed"); + } + + if (now.Status == DataRequestStatus.Completed) + { + // The operator's erasure completion committed it while this act ran; it stands as it completed. + continue; + } + + if (now.Status != DataRequestStatus.AwaitingPrivilegedStep || now.Version != erasure.Version + || await handle.ExecuteAsync( + CompleteErasure, + [ + new PlatformSqlParameter("id", erasure.Id), new PlatformSqlParameter("version", erasure.Version), + new PlatformSqlParameter("result", Merge(erasure.Result, redaction.Tenants[erasure.Group.TenantId], unserved: null)), + ], + cancellationToken) != 1) + { + throw Defect("erasure_not_completed"); + } + + completed++; + } + + return completed; + } + + /// + /// The redaction: one pass over every participant tenant, served or not, with every Membership the person holds there, + /// then one over the platform sentinel tenant by the person's subject key; their reports summed. Begin admitted the + /// closure only within , so a tenant's Memberships beyond one pass's bound, which the plan + /// refuses, are a defect named by its closed name, never an untyped failure. + /// + private async Task RedactAsync( + IPlatformAdminScopeHandle handle, UserId subject, IdentitySubjectKey key, IReadOnlyList groups, + CancellationToken cancellationToken) + { + var memberships = await handle.QueryAsync( + MembershipsSql, + [new PlatformSqlParameter("subject", subject.Value), new PlatformSqlParameter("limit", MaximumMemberships + 1)], + reader => (Tenant: TenantId.From(reader.GetGuid(0)), Id: reader.GetGuid(1)), + cancellationToken); + if (memberships.Count > MaximumMemberships) + { + throw Defect("memberships_beyond_bound"); + } + + var reports = new Dictionary(); + foreach (var tenant in groups.Select(group => group.TenantId).Distinct().OrderBy(tenant => tenant.Value)) + { + AuditRedactionPlan plan; + try + { + plan = AuditRedactionPlan.ForClosureTenant( + tenant, subject, memberships.Where(member => member.Tenant == tenant).Select(member => member.Id)); + } + catch (ArgumentException) + { + // The plan's own refusal names the person's tenant and Memberships nowhere; neither does the defect. + throw Defect("redaction_plan_refused"); + } + + reports[tenant] = await handle.RedactAuditAsync(plan, cancellationToken); + } + + var sentinel = await handle.RedactAuditAsync(AuditRedactionPlan.ForClosureSentinel(subject, key), cancellationToken); + return new AuditRedactionAggregate(reports, sentinel); + } + + /// + /// The provider's deletion. A port that throws, the caller's leaving included, answers nothing about whether the deletion + /// reached the provider: it is uncertain, and a repeat finds the account absent if it had landed. + /// + private async Task RemoveAccountAsync(string providerSubject, CancellationToken cancellationToken) + { + try + { + var outcome = await accountRemoval.RemoveAsync(providerSubject, cancellationToken); + return Enum.IsDefined(outcome) ? outcome : AccountRemovalOutcome.Uncertain; + } + catch (Exception failure) when (!IsFatal(failure)) + { + // The exception's type only: its text is the adapter's or the transport's, and nothing of it is the operator's. + LogProviderThrew(logger, failure.GetType().Name); + return AccountRemovalOutcome.Uncertain; + } + } + + /// + /// Writes and commits the result row of an attempt that ended after its checkpoint without finalizing, on a budget + /// detached from the caller. Nothing of the closure's state changes in that transaction, so a row that cannot be written + /// changes no answer: the intent row stands alone, the failure is logged, and the act's answer is what it found. + /// + private async Task RecordEndingAsync(IPlatformAdminScopeHandle handle, string entity, string token, string after) + { + using var budget = new CancellationTokenSource(CompletionBudget); + try + { + await handle.WriteResultAsync( + new PlatformResult(TenantId.PlatformSentinel, EntityType, entity, Underway, after), budget.Token); + await handle.CommitAsync(budget.Token); + } + catch (Exception failure) when (!IsFatal(failure)) + { + LogEndingLost(logger, token, failure); + } + } + + private static async Task CompleteClosureAsync( + IPlatformAdminScopeHandle handle, Guid id, DataRequestStatus status, long version, string result, + CancellationToken cancellationToken) + { + var completed = await handle.ExecuteAsync( + CompleteClosure, + [ + new PlatformSqlParameter("id", id), new PlatformSqlParameter("status", StatusCode(status)), + new PlatformSqlParameter("version", version), new PlatformSqlParameter("result", result), + ], + cancellationToken); + if (completed != 1) + { + throw new InvalidOperationException("A locked closure of the person did not complete in exactly one row; the act is abandoned."); + } + } + + /// + /// A request's recorded result with the redaction's retained audit kinds set, and for a closure its unserved groups. A + /// kind the report leaves out keeps its recorded count, because a report's list is partial and an absent kind is not zero. + /// + private static string Merge(string recorded, AuditRedactionReport report, int? unserved) + { + var result = JsonNode.Parse(recorded)?.AsObject() + ?? throw new InvalidOperationException("A request's recorded result is not a document; the act is abandoned."); + foreach (var entry in report.Retained) + { + if (!AuditKinds.Contains(entry.Kind)) + { + throw new InvalidOperationException("The redaction reported a retained kind the audit log does not hold; the act is abandoned."); + } + + result[DataRequestCodes.RetainedKinds.ToCode(entry.Kind)] = entry.Count; + } + + if (unserved is { } count) + { + result[DataRequestCodes.RetainedKinds.ToCode(RetainedReferenceKind.UnservedGroup)] = count; + } + + return result.ToJsonString(); + } + + /// A recorded result as closed kind codes and counts; every key is parsed against the closed vocabulary. + private static Dictionary Counts(string recorded) + { + var result = JsonNode.Parse(recorded)?.AsObject() + ?? throw new InvalidOperationException("A request's recorded result is not a document; the act is abandoned."); + return result.ToDictionary( + entry => DataRequestCodes.RetainedKinds.ToCode(DataRequestCodes.RetainedKinds.Parse(entry.Key)), + entry => entry.Value!.GetValue(), + StringComparer.Ordinal); + } + + private static JsonObject Document(string recorded) => JsonNode.Parse(recorded)!.AsObject(); + + private static JsonObject Tally(ClosureFinalizeTally tally) => new() + { + ["served"] = tally.Served, + ["ready"] = tally.Ready, + ["pending"] = tally.Pending, + ["unserved"] = tally.Unserved, + ["erasures_completed"] = tally.ErasuresCompleted, + ["closures_completed"] = tally.ClosuresCompleted, + }; + + /// Logs a broken invariant by its closed name and returns the exception that abandons the act. + private InvalidOperationException Defect(string defect) + { + LogDefect(logger, defect); + return new InvalidOperationException("A closure's Finalize found a state no admitted path writes; the act is abandoned."); + } + + [LoggerMessage(EventId = 7121, Level = LogLevel.Warning, + Message = "A closure's Finalize stopped at the identity provider ({Outcome}); the closure stays fulfilling and a repeat resumes it.")] + private static partial void LogProviderStopped(ILogger logger, string outcome); + + [LoggerMessage(EventId = 7122, Level = LogLevel.Error, + Message = "A closure's Finalize found {Defect}, a state no admitted path writes; the act is abandoned.")] + private static partial void LogDefect(ILogger logger, string defect); + + [LoggerMessage(EventId = 7123, Level = LogLevel.Critical, + Message = "A closure Finalize's result row recording {Outcome} could not be written; its intent row stands alone and the answer is unchanged.")] + private static partial void LogEndingLost(ILogger logger, string outcome, Exception failure); + + [LoggerMessage(EventId = 7124, Level = LogLevel.Warning, + Message = "The identity provider's account removal threw {ExceptionType}; the deletion is treated as uncertain.")] + private static partial void LogProviderThrew(ILogger logger, string exceptionType); + + /// The closure as the act reads it locked, under every fence. + private sealed record FinalizingClosure( + DataRequestKind Kind, UserId Subject, DataRequestStatus Status, long Version, DateTimeOffset? BegunAt, string Result) + { + internal static FinalizingClosure Read(DbDataReader reader) => new( + DataRequestCodes.Kinds.Parse(reader.GetString(0)), UserId.From(reader.GetGuid(1)), + DataRequestCodes.Statuses.Parse(reader.GetString(2)), reader.GetInt64(3), + reader.IsDBNull(4) ? null : reader.GetFieldValue(4), reader.GetString(5)); + + /// Never prints the person. + public override string ToString() => nameof(FinalizingClosure); + } + + /// The person's account under the fences: its status, the raw provider subject and the subject key. + private sealed record ClosingAccount(UserAccount Status, string? ProviderSubject, IdentitySubjectKey Key) + { + // ck_users_subject_lifecycle keeps the raw subject on an Active User, Begin's arrow keeps it on Closing, and Closed + // removes it; a Closed account is judged before the subject is ever needed. + internal static ClosingAccount Read(DbDataReader reader) => new( + ParseAccount(reader.GetString(0)), reader.IsDBNull(1) ? null : reader.GetString(1), + IdentitySubjectKey.FromBytes(reader.GetFieldValue(2))); + + /// Never prints the subject or the key. + public override string ToString() => nameof(ClosingAccount); + } + + /// One group's newest erasure of the person, and whether it stands for the group. + private sealed record GroupErasure( + ClosureParticipantGroup Group, Guid Id, DataRequestStatus Status, long Version, string Result, + bool CompletedDuringClosure, bool Covers, DataRequestOrigin Origin) + { + /// Whether the erasure has not reached a terminal status. + internal bool Open => Status is DataRequestStatus.Scheduled or DataRequestStatus.Fulfilling + or DataRequestStatus.AwaitingPrivilegedStep; + + internal static GroupErasure Read(DbDataReader reader) => new( + new ClosureParticipantGroup( + TenantId.From(reader.GetGuid(0)), reader.IsDBNull(1) ? null : OrganizationId.From(reader.GetGuid(1))), + reader.GetGuid(2), DataRequestCodes.Statuses.Parse(reader.GetString(3)), reader.GetInt64(4), reader.GetString(5), + reader.GetBoolean(6), reader.GetBoolean(7), DataRequestCodes.Origins.Parse(reader.GetString(8))); + + /// Never prints the request's group. + public override string ToString() => nameof(GroupErasure); + } + + /// The tallies, the served groups and the participant erasures awaiting the privileged step. + private sealed record Readiness( + ClosureFinalizeTally Tally, IReadOnlySet Served, IReadOnlyList Awaiting) + { + public override string ToString() => nameof(Readiness); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/AccountClosureOperatorOperations.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/AccountClosureOperatorOperations.cs new file mode 100644 index 000000000..ca5a4c4ea --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/AccountClosureOperatorOperations.cs @@ -0,0 +1,236 @@ +using System.Data.Common; +using System.Text.Json.Nodes; +using LearnStack.Infrastructure.Messaging; +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.Extensions.Logging; + +namespace LearnStack.Modules.Identity.Infrastructure.DataRequests; + +/// +/// The confined owner of the operator's global account closure acts (ADR-0107 §§ 7 and 8): Begin and Finalize, each in its +/// own part of this class. +/// +/// +/// +/// The database bounds what it reads and decides what it admits. Every act is one entered platform scope on +/// learnstack_platform, which reads the request, the person's User status and Memberships, and the administrator +/// predicate's columns through closed column grants. The changes it makes are admitted by the users trigger exception +/// and the request guard's closure arrows only with the fences this connection holds in pg_locks, the subject's User +/// status and the request's own state: no flag of this class is trusted by the database. +/// +/// +/// Lifecycle through Tenancy. Which participant groups are served, and which participant tenants the +/// last-administrator rule protects, comes from Tenancy's own port, read on the scope's transaction; no Tenancy table is +/// named here. +/// +/// +/// The fan-out runs after the commit. The per-group erasures run as the application role in each group's own +/// transaction and take the person's fences themselves, so they start only once Begin has committed and released its own. +/// No fan-out registered refuses the act before anything is entered or written, so a deployment without one never moves a +/// person to Closing. +/// +/// +/// The provider account. This class is the one holder of , whose client +/// can also create and update users in the shared realm; only Finalize asks it to delete, between its two transactions, +/// with the raw provider subject it read on the platform connection, which it never logs, audits, meters or returns. Begin +/// asks only the port's local preflight, with the subject its first read returns, and refuses a closure the port could +/// never finish before the person leaves Active. +/// +/// +/// The bounds. Every bound a later step enforces is judged by Begin before the person leaves Active +/// (): a person in more participant groups, or with more Memberships in one participant tenant, +/// than one closure is admitted for is refused with nothing changed, never moved to Closing and then stranded. +/// +/// +/// Failures. A transient database fault before the commit, a fence not granted within its bound included, is the +/// unavailable owner and safe to repeat; any failure once the commit was sent is the unknown outcome. Anything else, a +/// refused credential or a missing grant included, is the defect it is. +/// +/// +public sealed partial class AccountClosureOperatorOperations( + IPlatformAdminScope scope, + IClosureGroupLifecycleReader lifecycle, + IDataRequestHoldSource holds, + IEnumerable fanOuts, + IIdentityProviderAccountRemoval accountRemoval, + ILogger logger) : IAccountClosureOperatorOperations +{ + private const string EntityType = "DataSubjectRequest"; + + // The request as the act first meets it, before any fence: enough to refuse what is not a closure, to find the person, + // to know whether the closure already began, and to ask the identity provider's port whether the person's account could + // ever be deleted. The platform role reads these columns and the User's status and raw subject by grant. + private const string ReadRequest = """ + SELECT r.tenant_id, r.organization_id, r.kind, r.subject_user_id, r.status, person.status, person.provider_subject + FROM data_subject_requests AS r LEFT JOIN users AS person ON person.id = r.subject_user_id + WHERE r.id = @id + """; + + // The request again, locked, once every fence is held; whether its window has passed is the database clock's answer, + // which the guard's Begin arrow asks again with a later clock. + private const string LockRequest = """ + SELECT kind, subject_user_id, status, last_refusal, row_version, + COALESCE(clock_timestamp() >= execute_at, false) + FROM data_subject_requests WHERE id = @id FOR UPDATE + """; + + private const string ReadUserStatus = "SELECT status FROM users WHERE id = @subject"; + + /// + /// Whether the identity provider's port could ever send the deletion of this raw subject: a local answer, asked by Begin + /// before the person leaves Active, so a closure whose Finalize could never finish is refused while nothing has changed. + /// The subject is passed to the port and nowhere else. + /// + private bool ProviderAccepts(string? providerSubject) => + providerSubject is { Length: > 0 } subject && accountRemoval.CanRemove(subject); + + /// The one fan-out the act hands the served groups to, or a refusal when none or several are registered. + private IClosureFanOut RequireFanOut() + { + var registered = fanOuts.Take(2).ToArray(); + return registered.Length == 1 + ? registered[0] + : throw new InvalidOperationException( + "No single closure fan-out is registered, so a closure cannot begin; nothing was entered or changed."); + } + + /// + /// The served participant groups and the unserved count, from each group's lifecycle on the scope's transaction, and + /// the participant tenants that allow ordinary work. + /// + private async Task ClassifyAsync( + IPlatformAdminScopeHandle handle, IReadOnlyList groups, CancellationToken cancellationToken) + { + var facts = await lifecycle.ReadAsync( + handle, [.. groups.Select(group => (group.TenantId, group.OrganizationId))], cancellationToken); + var served = new List(); + var operable = new HashSet(); + for (var index = 0; index < groups.Count; index++) + { + var group = groups[index]; + var fact = facts[index]; + if (!fact.TenantAllowsOrdinaryWork) + { + continue; + } + + operable.Add(group.TenantId); + if (group.OrganizationId is null || (fact.OrganizationBelongsToTenant && fact.OrganizationAllowsOrdinaryWork)) + { + served.Add(group); + } + } + + return new ClosureParticipants(served, groups.Count - served.Count, [.. operable]); + } + + private static string StatusCode(DataRequestStatus status) => DataRequestCodes.Statuses.ToCode(status); + + private static string Account(UserAccount account) => account switch + { + UserAccount.Active => "active", + UserAccount.Closing => "closing", + _ => "closed", + }; + + private static UserAccount ParseAccount(string? status) => status switch + { + "Active" => UserAccount.Active, + "Closing" => UserAccount.Closing, + "Closed" => UserAccount.Closed, + // The foreign key keeps the User of every request, and ck_users_status closes its status. + _ => throw new InvalidOperationException("A closure's person has no readable User status; the act is abandoned."), + }; + + private static string State(params (string Name, JsonNode? Value)[] members) + { + var state = new JsonObject(); + foreach (var (name, value) in members) + { + state[name] = value; + } + + return state.ToJsonString(); + } + + private static void RequireOperation(PlatformAdmission admission, PlatformOperation expected) + { + ArgumentNullException.ThrowIfNull(admission); + if (!ReferenceEquals(admission.Operation, expected)) + { + throw new ArgumentException("The admission is not for this closure operation.", nameof(admission)); + } + } + + /// + /// A fault before the commit that a repeat may not meet: the transient database faults the other owners retry. A fence + /// or a row lock not granted within the act's bound (55P03) and a deadlock the database broke (40P01) are + /// among them, because the driver classifies both as transient; a test holds a fence past the bound to pin it. + /// + private static bool IsRetryable(Exception failure, CancellationToken cancellationToken) => + OperatorRecoveryFaults.IsTransientDatabaseFault(failure, cancellationToken); + + private static bool IsFatal(Exception failure) => failure is OutOfMemoryException or AccessViolationException or StackOverflowException; + + [LoggerMessage(EventId = 7120, Level = LogLevel.Error, + Message = "A closure's fan-out threw after its Begin committed; every served group is reported failed and a repeated Begin retries them.")] + private static partial void LogFanOutFailed(ILogger logger, Exception failure); + + /// The person's User status, closed. + private enum UserAccount + { + Active = 1, + Closing, + Closed, + } + + /// The participant groups split by their lifecycle. + /// The groups the fan-out reaches. + /// How many groups it does not. + /// The participant tenants that allow ordinary work. + private sealed record ClosureParticipants( + IReadOnlyList Served, int Unserved, IReadOnlyList OperableTenants) + { + public override string ToString() => nameof(ClosureParticipants); + } + + /// + /// The request as the act first reads it, before any fence; its group and person never change, and neither does the + /// raw provider subject of a person who is not Closed. + /// + private sealed record ClosureRequest( + DataRequestScopeGroup Group, DataRequestKind Kind, UserId Subject, DataRequestStatus Status, UserAccount Account, + string? ProviderSubject) + { + internal TenantId Tenant => Group.TenantId; + + internal static ClosureRequest Read(DbDataReader reader) => new( + new DataRequestScopeGroup( + TenantId.From(reader.GetGuid(0)), reader.IsDBNull(1) ? null : OrganizationId.From(reader.GetGuid(1))), + DataRequestCodes.Kinds.Parse(reader.GetString(2)), UserId.From(reader.GetGuid(3)), + DataRequestCodes.Statuses.Parse(reader.GetString(4)), ParseAccount(reader.IsDBNull(5) ? null : reader.GetString(5)), + reader.IsDBNull(6) ? null : reader.GetString(6)); + + /// Never prints the person or the raw subject. + public override string ToString() => nameof(ClosureRequest); + } + + /// The request as the act reads it locked, under every fence. + private sealed record LockedClosure( + DataRequestKind Kind, UserId Subject, DataRequestStatus Status, DataRequestRefusal? LastRefusal, long Version, bool Due) + { + internal static LockedClosure Read(DbDataReader reader) => new( + DataRequestCodes.Kinds.Parse(reader.GetString(0)), UserId.From(reader.GetGuid(1)), + DataRequestCodes.Statuses.Parse(reader.GetString(2)), + reader.IsDBNull(3) ? null : DataRequestCodes.Refusals.Parse(reader.GetString(3)), reader.GetInt64(4), + reader.GetBoolean(5)); + + /// Never prints the person. + public override string ToString() => nameof(LockedClosure); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/ClosureFanOut.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/ClosureFanOut.cs new file mode 100644 index 000000000..427420542 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/ClosureFanOut.cs @@ -0,0 +1,155 @@ +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.Modules.Identity.Application.Contracts.OperatorActs; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Platform; +using Microsoft.Extensions.Logging; + +namespace LearnStack.Modules.Identity.Infrastructure.DataRequests; + +/// +/// The closure's fan-out (fan_out_closure, ADR-0107 § 7): one pipeline act per participant group, each admitted by +/// the gate on its own and run by the operator act executor in the group's own tenant and organization. +/// +/// +/// +/// After Begin, never inside it. Begin's owner calls this once its transaction has committed and released the +/// fences, so each group's act takes the person's User fence and its tenant's fence on its own application connection. +/// Nothing here opens a connection, reads the platform scope or writes a row: the executor runs +/// through the ordinary pipeline, which writes the group tenant's MUST row. +/// +/// +/// One admission per act. The gate is asked for with the operator's +/// witness and ticket before every group, so the grant is evaluated per act: an operator whose grant is withdrawn between +/// groups is refused from that group on. The ticket never reaches a tenant row. +/// +/// +/// Every group is answered. Groups run one after another in a deterministic order, at most +/// . A refused admission, a refusal result and an exception are each that group's +/// , which a repeated Begin retries; only the operator's cancellation stops the +/// loop, by throwing. The call is idempotent, because each act adopts what an earlier one started. +/// +/// +/// Signals. One log line per group carries the outcome and, for a failure, the exception type or the refusal's +/// closed code; never the person, the group or a ticket. The data-request counter is labelled with the operation and the +/// group's outcome. +/// +/// +public sealed partial class ClosureFanOut( + IPlatformOperatorGate gate, + PlatformOperatorActExecutor executor, + ILogger logger) : IClosureFanOut +{ + /// + /// The most participant groups one call fans out to: the closure's group bound, which Begin judges before the person + /// leaves Active, so a longer list is a programming error of the caller (). + /// + public const int MaximumGroups = ClosureLimits.MaximumParticipantGroups; + + public async Task> FanOutAsync( + PlatformOperatorWitness operatorWitness, + string? ticket, + ClosureFanOutRequest request, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(operatorWitness); + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(request.Groups); + var subject = request.SubjectUserId; + if (!StronglyTypedId.IsAssigned(subject) || subject.Value.Version != 7 || subject == UserId.SystemActor) + { + throw new ArgumentException("A closure's fan-out names a real person.", nameof(request)); + } + + if (request.Groups.Count > MaximumGroups || request.Groups.Any(group => group is null + || !StronglyTypedId.IsAssigned(group.TenantId) || group.TenantId == TenantId.PlatformSentinel + || group.OrganizationId is { } organization && !StronglyTypedId.IsAssigned(organization)) + || request.Groups.Distinct().Count() != request.Groups.Count) + { + throw new ArgumentException( + "A closure's fan-out names at most " + MaximumGroups.ToString(System.Globalization.CultureInfo.InvariantCulture) + + " distinct participant groups.", nameof(request)); + } + + // Tenant, then the tenant-wide group before its organizations, then each organization: the same order whatever + // order the caller listed them in. + var groups = request.Groups.OrderBy(group => group.TenantId.Value) + .ThenBy(group => group.OrganizationId is null ? 0 : 1) + .ThenBy(group => group.OrganizationId?.Value ?? Guid.Empty) + .ToArray(); + var reports = new List(groups.Length); + foreach (var group in groups) + { + cancellationToken.ThrowIfCancellationRequested(); + var outcome = await RunAsync(operatorWitness, ticket, subject, group, cancellationToken).ConfigureAwait(false); + PlatformOperatorMetrics.DataRequest(PlatformOperations.ClosureFanOut, Token(outcome)); + reports.Add(new ClosureGroupReport(group, outcome)); + } + + return reports; + } + + /// One group's act: admitted, executed, and mapped to the group's closed outcome. + private async Task RunAsync(PlatformOperatorWitness operatorWitness, string? ticket, UserId subject, + ClosureParticipantGroup group, CancellationToken cancellationToken) + { + try + { + var admitted = await gate.AdmitAsync(operatorWitness, PlatformOperations.ClosureFanOut, ticket, cancellationToken) + .ConfigureAwait(false); + if (admitted.Admission is not { } admission) + { + // The gate counted and logged the refusal by its cause; the group is not started. + LogFailed(logger, "admission_" + admitted.Refusal.ToString()); + return ClosureGroupOutcome.Failed; + } + + var result = await executor.ExecuteAsync(admission, group.TenantId, group.OrganizationId, + new FanOutClosureCommand(subject, group.OrganizationId), cancellationToken).ConfigureAwait(false); + if (result.IsFailure) + { + // The act's own MUST row records the refusal; the reason here is the closed key, never a detail. + var reason = result.Error!.Details is { } details && details.Values.SelectMany(keys => keys).FirstOrDefault() is { } key + ? key.Key : result.Error.Message.Key; + LogFailed(logger, reason); + return ClosureGroupOutcome.Failed; + } + + var outcome = result.Value; + if (outcome is not (ClosureGroupOutcome.Started or ClosureGroupOutcome.Adopted or ClosureGroupOutcome.Waiting)) + { + throw new InvalidOperationException("A closure's fan-out act answers started, adopted or waiting."); + } + + var token = Token(outcome); + LogFinished(logger, token); + return outcome; + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } +#pragma warning disable CA1031 // A group that throws is that group's failure; the remaining groups still run (ADR-0107 § 7). + catch (Exception failure) +#pragma warning restore CA1031 + { + LogFailed(logger, failure.GetType().Name); + return ClosureGroupOutcome.Failed; + } + } + + private static string Token(ClosureGroupOutcome outcome) => outcome switch + { + ClosureGroupOutcome.Started => "fan_out_started", + ClosureGroupOutcome.Adopted => "fan_out_adopted", + ClosureGroupOutcome.Waiting => "fan_out_waiting", + _ => "fan_out_failed", + }; + + [LoggerMessage(EventId = 7541, Level = LogLevel.Information, Message = "Closure fan-out group finished ({Outcome}).")] + private static partial void LogFinished(ILogger logger, string outcome); + + [LoggerMessage(EventId = 7542, Level = LogLevel.Warning, + Message = "Closure fan-out group failed ({Reason}); a repeated Begin retries it.")] + private static partial void LogFailed(ILogger logger, string reason); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataErasureJobRegistration.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataErasureJobRegistration.cs new file mode 100644 index 000000000..805b5b8d7 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataErasureJobRegistration.cs @@ -0,0 +1,35 @@ +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.SharedKernel.Jobs; + +namespace LearnStack.Modules.Identity.Infrastructure.DataRequests; + +/// +/// The tenant-side erasure's two transactional definitions and their two ordinary roots +/// (ADR-0107 § 2, § 5): +/// once for the tenant-wide group and once for an organization group, version 1, identifier-only parameters, the +/// transactional queue and no capacity group. Each is submitted with ScheduleAsync at the end of the request's +/// cancellable window. +/// +/// +/// They join the Identity module's one job registry in InvitationEmailRegistration.CreateRegistry, beside the +/// export workflow's, because the runtime holds exactly one registry for every definition. +/// +public static class DataErasureJobRegistration +{ + public static IReadOnlyList Definitions { get; } = + [ + Definition(DataErasureJobKeys.TenantErasure.Value, BackgroundJobScope.TenantWide, typeof(RunTenantDataErasureCommand)), + Definition(DataErasureJobKeys.OrganizationErasure.Value, BackgroundJobScope.Organization, typeof(RunOrganizationDataErasureCommand)), + ]; + + public static IReadOnlyList Requests { get; } = + [ + new(typeof(RunTenantDataErasureCommand), BackgroundJobRequestClassification.Ordinary, BackgroundJobScope.TenantWide), + new(typeof(RunOrganizationDataErasureCommand), BackgroundJobRequestClassification.Ordinary, BackgroundJobScope.Organization), + ]; + + private static BackgroundJobDefinitionRegistration Definition(string key, BackgroundJobScope scope, Type root) => + new(key, typeof(DataErasureJobHandlers), typeof(DataErasureJobParameters), scope, BackgroundJobDefinitionReadiness.Active, + "transactional", BackgroundJobProfileRegistration.Transactional(root)); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataExportCustodyRefusals.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataExportCustodyRefusals.cs new file mode 100644 index 000000000..c75b94c7b --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataExportCustodyRefusals.cs @@ -0,0 +1,42 @@ +namespace LearnStack.Modules.Identity.Infrastructure.DataRequests; + +/// +/// Which custody refusals this process has already reported at critical severity, so that a stored chunk that cannot +/// be opened pages once per artifact and key label and its repeats are warnings +/// (data export runbook). +/// +/// +/// A download reads every chunk of an artifact, and a subject retries; one lost key would otherwise page once per +/// chunk read. The memory is one per process (a singleton), holds identifiers and non-secret labels only, and is +/// bounded: past distinct pairs it is cleared, so a refusal reported long ago is reported +/// at critical severity again rather than the set growing without limit. +/// +public sealed class DataExportCustodyRefusals +{ + /// The most distinct (artifact, key label) pairs remembered before the memory is cleared. + public const int Capacity = 256; + + private readonly HashSet<(Guid ArtifactId, string KeyLabel)> _reported = []; + private readonly Lock _gate = new(); + + /// + /// Whether this is the first refusal of the artifact under the label since the process started or the memory was + /// last cleared; the pair is remembered either way. + /// + public bool IsFirst(Guid artifactId, string keyLabel) + { + ArgumentNullException.ThrowIfNull(keyLabel); + var pair = (artifactId, keyLabel); + lock (_gate) + { + if (_reported.Count >= Capacity && !_reported.Contains(pair)) + { + _reported.Clear(); + } + + return _reported.Add(pair); + } + } + + public override string ToString() => nameof(DataExportCustodyRefusals); +} 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 000000000..9fceb96b0 --- /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/DataExportTicketStore.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataExportTicketStore.cs new file mode 100644 index 000000000..cc5b819ff --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataExportTicketStore.cs @@ -0,0 +1,133 @@ +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); + } + + public async Task CountAsync(DataExportArtifactId artifactId, string sessionBindingDigest, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(sessionBindingDigest); + Admit(); + if (sessionBindingDigest.Length != 64 || !sessionBindingDigest.All(char.IsAsciiHexDigitLower)) + { + throw new ArgumentException("A session binding is a lowercase hexadecimal SHA-256 digest.", nameof(sessionBindingDigest)); + } + + // Expiry by the database clock, as the ticket guard judges it; the tenant and artifact lead the ticket index, and + // an artifact holds at most DataRequestLimits.MaximumTicketsPerArtifact rows. + await using var command = DataRequestSql.Command(unit, tenant, """ + SELECT count(*) FILTER (WHERE session_binding_digest=@binding AND consumed_at IS NULL AND clock_timestamp() < expires_at), + count(*) + FROM public.data_export_tickets + WHERE tenant_id=@tenant AND organization_id IS NOT DISTINCT FROM @organization AND artifact_id=@artifact + """); + command.Parameters.AddWithValue("artifact", artifactId.Value); + command.Parameters.AddWithValue("binding", NpgsqlDbType.Bytea, Convert.FromHexString(sessionBindingDigest)); + return await DataRequestSql.ExecuteAsync(unit, async token => + { + await using var row = await command.ExecuteReaderAsync(token).ConfigureAwait(false); + return await row.ReadAsync(token).ConfigureAwait(false) + ? new DataExportTicketCounts(checked((int)row.GetInt64(0)), checked((int)row.GetInt64(1))) + : throw new InfrastructureException("Data request storage unavailable."); + }, 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 (!DataRequestOwner.IsAnnounced(unit, tenant, writable: true)) + { + 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 new file mode 100644 index 000000000..6f4d3df51 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestJobPhaseReader.cs @@ -0,0 +1,161 @@ +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; + +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 or erasure 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 +{ + /// + /// One request's newest job by its exact route. A constant so the plan test explains exactly this statement; the + /// index it seeks is ix_background_jobs_definition. + /// + internal const string SingleStatement = """ + 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 + """; + + /// A page's newest job per request, by the same exact route, in one statement; planned like the single read. + internal const string PageStatement = """ + 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 + """; + + public async Task ReadAsync(DataSubjectRequestId requestId, DataRequestKind kind, CancellationToken cancellationToken) + { + RequireOwner(); + if (Route(kind) is not { } definition) + { + return DataRequestJobPhase.Unavailable; + } + + await using var command = DataRequestSql.Command(unit, tenant, SingleStatement); + command.Parameters.AddWithValue("definition", definition); + command.Parameters.AddWithValue("parameters", Parameters(requestId, kind)); + using var budget = DataRequestSql.Budget(cancellationToken); + 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."); + } + } + + public async Task> ReadManyAsync( + IReadOnlyCollection requestIds, DataRequestKind kind, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(requestIds); + RequireOwner(); + if (requestIds.Count > 101) + { + throw new InvalidOperationException("A data request job phase page reads at most 101 requests."); + } + + var phases = requestIds.Distinct().ToDictionary(id => id, _ => DataRequestJobPhase.Unavailable); + if (phases.Count == 0 || Route(kind) is not { } definition) + { + return phases; + } + + var routed = phases.Keys.ToDictionary(id => Parameters(id, kind), id => id, StringComparer.Ordinal); + + // One statement for the page, newest job per request, by the same exact route as the single read. + await using var command = DataRequestSql.Command(unit, tenant, PageStatement); + command.Parameters.AddWithValue("definition", definition); + command.Parameters.AddWithValue("parameters", routed.Keys.ToArray()); + using var budget = DataRequestSql.Budget(cancellationToken); + try + { + await using var row = await command.ExecuteReaderAsync(budget.Token).ConfigureAwait(false); + while (await row.ReadAsync(budget.Token).ConfigureAwait(false)) + { + if (routed.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; + } + + /// The definition key of the kind's fulfilment job in the announced group; a closure has none in this step. + private string? Route(DataRequestKind kind) + { + var group = new DataRequestScopeGroup(tenant.TenantId, tenant.OrganizationId); + return kind switch + { + DataRequestKind.Export => DataExportJobKeys.ExportFor(group).Value, + DataRequestKind.Erasure => DataErasureJobKeys.ErasureFor(group).Value, + _ => null, + }; + } + + /// The canonical stored parameters of the request's own fulfilment job. + private static string Parameters(DataSubjectRequestId requestId, DataRequestKind kind) => kind == DataRequestKind.Erasure + ? BackgroundJobPayloadContract.Serialize(new DataErasureJobParameters(requestId.Value), typeof(DataErasureJobParameters), + BackgroundJobPayloadKind.Parameters) + : BackgroundJobPayloadContract.Serialize(new DataExportJobParameters(requestId.Value), typeof(DataExportJobParameters), + BackgroundJobPayloadKind.Parameters); + + private void RequireOwner() + { + if (!DataRequestOwner.IsAnnounced(unit, tenant, writable: false)) + { + 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 + { + (_, 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/DataRequestOperatorOperations.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestOperatorOperations.cs new file mode 100644 index 000000000..7a007e0b6 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestOperatorOperations.cs @@ -0,0 +1,429 @@ +using System.Collections.Frozen; +using System.Data.Common; +using System.Globalization; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using LearnStack.Infrastructure.Messaging; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Pagination; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; + +namespace LearnStack.Modules.Identity.Infrastructure.DataRequests; + +/// +/// The confined owner of the operator's data-request acts (ADR-0107 § 8, ADR-0108): the metadata-only inspection of the +/// work that needs a person, and the completion of an erasure's privileged step. +/// +/// +/// +/// The database bounds what it reads. Each call is one entered platform scope on learnstack_platform, +/// which holds a closed-column SELECT of the request and artifact tables and nothing on their tickets and +/// chunks, so a statement that named a requester, an actor stamp, an artifact's subject or its key version would be +/// refused by PostgreSQL. The inspection's own projection is narrower still: it selects no subject, snapshot, progress +/// or result, although the completion reads the subject, the snapshot and the result of the one request it completes +/// (the role is granted them for that). An inspection reads and changes nothing, so its audit is the scope's entry row +/// and it ends by disposal. +/// +/// +/// A completion is one transaction. The request is locked and read whole, the plan is built from that row and +/// never from the caller, the Audit-owned executor redacts on the scope's transaction, the request moves to +/// completed under the request guard's platform arm, and the result row names the request's own tenant; all of +/// it commits together or nothing does (ADR-0108 § 8). A request already completed answers its recorded result and +/// writes no second row; two concurrent completions serialize on the row lock and the second finds the first's, provided +/// the first finishes within the second's command timeout (the redaction takes time in proportion to the audit volume). +/// +/// +/// Failures. A transient database fault before the commit is the unavailable owner, safe to repeat because the +/// redaction is idempotent; any failure once the commit was sent is the unknown outcome. Anything else, a refused +/// credential or a missing grant included, is the defect it is. +/// +/// +public sealed class DataRequestOperatorOperations(IPlatformAdminScope scope) : IDataRequestOperatorOperations +{ + private const int MaximumLimit = CursorPagination.MaxLimit; + private const string EntityType = "DataSubjectRequest"; + + /// + /// The four retained kinds the audit log holds (ADR-0107 § 6, ADR-0108 § 4): the redaction's report sets these, and + /// the request guard's platform arm refuses a completion that changes any other kind of the tenant side's record. + /// + private static readonly FrozenSet AuditKinds = new[] + { + RetainedReferenceKind.AuditActorReference, RetainedReferenceKind.AuditEntityReference, + RetainedReferenceKind.AuditMetadataReference, RetainedReferenceKind.UnscopedAuditRows, + }.ToFrozenSet(); + + private const string RequestColumns = + "r.id, r.tenant_id, r.organization_id, r.kind, r.origin, r.status, r.created_at, r.execute_at, r.completed_at, " + + "r.last_refusal, r.failure_reason"; + + // The ordering key of the three request lists: when the request fell due. An erasure or closure falls due when its + // window ends and the rest when they are filed; a request cannot have started work before it, so a stuck one is + // never missed. The text is the index's expression, character for character, or the planner cannot use the index. + private const string DueAt = "COALESCE(r.execute_at, r.created_at)"; + + private const string LockRequest = """ + SELECT id, tenant_id, organization_id, kind, origin, subject_user_id, status, membership_snapshot::text, + result::text, row_version, completed_at + FROM data_subject_requests WHERE id = @id FOR UPDATE + """; + + // The guard's platform arm stamps completed_at, updated_at and updated_by from the database clock and the system + // actor, so the statement sets only what the operator decides: the arrow, the merged result and the version step. + private const string Complete = """ + UPDATE data_subject_requests SET status = 'completed', result = @result::jsonb, row_version = row_version + 1 + WHERE id = @id AND kind = 'erasure' AND status = 'awaiting_privileged_step' AND row_version = @version + RETURNING completed_at + """; + + /// + /// The statement of one inspection page. It is exposed so that a test can ask PostgreSQL for the plan of the text + /// the inspection really runs: every list must be an ordered scan of its partial index, with no sort. + /// + public static string InspectionSql(DataRequestInspectionState state, bool afterCursor) => state switch + { + DataRequestInspectionState.AwaitingPrivilegedStep => RequestPage("awaiting_privileged_step", null, afterCursor), + DataRequestInspectionState.OverdueScheduled => RequestPage("scheduled", "now()", afterCursor), + DataRequestInspectionState.StuckFulfilling => RequestPage("fulfilling", "now() - @stuck", afterCursor), + DataRequestInspectionState.ExpiredArtifact => + $"SELECT {RequestColumns}, a.id, a.status, a.expires_at FROM data_export_artifacts a " + + "JOIN data_subject_requests r ON r.tenant_id = a.tenant_id AND r.id = a.request_id " + + "WHERE a.status IN ('available', 'expired') AND a.expires_at <= now()" + + (afterCursor ? " AND (a.expires_at, a.id) > (@after, @key)" : string.Empty) + + " ORDER BY a.expires_at, a.id LIMIT @size", + _ => throw new ArgumentOutOfRangeException(nameof(state), "The inspection lists only its four closed states."), + }; + + private static string RequestPage(string status, string? dueBy, bool afterCursor) => + $"SELECT {RequestColumns}, NULL::uuid, NULL::text, NULL::timestamptz FROM data_subject_requests r " + + $"WHERE r.status = '{status}'" + + (dueBy is null ? string.Empty : $" AND {DueAt} <= {dueBy}") + + (afterCursor ? $" AND ({DueAt}, r.id) > (@after, @key)" : string.Empty) + + $" ORDER BY {DueAt}, r.id LIMIT @size"; + + /// + public async Task?> InspectAsync( + PlatformAdmission admission, DataRequestInspectionQuery query, CancellationToken cancellationToken = default) + { + RequireOperation(admission, PlatformOperations.DataRequestInspect); + ArgumentNullException.ThrowIfNull(query); + var state = Enum.IsDefined(query.State) + ? query.State + : throw new ArgumentOutOfRangeException(nameof(query), "The inspection lists only its four closed states."); + var size = Math.Clamp(query.Limit, 1, MaximumLimit); + var scopeKey = state.ToString(); + long? after = null; + var key = Guid.Empty; + if (query.Cursor is not null) + { + if (!TryDecode(query.Cursor, scopeKey, out var ticks, out key)) + { + return null; + } + + after = ticks; + } + + var parameters = new List { new("size", size + 1) }; + if (state == DataRequestInspectionState.StuckFulfilling) + { + parameters.Add(new PlatformSqlParameter("stuck", DataRequestLimits.StuckFulfillingAfter)); + } + + if (after is { } position) + { + parameters.Add(new PlatformSqlParameter("after", new DateTimeOffset(position, TimeSpan.Zero))); + parameters.Add(new PlatformSqlParameter("key", key)); + } + + IReadOnlyList rows; + try + { + await using var handle = await scope.EnterAsync(admission, cancellationToken).ConfigureAwait(false); + rows = await handle.QueryAsync(InspectionSql(state, after is not null), parameters, MapItem, cancellationToken) + .ConfigureAwait(false); + } + catch (Exception failure) when (OperatorRecoveryFaults.IsTransientDatabaseFault(failure, cancellationToken)) + { + // A read is safe to repeat; the cause is for the route's log, never for the response. + throw new OperatorRecoveryUnavailableException(cause: failure); + } + + var items = rows.Take(size).ToList(); + var next = rows.Count > size && items.Count > 0 ? Encode(scopeKey, items[^1], state) : null; + return new InspectionPage(items, next); + } + + /// + public async Task CompleteErasureAsync( + PlatformAdmission admission, Guid requestId, CancellationToken cancellationToken = default) + { + RequireOperation(admission, PlatformOperations.ErasureComplete); + if (requestId == Guid.Empty) + { + throw new ArgumentException("An erasure completion names a request.", nameof(requestId)); + } + + var commitSent = false; + try + { + return await CompleteCoreAsync(admission, requestId, () => commitSent = true, cancellationToken); + } + catch (Exception failure) when (commitSent && !IsFatal(failure)) + { + // The commit was sent: it may have landed, so this is never "nothing changed, repeat it". A repeat after a + // landed commit answers the recorded result with no second row, which is how the operator finds out. + throw new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true, cause: failure); + } + catch (Exception failure) when (!commitSent && OperatorRecoveryFaults.IsTransientDatabaseFault(failure, cancellationToken)) + { + // Nothing committed, and the redaction's statements are idempotent, so a repeat is safe. + throw new OperatorRecoveryUnavailableException(cause: failure); + } + } + + private async Task CompleteCoreAsync( + PlatformAdmission admission, Guid requestId, Action sendingCommit, CancellationToken cancellationToken) + { + await using var handle = await scope.EnterAsync(admission, cancellationToken); + + // 1. The request, whole and locked: a concurrent completion waits here and then reads the committed outcome. + var rows = await handle.QueryAsync(LockRequest, [new PlatformSqlParameter("id", requestId)], ReadRequest, cancellationToken); + if (rows.Count == 0) + { + return new ErasureCompletionResult(ErasureCompletionOutcome.NotFound); + } + + var request = rows[0]; + var status = DataRequestCodes.Statuses.ToCode(request.Status); + if (request.Kind != DataRequestKind.Erasure) + { + return new ErasureCompletionResult(ErasureCompletionOutcome.NotErasure, request.Tenant, status); + } + + if (request.Origin == DataRequestOrigin.ClosureFanout) + { + // ADR-0107 § 7: a closure's fan-out erasure is completed by that closure's finalization, which also redacts the + // sentinel tenant and removes the provider account; completing it alone would leave the closure unfinished. + return new ErasureCompletionResult(ErasureCompletionOutcome.ClosureFanout, request.Tenant, status); + } + + if (request.Status == DataRequestStatus.Completed) + { + // ADR-0108 § 8: a re-run after the commit returns the recorded result with no second row. The scope ends by + // disposal, which writes nothing beyond its entry row. + return new ErasureCompletionResult( + ErasureCompletionOutcome.AlreadyCompleted, request.Tenant, status, request.CompletedAt, Codes(request.Retained)); + } + + if (request.Status != DataRequestStatus.AwaitingPrivilegedStep) + { + return new ErasureCompletionResult(ErasureCompletionOutcome.NotAwaiting, request.Tenant, status); + } + + // 2. The redaction, from the row's immutable subject, group, origin and snapshot, on this transaction. + var report = await handle.RedactAuditAsync(new AuditRedactionPlan(request.Subject()), cancellationToken); + var retained = Merge(request.Retained, report); + + // 3. The arrow, under the guard's platform arm, exactly once. + var completed = await handle.QueryAsync( + Complete, + [ + new PlatformSqlParameter("id", requestId), + new PlatformSqlParameter("version", request.Version), + new PlatformSqlParameter("result", ResultJson(retained)), + ], + reader => reader.GetFieldValue(0), + cancellationToken); + if (completed.Count != 1) + { + throw new InvalidOperationException( + "The locked erasure did not complete in exactly one row, so no result row describes it; the act is abandoned."); + } + + // 4. The MUST row, under the request's real tenant: the tenant reads it, so it has no ticket and no actor. + await handle.WriteResultAsync( + new PlatformResult( + TenantId.From(request.Tenant), + EntityType, + requestId.ToString("D", CultureInfo.InvariantCulture), + StatusState(request.Status), + AfterState(report)), + cancellationToken); + + // Past the point where the caller's abort matters: a cancelled commit leaves its outcome unknown. + sendingCommit(); + await handle.CommitAsync(CancellationToken.None); + return new ErasureCompletionResult( + ErasureCompletionOutcome.Completed, request.Tenant, DataRequestCodes.Statuses.ToCode(DataRequestStatus.Completed), + completed[0], Codes(retained), report); + } + + /// + /// The tenant side's record with the audit log's kinds set from the report. A kind the report leaves out keeps its + /// recorded count, because a report's list is partial and an absent kind is not zero. + /// + private static SortedDictionary Merge( + IReadOnlyDictionary recorded, AuditRedactionReport report) + { + var merged = new SortedDictionary(); + foreach (var (kind, count) in recorded) + { + merged[kind] = count; + } + + foreach (var entry in report.Retained) + { + if (!AuditKinds.Contains(entry.Kind)) + { + throw new InvalidOperationException( + "The redaction reported a retained kind the audit log does not hold; the act is abandoned."); + } + + merged[entry.Kind] = entry.Count; + } + + return merged; + } + + private static string ResultJson(IReadOnlyDictionary retained) + { + var json = new JsonObject(); + foreach (var (kind, count) in retained) + { + json[DataRequestCodes.RetainedKinds.ToCode(kind)] = count; + } + + return json.ToJsonString(); + } + + private static Dictionary Codes(IReadOnlyDictionary retained) => + retained.ToDictionary(entry => DataRequestCodes.RetainedKinds.ToCode(entry.Key), entry => entry.Value, StringComparer.Ordinal); + + private static string StatusState(DataRequestStatus status) => + new JsonObject { ["status"] = DataRequestCodes.Statuses.ToCode(status) }.ToJsonString(); + + /// + /// The closed report with the new status: counts per column and per kind, never a person identifier. + /// + private static string AfterState(AuditRedactionReport report) + { + var after = JsonNode.Parse(report.ToClosedJson())!.AsObject(); + after.Insert(0, "status", DataRequestCodes.Statuses.ToCode(DataRequestStatus.Completed)); + return after.ToJsonString(); + } + + private static LockedRequest ReadRequest(DbDataReader reader) + { + var snapshot = new List(); + using (var document = JsonDocument.Parse(reader.GetString(7))) + { + foreach (var member in document.RootElement.EnumerateArray()) + { + snapshot.Add(Guid.Parse(member.GetString()!, CultureInfo.InvariantCulture)); + } + } + + var retained = new Dictionary(); + using (var document = JsonDocument.Parse(reader.GetString(8))) + { + foreach (var entry in document.RootElement.EnumerateObject()) + { + retained[DataRequestCodes.RetainedKinds.Parse(entry.Name)] = entry.Value.GetInt64(); + } + } + + return new LockedRequest( + reader.GetGuid(0), reader.GetGuid(1), reader.IsDBNull(2) ? null : reader.GetGuid(2), + DataRequestCodes.Kinds.Parse(reader.GetString(3)), DataRequestCodes.Origins.Parse(reader.GetString(4)), + reader.GetGuid(5), DataRequestCodes.Statuses.Parse(reader.GetString(6)), snapshot, retained, reader.GetInt64(9), + reader.IsDBNull(10) ? null : reader.GetFieldValue(10)); + } + + private static DataRequestInspectionItem MapItem(DbDataReader reader) => new( + reader.GetGuid(0), reader.GetGuid(1), reader.IsDBNull(2) ? null : reader.GetGuid(2), + DataRequestCodes.Kinds.ToCode(DataRequestCodes.Kinds.Parse(reader.GetString(3))), + DataRequestCodes.Origins.ToCode(DataRequestCodes.Origins.Parse(reader.GetString(4))), + DataRequestCodes.Statuses.ToCode(DataRequestCodes.Statuses.Parse(reader.GetString(5))), + reader.GetFieldValue(6), + reader.IsDBNull(7) ? null : reader.GetFieldValue(7), + reader.IsDBNull(8) ? null : reader.GetFieldValue(8), + reader.IsDBNull(9) ? null : DataRequestCodes.Refusals.ToCode(DataRequestCodes.Refusals.Parse(reader.GetString(9))), + reader.IsDBNull(10) ? null : DataRequestCodes.FailureReasons.ToCode(DataRequestCodes.FailureReasons.Parse(reader.GetString(10))), + reader.IsDBNull(11) + ? null + : new DataExportArtifactInspection( + reader.GetGuid(11), + DataRequestCodes.ArtifactStatuses.ToCode(DataRequestCodes.ArtifactStatuses.Parse(reader.GetString(12))), + reader.GetFieldValue(13))); + + private static void RequireOperation(PlatformAdmission admission, PlatformOperation expected) + { + ArgumentNullException.ThrowIfNull(admission); + if (!ReferenceEquals(admission.Operation, expected)) + { + throw new ArgumentException("The admission is not for this data-request operation.", nameof(admission)); + } + } + + private static bool IsFatal(Exception failure) => failure is OutOfMemoryException or AccessViolationException or StackOverflowException; + + /// + /// The position after : its ordering instant and its own key, bound to the list. + /// + private static string Encode(string scopeKey, DataRequestInspectionItem item, DataRequestInspectionState state) + { + var (instant, key) = state == DataRequestInspectionState.ExpiredArtifact + ? (item.Artifact!.ExpiresAt, item.Artifact.ArtifactId) + : (item.ExecuteAt ?? item.CreatedAt, item.RequestId); + return Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Join( + '~', "v1", scopeKey, instant.UtcTicks.ToString(CultureInfo.InvariantCulture), key.ToString("D", CultureInfo.InvariantCulture)))) + .TrimEnd('=').Replace('+', '-').Replace('/', '_'); + } + + private static bool TryDecode(string cursor, string scopeKey, out long ticks, out Guid key) + { + ticks = 0; + key = Guid.Empty; + if (cursor.Length is 0 or > 512) + { + return false; + } + + try + { + var padded = cursor.Replace('-', '+').Replace('_', '/'); + padded = padded.PadRight(padded.Length + ((4 - padded.Length % 4) % 4), '='); + var parts = Encoding.UTF8.GetString(Convert.FromBase64String(padded)).Split('~'); + return parts is ["v1", var issuedFor, var instant, var position] + && string.Equals(issuedFor, scopeKey, StringComparison.Ordinal) + && long.TryParse(instant, NumberStyles.None, CultureInfo.InvariantCulture, out ticks) + && ticks <= DateTimeOffset.MaxValue.UtcTicks + && Guid.TryParseExact(position, "D", out key); + } + catch (FormatException) + { + return false; + } + } + + /// The request row the completion locked, read whole through the platform role's column grant. + private sealed record LockedRequest( + Guid Id, Guid Tenant, Guid? Organization, DataRequestKind Kind, DataRequestOrigin Origin, Guid SubjectUser, + DataRequestStatus Status, IReadOnlyList Snapshot, IReadOnlyDictionary Retained, + long Version, DateTimeOffset? CompletedAt) + { + /// The plan's subject, from the row's immutable snapshot and never from the caller. + internal UserDataSubject Subject() => new( + Id, Kind, Origin, UserId.From(SubjectUser), + new DataRequestScopeGroup(TenantId.From(Tenant), Organization is { } organization ? OrganizationId.From(organization) : null), + Snapshot); + + /// Never prints the subject or the snapshot. + public override string ToString() => nameof(LockedRequest); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestOwner.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestOwner.cs new file mode 100644 index 000000000..538cf7e07 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestOwner.cs @@ -0,0 +1,17 @@ +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Tenancy; + +namespace LearnStack.Modules.Identity.Infrastructure.DataRequests; + +/// +/// The announced-owner test the data-request adapters share: an active, not rollback-only transaction, writable when the +/// caller writes, announced for exactly the context's tenant and organization. Each adapter keeps its own refusal, so no +/// message or exception type changes with the sharing. +/// +internal static class DataRequestOwner +{ + internal static bool IsAnnounced(IUnitOfWork unit, ITenantContext tenant, bool writable) => + unit.HasActiveTransaction && !unit.IsRollbackOnly && (!writable || unit.Mode == TransactionMode.ReadWrite) + && unit.GetTenantContextAnnouncement(unit.Transaction) is { } announcement + && announcement.TenantId == tenant.TenantId && announcement.OrganizationId == tenant.OrganizationId; +} 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 000000000..eebbaf594 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestReader.cs @@ -0,0 +1,183 @@ +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: the + // subject's page walks the subject index, the administrator's the group's (tenant, organization, id) index. + 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); + var page = query.OrderByDescending(request => request.Id).Take(take); + // The receipt's columns only: the progress document never, the Membership snapshot only on the administrator's + // page, the one view that shows it. + var rows = subject is null + ? page.Select(request => new DataRequestReceiptRow(request.Id, request.Kind, request.Origin, request.Status, + request.SubjectUserId, request.RequesterUserId, request.CreatedAt, request.UpdatedAt, request.CompletedAt, + request.ExecuteAt, request.LastRefusal, request.FailureReason, request.ResultJson, request.MembershipSnapshotJson, + request.Version)) + : page.Select(request => new DataRequestReceiptRow(request.Id, request.Kind, request.Origin, request.Status, + request.SubjectUserId, request.RequesterUserId, request.CreatedAt, request.UpdatedAt, request.CompletedAt, + request.ExecuteAt, request.LastRefusal, request.FailureReason, request.ResultJson, null, request.Version)); + return await Guard(() => rows.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 = DataRequestSql.Statement(unit, "SELECT clock_timestamp()"); + 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 (!DataRequestOwner.IsAnnounced(unit, tenant, writable: false)) + { + 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 000000000..a2bfde799 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestSql.cs @@ -0,0 +1,57 @@ +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 +{ + /// The one statement budget of the data-request adapters: the command timeout and the cancellation window. + internal const int StatementBudgetSeconds = 5; + + /// A statement on the ambient transaction that binds no parameter, under the statement budget. + internal static NpgsqlCommand Statement(IUnitOfWork unit, string sql) => + new(sql, (NpgsqlConnection)unit.Connection, (NpgsqlTransaction)unit.Transaction!) { CommandTimeout = StatementBudgetSeconds }; + + internal static NpgsqlCommand Command(IUnitOfWork unit, ITenantContext tenant, string sql) + { + var command = Statement(unit, sql); + command.Parameters.AddWithValue("tenant", tenant.TenantId.Value); + command.Parameters.AddWithValue("organization", NpgsqlDbType.Uuid, (object?)tenant.OrganizationId?.Value ?? DBNull.Value); + return command; + } + + /// A cancellation window of the statement budget, linked to the caller's token. + internal static CancellationTokenSource Budget(CancellationToken cancellationToken) + { + var budget = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + budget.CancelAfter(TimeSpan.FromSeconds(StatementBudgetSeconds)); + return budget; + } + + internal static async Task ExecuteAsync(IUnitOfWork unit, 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 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 new file mode 100644 index 000000000..5c9080c97 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestStore.cs @@ -0,0 +1,320 @@ +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.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; + +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), + typeof(RunTenantDataErasureCommand), typeof(RunOrganizationDataErasureCommand), + ]; + + /// + /// The tenant's eligible tenant-wide administrators, split into the subject and everybody else: exactly the + /// administrator predicate of the deferred complete-graph guard (fn_identity_complete_graph_guard), so the + /// erasure that passes it cannot be refused by that guard for the same Membership state. The kernel grants are the + /// manifest's own values, the guard's literal. + /// + internal static readonly string AdministratorStanding = $""" + SELECT COALESCE(bool_or(member.user_id = @subject), false), COALESCE(bool_or(member.user_id <> @subject), false) + FROM public.memberships AS member + JOIN public.membership_role_assignments AS assignment + ON assignment.tenant_id = member.tenant_id AND assignment.membership_id = member.id + JOIN public.roles AS role ON role.tenant_id = assignment.tenant_id AND role.id = assignment.role_id + WHERE member.tenant_id = @tenant AND member.organization_id IS NULL + AND member.status = 'Active' AND member.deleted_at IS NULL AND member.deleted_by IS NULL + AND role.built_in_key = 'TenantAdmin' AND role.permission_scope = 'Tenant' + AND role.deleted_at IS NULL AND role.deleted_by IS NULL + AND NOT EXISTS (SELECT 1 FROM (VALUES {IdentityFoundationManifest.Version1.KernelSqlValues}) AS kernel(scope,permission_key) + WHERE NOT EXISTS (SELECT 1 FROM public.role_permission_grants AS grant_row + WHERE grant_row.tenant_id = role.tenant_id AND grant_row.role_id = role.id + AND grant_row.permission_scope = kernel.scope AND grant_row.permission_key = kernel.permission_key)) + """; + + private const string ActiveIndex = "ux_data_subject_requests_active"; + + /// + /// The request guard's refusal of a subject not in the status the request's origin allows (ADR-0107 § 7): the closed + /// message the migration installs, matched with its SQLSTATE so no other check violation is read as it. + /// + internal const string SubjectNotAdmittedMessage = "Data request subject is not admitted."; + + 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); + 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; + } + + /// + /// The row lock waits behind a running export job, which holds it for its whole transaction; a wait past the + /// five-second budget is the retryable (503), like every sibling read here. + /// + public async Task FindLockedAsync(DataSubjectRequestId requestId, CancellationToken cancellationToken) + { + Admit(); + await using var command = Command(""" + SELECT id FROM public.data_subject_requests + WHERE id=@id AND tenant_id=@tenant AND organization_id IS NOT DISTINCT FROM @organization FOR UPDATE + """); + command.Parameters.AddWithValue("id", requestId.Value); + if (await ExecuteAsync(token => command.ExecuteScalarAsync(token), cancellationToken).ConfigureAwait(false) is null) + { + return null; + } + + return await ExecuteAsync(token => db.DataSubjectRequests.SingleOrDefaultAsync(request => request.Id == requestId + && request.TenantId == tenant.TenantId && request.OrganizationId == tenant.OrganizationId, token), cancellationToken) + .ConfigureAwait(false); + } + + 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 HoldsReadableArtifactAsync(UserId subject, CancellationToken cancellationToken) + { + Admit(); + // Readability by the database clock, as the guards, the receipts and the chunk read judge it; the partial + // index of available artifacts holds at most one row per subject and group. + await using var command = Command(""" + SELECT EXISTS (SELECT 1 FROM public.data_export_artifacts + WHERE tenant_id=@tenant AND organization_id IS NOT DISTINCT FROM @organization AND subject_user_id=@subject + AND status='available' AND clock_timestamp() < expires_at) + """); + command.Parameters.AddWithValue("subject", subject.Value); + return await ExecuteAsync(token => command.ExecuteScalarAsync(token), cancellationToken).ConfigureAwait(false) is true; + } + + public async Task HoldsCompletedFanOutAsync(UserId subject, CancellationToken cancellationToken) + { + Admit(); + // The person's requests of the group, through the request subject index; a completed fan-out is terminal, so the + // one-active index does not bound it, and the EXISTS stops at the first. + await using var command = Command(""" + SELECT EXISTS (SELECT 1 FROM public.data_subject_requests + WHERE tenant_id=@tenant AND organization_id IS NOT DISTINCT FROM @organization AND subject_user_id=@subject + AND kind='erasure' AND origin='closure_fanout' AND status='completed') + """); + command.Parameters.AddWithValue("subject", subject.Value); + return await ExecuteAsync(token => command.ExecuteScalarAsync(token), cancellationToken).ConfigureAwait(false) is true; + } + + 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."); + } + + await SaveChangesAsync(cancellationToken).ConfigureAwait(false); + } + + 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 HoldsCurrentMembershipAsync(UserId subject, CancellationToken cancellationToken) + { + Admit(); + // ux_memberships_current_scope is the (tenant, user, organization) index of exactly these rows. + await using var command = Command(""" + SELECT EXISTS (SELECT 1 FROM public.memberships + WHERE tenant_id=@tenant AND user_id=@subject AND organization_id IS NOT DISTINCT FROM @organization + AND deleted_at IS NULL AND status IN ('Active','Suspended')) + """); + command.Parameters.AddWithValue("subject", subject.Value); + return await ExecuteAsync(token => command.ExecuteScalarAsync(token), cancellationToken).ConfigureAwait(false) is true; + } + + public async Task IsSoleEligibleTenantAdministratorAsync(UserId subject, CancellationToken cancellationToken) + { + Admit(); + await using var command = Command(AdministratorStanding); + command.Parameters.AddWithValue("subject", subject.Value); + return await ExecuteAsync(async token => + { + await using var row = await command.ExecuteReaderAsync(token).ConfigureAwait(false); + return await row.ReadAsync(token).ConfigureAwait(false) && row.GetBoolean(0) && !row.GetBoolean(1); + }, cancellationToken).ConfigureAwait(false); + } + + public async Task HoldsErasureFencesAsync(UserId subject, CancellationToken cancellationToken) + { + Admit(); + // The same backend-local lock observation the contextual guards make; it reads pg_locks and nothing else. + await using var command = Command(""" + SELECT public.fn_identity_lock_held('user',@subject,true) AND public.fn_identity_lock_held('tenant',@tenant,true) + """); + command.Parameters.AddWithValue("subject", subject.Value); + return await ExecuteAsync(token => command.ExecuteScalarAsync(token), cancellationToken).ConfigureAwait(false) is true; + } + + 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 {DataSubjectRequestConfiguration.ActiveFilter} + 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 the store refuses is a storage refusal here. + async Task IAggregateWriteStore.AddAsync(DataSubjectRequest aggregate, + CancellationToken cancellationToken) + { + if (await TryAddAsync(aggregate, cancellationToken).ConfigureAwait(false) != DataRequestInsertion.Added) + { + throw new InfrastructureException("Data request not stored."); + } + } + + 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 DataRequestInsertion.Added; + } + 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 DataRequestInsertion.AlreadyActive; + } + catch (DbUpdateException failure) when (failure.InnerException is PostgresException + { + SqlState: PostgresErrorCodes.CheckViolation, MessageText: SubjectNotAdmittedMessage, + }) + { + // ADR-0107 § 7: the guard read the subject's User status under the User fence and refused it, so the person's + // account is closing or closed (or, for a fan-out, not closing). Nothing was stored and the transaction is aborted. + db.Entry(request).State = EntityState.Detached; + unit.MarkRollbackOnly(); + return DataRequestInsertion.SubjectNotAdmitted; + } + 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 (!DataRequestOwner.IsAnnounced(unit, tenant, writable: true)) + { + 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 000000000..fda6af442 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/IdentityUserDataParticipant.cs @@ -0,0 +1,388 @@ +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. +/// +/// +/// Bounds. memberships is bounded by the frozen snapshot and invitations_accepted by the offers a +/// person can accept; invitations_issued grows with administrative work, so it is written newest first under +/// and a cap hit is declared with the records +/// included and the records in total, as the audit section's is. +/// +/// +/// Erasure is 's, inside the erasure job's transaction (ADR-0107 § 5): the +/// participant only hands it the request's subject. +/// +/// +/// The retained report names what survives in the group, read after an erasure's writes: the request receipts, +/// the invitations the subject accepted or issued (invitation_record), attribution and, for the tenant-wide group, +/// the federation and provider-event references. Their invitation envelopes are retained too (ADR-0107 § 6), but the +/// application role holds no read of the envelope table, so that kind is not counted here and is absent from the +/// report rather than reported as zero. +/// +/// +public sealed class IdentityUserDataParticipant(IdentityDbContext db, ITenantContext tenant, + MembershipFieldRevisionReader fields, DataErasureService erasure) : IUserDataParticipant +{ + internal const string ParticipantKey = "identity"; + internal const string ThirdParty = "third_party"; + internal const string Self = "self"; + internal const string IssuedCollection = "invitations_issued"; + internal const string AcceptedCollection = "invitations_accepted"; + private const int Page = 200; + + /// + /// The request's own receipt rows, reported as request_receipt wherever any of their UserId columns + /// names the person (the subject, the requester, whoever created, cancelled or revoked them), once per row, and + /// therefore left out of attribution_reference so no row is reported twice. + /// + private static readonly IReadOnlySet ReceiptTypes = + new HashSet { typeof(DataSubjectRequest), typeof(DataExportArtifact), typeof(DataExportTicket) }; + + /// + /// The UserId columns that are a row's subject or party, not its author: the subject's own Membership is + /// exported, and the others are reported as invitation_record, federation_actor_reference and + /// provider_event_record; every other UserId column of the context is attribution. + /// + private static readonly (Type Entity, string Property)[] PartyProperties = + [ + (typeof(Membership), nameof(Membership.UserId)), + (typeof(Invitation), nameof(Invitation.InviterUserId)), + (typeof(Invitation), nameof(Invitation.AcceptedBy)), + (typeof(FederationConnection), nameof(FederationConnection.PendingActor)), + (typeof(FederationConnection), nameof(FederationConnection.TestActor)), + (typeof(ProviderEventTarget), nameof(ProviderEventTarget.AffectedUserId)), + ]; + + private static readonly IReadOnlyDictionary CollectionCaps = + new Dictionary(StringComparer.Ordinal) { [IssuedCollection] = DataRequestLimits.IssuedInvitationsCollectionBytes }; + + public string Key => ParticipantKey; + + public IReadOnlyDictionary ExportCollectionCapBytes => CollectionCaps; + + 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 Task EraseAsync(UserDataSubject subject, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(subject); + RequireGroup(subject); + return subject.Kind == DataRequestKind.Erasure + ? erasure.EraseAsync(subject, cancellationToken) + : throw new InvalidOperationException("Only an erasure request erases."); + } + + 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 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, + await AttributionReferenceCounter.CountNamingRowsAsync(db, subject, ReceiptTypes, cancellationToken).ConfigureAwait(false)), + new(RetainedReferenceKind.InvitationRecord, invitations), + new(RetainedReferenceKind.AttributionReference, + await AttributionReferenceCounter.CountAsync(db, subject, ReceiptTypes, PartyProperties, 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, oldest first; issued ones omit the invitee's and are + /// written newest first under their collection cap, whose hit is declared. + /// + 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 ? AcceptedCollection : IssuedCollection; + 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); + var ordered = accepted + ? query.OrderBy(invitation => invitation.CreatedAt).ThenBy(invitation => invitation.Id) + : query.OrderByDescending(invitation => invitation.CreatedAt).ThenByDescending(invitation => invitation.Id); + long included = 0; + for (var offset = 0; ; offset += Page) + { + // Bounded pages in a stable order on the one transaction; the caps and the bundle bound the total. + var page = await ordered.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.SectionCapReached) + { + // Counted after the pages, on the same transaction; the maximum keeps the statement coherent + // should a statement-level snapshot see fewer rows than were written. + var total = await query.LongCountAsync(cancellationToken).ConfigureAwait(false); + writer.DeclareTruncated(collection, included, Math.Max(total, included)); + return false; + } + + if (appended != UserDataExportAppend.Appended) + { + return false; + } + + included++; + } + + 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) => UserDataParticipantGuard.RequireGroup(subject, tenant); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/IdentityUserReferenceLocator.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/IdentityUserReferenceLocator.cs new file mode 100644 index 000000000..d18b03f76 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/IdentityUserReferenceLocator.cs @@ -0,0 +1,40 @@ +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.DataProtection; + +namespace LearnStack.Modules.Identity.Infrastructure.DataRequests; + +/// +/// Where the Identity module's audited aggregates hold a person or Membership reference in their audit snapshots +/// (ADR-0108 § 7). +/// +/// +/// Every copy is redactable except the key of a User or a Membership, which is the row's own entity_id. +/// The table rows these snapshots describe keep their references under ADR-0107 § 6 (a Membership tombstone, a +/// request receipt, a federation actor); the audit copies are not on ADR-0108 § 6's list of survivors. +/// +public sealed class IdentityUserReferenceLocator : IUserReferenceLocator +{ + public IReadOnlyCollection Redactable { get; } = + [ + .. UserReferenceDeclarations.Attribution(typeof(User), typeof(Membership), typeof(Role), typeof(Invitation), + typeof(FederationConnection), typeof(DataSubjectRequest), typeof(DataExportArtifact)), + new(typeof(Membership), UserReferencePath.Of(nameof(Membership.UserId)), UserReferenceKind.User), + new(typeof(Invitation), UserReferencePath.Of(nameof(Invitation.InviterUserId)), UserReferenceKind.User), + new(typeof(Invitation), UserReferencePath.Of(nameof(Invitation.AcceptedBy)), UserReferenceKind.User), + new(typeof(Invitation), UserReferencePath.Of(nameof(Invitation.ResultMembershipId)), UserReferenceKind.Membership), + new(typeof(FederationConnection), UserReferencePath.Of(nameof(FederationConnection.PendingActor)), UserReferenceKind.User), + new(typeof(FederationConnection), UserReferencePath.Of(nameof(FederationConnection.TestActor)), UserReferenceKind.User), + new(typeof(DataSubjectRequest), UserReferencePath.Of(nameof(DataSubjectRequest.SubjectUserId)), UserReferenceKind.User), + new(typeof(DataSubjectRequest), UserReferencePath.Of(nameof(DataSubjectRequest.RequesterUserId)), UserReferenceKind.User), + new(typeof(DataSubjectRequest), UserReferencePath.Elements(nameof(DataSubjectRequest.MembershipSnapshotJson)), + UserReferenceKind.Membership), + new(typeof(DataExportArtifact), UserReferencePath.Of(nameof(DataExportArtifact.SubjectUserId)), UserReferenceKind.User), + new(typeof(DataExportTicket), UserReferencePath.Of(nameof(DataExportTicket.CreatedBy)), UserReferenceKind.User), + ]; + + public IReadOnlyCollection Retained { get; } = + [ + UserReferenceDeclarations.OwnKey(typeof(User)), + UserReferenceDeclarations.OwnKey(typeof(Membership)), + ]; +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/PlatformIdentityFences.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/PlatformIdentityFences.cs new file mode 100644 index 000000000..620e4a81e --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/PlatformIdentityFences.cs @@ -0,0 +1,201 @@ +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; + +namespace LearnStack.Modules.Identity.Infrastructure.DataRequests; + +/// +/// The fences of a global account closure on the platform connection (ADR-0107 § 7): the person's exclusive User key, then +/// the exclusive key of every tenant in which the person holds a Membership of any status, ascending by key, each a +/// transaction-scoped advisory lock taken through the platform scope's statement facade. +/// +/// +/// +/// Why not . That port fences one tenant inside a tenant-announced application +/// transaction. A closure spans every tenant of the person on a connection that announces nothing, so this is a separate +/// acquirer with the same key derivation () and the same canonical order: Users before +/// tenants, each family ascending by its key. Its census leg sits beside +/// Identity_Membership_Invariants_Use_Fresh_Ordered_Locks, and this file is the one place that takes a User key and +/// then tenant keys on a platform connection. +/// +/// +/// The participants are read under the User fence. A Membership is admitted only under the person's exclusive User +/// key and is never deleted, so once that key is held the set of tenants, and the Memberships counted in each, cannot grow +/// before the tenant keys are taken. That holds only for a statement whose snapshot is taken after the key was granted, +/// which is what READ COMMITTED gives every statement; the acquirer refuses any other isolation before it takes a key. The +/// database is the witness of the rest: the users trigger exception and the request guard's closure arrows read the +/// keys this connection holds in pg_locks, and refuse the change without them. +/// +/// +/// The size is read with the participants. One grouped statement over the person's own Memberships answers every +/// participant group and how many Memberships of any status it holds, so the closure's bounds +/// () are judged under the User fence, before any tenant key: a person past them takes no tenant +/// key at all. +/// +/// +/// Two forms. takes every key, for a transaction that changes the User or a closure's +/// request, which the database admits only under all of them. takes the User key alone, for +/// Finalize's first transaction, which changes neither and only redacts: the participant tenants' own identity writes do +/// not wait for its redaction. +/// +/// +/// Bounded, and only for the transaction. The wait for every key is bounded by the transaction's own +/// lock_timeout, set first; a key not granted in time fails the statement with 55P03, which leaves the scope +/// to be abandoned, and the owner answers it as the retryable unavailable. Transaction-scoped keys end at the commit or the +/// rollback, so a second transaction (Finalize's) takes them again; no session-level lock is ever taken. +/// +/// +internal static class PlatformIdentityFences +{ + /// The most a closure waits for any one of its keys. + internal static readonly TimeSpan LockWait = TimeSpan.FromSeconds(3); + + /// + /// The most participant groups one closure is admitted for and reads (); + /// the read returns one more, so a person past it is seen and never fenced partially. + /// + internal const int MaximumGroups = ClosureLimits.MaximumParticipantGroups; + + private const string ReadCommitted = "SELECT pg_catalog.current_setting('transaction_isolation')"; + + private const string BoundTheWait = "SELECT pg_catalog.set_config('lock_timeout', '3s', true)"; + + private const string TakeExclusive = "SELECT pg_catalog.pg_advisory_xact_lock(@key)"; + + /// + /// Every group of the person, a Revoked tombstone's included, with how many Memberships of any status the person holds + /// there: one grouped statement over the person's own rows through ix_memberships_user_id, whose cost is those + /// rows, never a group's or a tenant's. The platform role reads the six granted columns of memberships and nothing else. + /// Exposed so that a test can ask for its plan. + /// + internal static string ParticipantsSql { get; } = """ + SELECT member.tenant_id, member.organization_id, count(*) FROM public.memberships AS member + WHERE member.user_id = @subject + GROUP BY member.tenant_id, member.organization_id + ORDER BY member.tenant_id, member.organization_id NULLS FIRST + LIMIT @limit + """; + + /// + /// Takes the person's User fence, reads the participant groups under it, and, when the closure is within its bounds, + /// takes every participant tenant's fence (with the closure request's own tenant) ascending by key, on + /// 's transaction. Past the bounds it takes no tenant key and says so. + /// + /// An entered platform scope; its transaction holds the keys until it ends. + /// The person. + /// The tenant the closure request lives in, which the request guard also fences. + /// Cancellation. + /// The groups read under the User fence and the tenants fenced, in the order they were taken. + internal static Task AcquireAsync( + IPlatformAdminScopeHandle handle, UserId subject, TenantId requestTenant, CancellationToken cancellationToken) => + AcquireCoreAsync(handle, subject, requestTenant, cancellationToken); + + /// + /// Takes the person's User fence alone and reads the participant groups under it: for a transaction that moves no User + /// and no closure request, so no participant tenant waits for it. + /// + /// An entered platform scope; its transaction holds the key until it ends. + /// The person. + /// Cancellation. + /// The groups read under the User fence; no tenant is fenced. + internal static Task AcquireUserAsync( + IPlatformAdminScopeHandle handle, UserId subject, CancellationToken cancellationToken) => + AcquireCoreAsync(handle, subject, requestTenant: null, cancellationToken); + + /// + /// The one body of both forms: the isolation check, the bound, the User key, the participants under it, and, for a + /// request tenant within the bounds, the tenant keys ascending. + /// + private static async Task AcquireCoreAsync( + IPlatformAdminScopeHandle handle, UserId subject, TenantId? requestTenant, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(handle); + var userKey = IdentityAdvisoryLockKey.ForUser(subject); + if (requestTenant is { } own) + { + _ = IdentityAdvisoryLockKey.ForTenant(own); + } + + var isolation = await handle.QueryAsync(ReadCommitted, null, reader => reader.GetString(0), cancellationToken); + if (isolation.Count != 1 || !string.Equals(isolation[0], "read committed", StringComparison.Ordinal)) + { + // A snapshot taken before the User key was granted could miss a Membership admitted just before it, and that + // tenant would be neither fenced nor judged. + throw new InvalidOperationException("A closure's fences are taken only in a READ COMMITTED transaction; the act is abandoned."); + } + + await handle.ExecuteAsync(BoundTheWait, null, cancellationToken); + await handle.ExecuteAsync(TakeExclusive, [new PlatformSqlParameter("key", userKey)], cancellationToken); + + var participants = await ReadParticipantsAsync(handle, subject, cancellationToken); + if (requestTenant is not { } request || !participants.WithinBounds) + { + return new PlatformIdentityFenceSet(subject, participants.Groups, [], participants.WithinBounds); + } + + var tenants = participants.Groups.Select(group => group.TenantId).Append(request).Distinct() + .OrderBy(IdentityAdvisoryLockKey.ForTenant).ToArray(); + foreach (var tenant in tenants) + { + await handle.ExecuteAsync( + TakeExclusive, [new PlatformSqlParameter("key", IdentityAdvisoryLockKey.ForTenant(tenant))], cancellationToken); + } + + return new PlatformIdentityFenceSet(subject, participants.Groups, tenants, WithinBounds: true); + } + + /// + /// The person's participant groups and whether the closure is within its bounds: at most one group past + /// is read, so a person past it is seen without reading every group. Fenced, inside the + /// acquirer; unfenced only for a person whose User is no longer Active, whom no Membership can be admitted for. + /// + /// The person has no Membership. + internal static async Task ReadParticipantsAsync( + IPlatformAdminScopeHandle handle, UserId subject, CancellationToken cancellationToken) + { + var rows = await handle.QueryAsync( + ParticipantsSql, + [new PlatformSqlParameter("subject", subject.Value), new PlatformSqlParameter("limit", MaximumGroups + 1)], + reader => (Group: new ClosureParticipantGroup( + TenantId.From(reader.GetGuid(0)), reader.IsDBNull(1) ? null : OrganizationId.From(reader.GetGuid(1))), + Memberships: reader.GetInt64(2)), + cancellationToken); + if (rows.Count == 0) + { + // A closure is filed in a group the person holds a Membership in, and Memberships are never deleted. + throw new InvalidOperationException("A closure's person holds no Membership; the act is abandoned."); + } + + var fullest = rows.GroupBy(row => row.Group.TenantId).Max(tenant => tenant.Sum(row => row.Memberships)); + var within = ClosureLimits.Admits(rows.Count, (int)Math.Min(fullest, int.MaxValue)); + return new ClosureParticipantRead([.. rows.Select(row => row.Group)], within); + } +} + +/// The participant groups read under the User fence, and whether the closure is within its bounds. +/// The groups in key order: every one when within the bounds, one past the group bound otherwise. +/// +/// Whether the groups and the Memberships of the fullest participant tenant are within . +/// +internal sealed record ClosureParticipantRead(IReadOnlyList Groups, bool WithinBounds) +{ + /// Never prints a group, which is the person's Membership. + public override string ToString() => nameof(ClosureParticipantRead); +} + +/// What the acquirer fenced. +/// The person whose User key is held. +/// The participant groups, read under the User key. +/// +/// The tenants whose keys are held, ascending by key; none for the User-only form, or when the closure is past its bounds. +/// +/// Whether the closure is within ; past them no tenant key was taken. +internal sealed record PlatformIdentityFenceSet( + UserId Subject, IReadOnlyList Groups, IReadOnlyList Tenants, bool WithinBounds) +{ + /// Never prints the person. + public override string ToString() => nameof(PlatformIdentityFenceSet); +} 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 000000000..e6663ad6c --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/PostgresDataExportArtifactStore.cs @@ -0,0 +1,347 @@ +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.Errors; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +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. The artifact is stamped, and its readability and the revoke-or-purge decision are judged, by the +/// database clock the guards use, so an artifact past its expiry is unreadable whether or not its purge ran and a +/// revocation never meets a creation stamp from a clock ahead of the database's. +/// +/// +/// Failures. A statement that fails or outlives its five-second budget leaves the owner rollback-only and is +/// the retryable ; a custody refusal of a stored chunk (a key the ring no longer +/// holds, or a chunk that fails authentication) is logged with identifiers only and answered as an absence, so the +/// subject meets the one uniform refusal and no secret or position leaves. The first refusal of an artifact under a +/// key label in this process is and its repeats (every further chunk, every retry) +/// are , through . +/// +/// +public sealed class PostgresDataExportArtifactStore(IdentityDbContext db, IUnitOfWork unit, ITenantContext tenant, + DataExportCipher cipher, IAuditSubject audit, DataExportCustodyRefusals refusals, ILogger logger) + : IDataExportArtifactStore +{ + private static readonly EventId CustodyRefusedEvent = new(3193, "DataExportChunkCustodyRefused"); + + private static readonly Action LogCustodyRefused = + LoggerMessage.Define(LogLevel.Critical, CustodyRefusedEvent, + "Data export chunk custody refused: tenant {TenantId}, artifact {ArtifactId}, chunk {ChunkIndex}, key version {KeyVersion}."); + + private static readonly Action LogCustodyRefusedAgain = + LoggerMessage.Define(LogLevel.Warning, CustodyRefusedEvent, + "Data export chunk custody refused again: tenant {TenantId}, artifact {ArtifactId}, chunk {ChunkIndex}, key version {KeyVersion}; reported at critical severity before."); + + /// + public bool CanOpen(string keyVersion) => cipher.HoldsKey(keyVersion); + + 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(); + } + + // The database clock stamps the artifact, as the guards judge it; the request's own last stamp is the floor the + // aggregate requires, so a request clock ahead of the database's still orders. + var now = await DatabaseNowAsync(cancellationToken).ConfigureAwait(false); + var floor = request.UpdatedAt ?? request.CreatedAt; + var created = DataExportArtifact.Create(DataExportArtifactId.From(put.ArtifactId), request, put.ByteCount, + cipher.ActiveKeyVersion, put.Truncations, now > floor ? now : floor, 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); + var stored = await ExecuteAsync(async token => + { + await using var row = await command.ExecuteReaderAsync(token).ConfigureAwait(false); + if (!await row.ReadAsync(token).ConfigureAwait(false)) + { + return (StoredChunk?)null; + } + + return new StoredChunk(row.GetGuid(0), row.GetInt32(1), + new DataExportSealedChunk(row.GetString(2), (byte[])row[3], (byte[])row[4], (byte[])row[5])); + }, cancellationToken).ConfigureAwait(false); + if (stored is null) + { + return null; + } + + byte[] plaintext; + try + { + plaintext = cipher.Open(new DataExportChunkBinding(tenant.TenantId.Value, stored.RequestId, artifact.ArtifactId, index, + stored.Count), stored.Chunk); + } + catch (ObjectDisposedException) + { + // The host is stopping and the key ring has been cleared: retryable, nothing was disclosed. + throw Unavailable(); + } + catch (Exception failure) when (failure is InvalidOperationException or ArgumentException) + { + // A key the ring no longer holds, or a chunk moved, altered or sealed under another binding: the stored bundle + // cannot be served. The label is a non-secret ring version, never key material. + var label = DataRequestLimits.IsKeyVersion(stored.Chunk.KeyVersion) ? stored.Chunk.KeyVersion : "invalid"; + (refusals.IsFirst(artifact.ArtifactId, label) ? LogCustodyRefused : LogCustodyRefusedAgain)( + logger, tenant.TenantId.Value, artifact.ArtifactId, index, label, null); + return null; + } + + return new DataExportPlaintextChunk(index, stored.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. + unit.MarkRollbackOnly(); + throw Unavailable(); + } + + // The transition is stored first: the chunk guard deletes ciphertext only of an artifact that is no longer + // available, and the deferred completeness check demands that none is left when the transaction commits. + await SaveAsync(cancellationToken).ConfigureAwait(false); + 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); + } + + 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 = DataRequestSql.Statement(unit, "SELECT clock_timestamp()"); + 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) => DataRequestSql.Command(unit, tenant, sql); + + private async Task ExecuteAsync(Func> statement, CancellationToken cancellationToken) + { + using var budget = DataRequestSql.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 void RequireGroup(DataRequestScopeGroup group, bool writable) + { + ArgumentNullException.ThrowIfNull(group); + if (group.TenantId != tenant.TenantId || group.OrganizationId != tenant.OrganizationId + || !DataRequestOwner.IsAnnounced(unit, tenant, writable)) + { + 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 InfrastructureException Unavailable() => new("Data export artifact storage unavailable."); + + private sealed record StoredChunk(Guid RequestId, int Count, DataExportSealedChunk Chunk) + { + public override string ToString() => nameof(StoredChunk); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Invitations/InvitationAdministrationStore.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Invitations/InvitationAdministrationStore.cs index 33c0faa48..70f068b6b 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Invitations/InvitationAdministrationStore.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Invitations/InvitationAdministrationStore.cs @@ -2,6 +2,7 @@ using LearnStack.Modules.Identity.Domain; using LearnStack.Modules.Identity.Infrastructure.Persistence; using LearnStack.SharedKernel.Errors; +using LearnStack.SharedKernel.Identifiers; using LearnStack.SharedKernel.Permissions; using LearnStack.SharedKernel.Persistence; using LearnStack.SharedKernel.Tenancy; @@ -62,6 +63,37 @@ public async Task> ReadRolesAsync(CancellationToken cancella } catch (NpgsqlException) { unit.MarkRollbackOnly(); throw new InfrastructureException("Invitation administration storage unavailable."); } } + public async Task> FindPendingIssuedLockedAsync(UserId inviter, int take, CancellationToken cancellationToken) + { + Admit(); + if (take is < 1 or > 101) throw new ArgumentOutOfRangeException(nameof(take)); + control.PrepareFreshRead(); + try + { + // ix_invitations_inviter_user_id narrows to the person's issued offers; the tenant, group and status filter + // that short list. The rows stay locked against a concurrent administrator until the erasure commits. + await using var command = new NpgsqlCommand(""" + SELECT public.fn_identity_assert_tenant_fence(@tenant,false); + SELECT id FROM public.invitations WHERE inviter_user_id=@inviter AND tenant_id=@tenant + AND organization_id IS NOT DISTINCT FROM @org AND status='Pending' AND deleted_at IS NULL + ORDER BY id LIMIT @take FOR NO KEY UPDATE; + """, (NpgsqlConnection)unit.Connection, (NpgsqlTransaction)unit.Transaction!) { CommandTimeout = 5 }; + command.Parameters.AddWithValue("tenant", context.TenantId.Value); + command.Parameters.AddWithValue("inviter", inviter.Value); + command.Parameters.AddWithValue("org", NpgsqlDbType.Uuid, (object?)context.OrganizationId?.Value ?? DBNull.Value); + command.Parameters.AddWithValue("take", take); + var ids = new List(take); + await using (var row = await command.ExecuteReaderAsync(cancellationToken)) + { + await row.NextResultAsync(cancellationToken); + while (await row.ReadAsync(cancellationToken)) ids.Add(InvitationId.From(row.GetGuid(0))); + } + if (ids.Count == 0) return []; + return await Scoped.Where(row => ids.Contains(row.Id) && row.Status == InvitationStatus.Pending) + .OrderBy(row => row.Id).ToArrayAsync(cancellationToken); + } + catch (NpgsqlException) { unit.MarkRollbackOnly(); throw new InfrastructureException("Invitation administration storage unavailable."); } + } public Task AddAsync(Invitation aggregate, CancellationToken cancellationToken = default) { Admit(); db.Invitations.Add(aggregate); return control.SaveAsync(cancellationToken); 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 cfa7aa271..c77c388a5 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 and data-erasure + // 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, .. DataErasureJobRegistration.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, .. DataErasureJobRegistration.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/AccountClosureStorageDdl.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/AccountClosureStorageDdl.cs new file mode 100644 index 000000000..a74461955 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/AccountClosureStorageDdl.cs @@ -0,0 +1,831 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +/// +/// P03-10 Step 3 storage for a global account closure (ADR-0107 §§ 7 and 8, ADR-0072 Amendment 8): the platform role's +/// closed-column grants, the one users trigger exception, the request guard's closure arrows and the INSERT +/// arm's User status witness. Each arrow reads its witnesses in SQL, on the writing connection; none trusts a flag. +/// +/// +/// +/// The grants. learnstack_platform bypasses row security, so its grants are its whole bound. It reads +/// users by id, status, provider_subject (the subject Finalize removes from the provider) +/// and subject_key (the key ADR-0108 § 4's closure plan selects the sentinel tenant's rows by), and updates +/// only status and provider_subject. It reads the participant groups from six memberships +/// columns, and the last-administrator judgment of a participant tenant from exactly the columns the deferred +/// complete-graph guard's administrator predicate reads on the assignment, Role and grant tables; the Membership side +/// of that predicate needs no deleted_by, because ck_memberships_lifecycle makes an Active Membership's +/// deletion columns NULL. It may also write a closure's last_refusal, and execute the two lock observers, which +/// read only the calling backend's own pg_locks rows. +/// +/// +/// The fences. A closure's fences are the subject's User key and the key of every tenant in which the subject +/// holds a Membership of any status, a Revoked tombstone included, each held exclusively on the connection that +/// writes. Memberships are never deleted and a new one is admitted only under the subject's exclusive User key, so +/// while that key is held the participant set cannot change under the check. +/// +/// +/// The users exception. fn_identity_user_immutable still backs the three triggers whose names the +/// table has always had. A DELETE, a TRUNCATE and every role's UPDATE but the platform session's stay refused, the +/// migration owner's included. The platform session's UPDATE passes only when nothing but the status and the raw +/// provider subject changes, the transition is Active to Closing with the subject kept or Closing to Closed with it +/// removed, and the fences above are held; a subject with no Membership has none to hold and is refused, since a +/// closure is filed in a group and a person with no Membership is Phase 11's. The function stamps the row version, +/// the update time and the system actor itself, so the column grant stays at the two columns. +/// +/// +/// The request guard. The platform arm gains a closure's Begin (scheduled → fulfilling), its refusal +/// record (scheduled → scheduled setting last_refusal), its Finalize (fulfilling → completed) and +/// the completion of its fan-out erasures (awaiting_privileged_step → completed), each under the subject's User +/// status and the fences it needs; the erasure completion of Step 2 is unchanged. The application arms are Step 1's +/// character for character but for one change to the INSERT arm, which a unit test pins: a request may be born +/// fulfilling only as a closure's fan-out erasure, and every request is admitted only for a subject in the one +/// status its origin allows, read under the subject's exclusive User fence the arm already requires: Closing for a +/// fan-out, Active for every other. A filing admitted while the person was Active whose transaction takes the User +/// fence only after a Begin or a Finalize committed therefore inserts nothing: no closure stays scheduled behind +/// a closed account, and no administrator files for a person whose account is closing. +/// +/// +/// Finalize's forward migration. replaces the guard once more, so that Finalize's +/// arm also completes a closure of the subject that was never begun, and grants the platform role the request's update +/// stamp, a begun closure's Begin moment. The constants applied are unchanged. +/// +/// +/// The hardening's forward migration. replaces the guard a third time with two changes +/// to the application arms: the UPDATE arm refuses every write of a closure's row but one that keeps it scheduled or +/// cancels it, so a fulfilling closure is the platform's alone, and the INSERT arm asks the subject's status after +/// the snapshot. The constants the earlier migrations applied are unchanged. +/// +/// +/// The witness function. The application role cannot read another person's users row, so the INSERT arm +/// asks fn_identity_user_status, a definer owned like the others, which returns the subject's status, or NULL +/// when there is no such User, outside a trigger, or without the subject's exclusive User fence on the calling backend. +/// +/// +internal static class AccountClosureStorageDdl +{ + internal static void Install(MigrationBuilder migration) + { + ArgumentNullException.ThrowIfNull(migration); + migration.Sql(Grants); + migration.Sql(UserStatusWitness); + migration.Sql(UserGuard); + migration.Sql(RequestGuard); + } + + /// ADR-0107 § 8, exactly. Column grants are read from the attribute ACLs. + private const string Grants = """ + GRANT SELECT (id, status, provider_subject, subject_key) ON public.users TO learnstack_platform; + GRANT UPDATE (status, provider_subject) ON public.users TO learnstack_platform; + GRANT SELECT (id, tenant_id, organization_id, user_id, status, deleted_at) ON public.memberships TO learnstack_platform; + GRANT SELECT (tenant_id, membership_id, role_id) ON public.membership_role_assignments TO learnstack_platform; + GRANT SELECT (id, tenant_id, built_in_key, permission_scope, deleted_at, deleted_by) ON public.roles TO learnstack_platform; + GRANT SELECT (tenant_id, role_id, permission_scope, permission_key) ON public.role_permission_grants TO learnstack_platform; + GRANT UPDATE (last_refusal) ON public.data_subject_requests TO learnstack_platform; + GRANT EXECUTE ON FUNCTION public.fn_identity_contextual_lock_key(text, uuid) TO learnstack_platform; + GRANT EXECUTE ON FUNCTION public.fn_identity_lock_held(text, uuid, boolean) TO learnstack_platform; + """; + + /// + /// The INSERT arm's one read of users: the subject's status, read as the owner because the application role + /// sees no other person's row, inside a trigger and under the subject's exclusive User fence only. + /// + private const string UserStatusWitness = """ + CREATE FUNCTION public.fn_identity_user_status(target uuid) RETURNS text + LANGUAGE plpgsql VOLATILE SECURITY DEFINER SET search_path = pg_catalog + AS $$ + DECLARE selected text; + BEGIN + IF pg_catalog.pg_trigger_depth() < 1 OR public.fn_identity_lock_held('user', target, true) IS NOT TRUE THEN + RETURN NULL; + END IF; + SELECT person.status INTO selected FROM public.users AS person WHERE person.id = target; + RETURN selected; + END; + $$; + ALTER FUNCTION public.fn_identity_user_status(uuid) OWNER TO learnstack_migration; + REVOKE ALL ON FUNCTION public.fn_identity_user_status(uuid) FROM PUBLIC; + GRANT EXECUTE ON FUNCTION public.fn_identity_user_status(uuid) TO learnstack_app; + """; + + /// + /// The one users trigger exception of ADR-0107 § 7 and ADR-0072 Amendment 8. Its body reads rows only through + /// existence tests, as the census of the first Identity migration's functions requires. + /// + private const string UserGuard = """ + CREATE OR REPLACE FUNCTION public.fn_identity_user_immutable() RETURNS trigger + LANGUAGE plpgsql SECURITY INVOKER SET search_path=pg_catalog AS $$ + BEGIN + -- ADR-0107 § 7 and ADR-0072 Amendment 8: the closure's UPDATE by the platform session is the one admitted + -- change. A DELETE, a TRUNCATE and every other role's UPDATE stay refused, the migration owner's included. + IF (TG_OP <> 'UPDATE' OR session_user <> 'learnstack_platform' OR current_user <> 'learnstack_platform') IS NOT FALSE + THEN + RAISE EXCEPTION 'Identity bindings have no admitted update or removal owner.' USING ERRCODE='23514'; + END IF; + -- Only the status and the raw provider subject change: the key, the authority and the creation evidence are + -- the permanent tombstone, and the bookkeeping is stamped below. + IF (ROW(NEW.id, NEW.authority_id, NEW.subject_key, NEW.creation_audit_id, NEW.creation_audit_timestamp, + NEW.created_at, NEW.created_by, NEW.updated_at, NEW.updated_by, NEW.deleted_at, NEW.deleted_by, + NEW.row_version) + IS DISTINCT FROM ROW(OLD.id, OLD.authority_id, OLD.subject_key, OLD.creation_audit_id, + OLD.creation_audit_timestamp, OLD.created_at, OLD.created_by, OLD.updated_at, OLD.updated_by, + OLD.deleted_at, OLD.deleted_by, OLD.row_version)) IS NOT FALSE + THEN + RAISE EXCEPTION 'User closure column refused.' USING ERRCODE='23514'; + END IF; + -- Active to Closing keeps the raw subject; Closing to Closed removes it. Nothing returns to Active. + IF (NOT ((OLD.status = 'Active' AND NEW.status = 'Closing' + AND NEW.provider_subject IS NOT DISTINCT FROM OLD.provider_subject) + OR (OLD.status = 'Closing' AND NEW.status = 'Closed' AND NEW.provider_subject IS NULL))) IS NOT FALSE + THEN + RAISE EXCEPTION 'User closure transition refused.' USING ERRCODE='23514'; + END IF; + -- The fences, observed on this connection: the subject's User key, then the key of every tenant in which the + -- subject holds a Membership of any status, each exclusively. A subject with no Membership has no closure. + IF public.fn_identity_lock_held('user', OLD.id, true) IS NOT TRUE THEN + RAISE EXCEPTION 'User closure fence refused.' USING ERRCODE='23514'; + END IF; + IF NOT EXISTS (SELECT 1 FROM public.memberships AS member WHERE member.user_id = OLD.id) THEN + RAISE EXCEPTION 'User closure participant refused.' USING ERRCODE='23514'; + END IF; + IF EXISTS (SELECT 1 FROM public.memberships AS member WHERE member.user_id = OLD.id + GROUP BY member.tenant_id + HAVING public.fn_identity_lock_held('tenant', member.tenant_id, true) IS NOT TRUE) THEN + RAISE EXCEPTION 'User closure tenant fence refused.' USING ERRCODE='23514'; + END IF; + -- Never earlier than the row's last stamp; the system actor, as every operator-stamped row. + NEW.updated_at := GREATEST(clock_timestamp(), COALESCE(OLD.updated_at, OLD.created_at)); + NEW.updated_by := '00000000-0000-7000-8000-000000000001'::uuid; + NEW.row_version := OLD.row_version + 1; + RETURN NEW; + END $$; + REVOKE ALL ON FUNCTION public.fn_identity_user_immutable() FROM PUBLIC; + """; + + /// + /// The request guard of with the closure's arrows in its platform arm and the + /// User status witness in the application's INSERT arm; a unit test compares the application arms with Step 1's and + /// pins that one difference. + /// + private const string RequestGuard = """ + CREATE OR REPLACE 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 + -- The platform arm (ADR-0107 §§ 7 and 8, ADR-0108 § 8). learnstack_platform takes the operator's arrows below + -- and writes nothing else: every other column as the statement presents it, the version step, and the stamps + -- written here from the database clock and the system actor, so no caller supplies a time and the columns it + -- holds no grant on need none. A closure's arrows read their witnesses here, on this connection: the subject's + -- User status and the fences the connection holds, never a flag the caller passes. + IF session_user = 'learnstack_platform' AND current_user = 'learnstack_platform' THEN + IF (TG_TABLE_SCHEMA <> 'public' OR TG_TABLE_NAME <> 'data_subject_requests' OR TG_OP <> 'UPDATE') IS NOT FALSE + THEN RAISE EXCEPTION 'Data request mutation refused.' USING ERRCODE = '23514'; 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.progress, NEW.failure_reason, + NEW.created_at, NEW.created_by, NEW.updated_at, NEW.updated_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.progress, OLD.failure_reason, + OLD.created_at, OLD.created_by, OLD.updated_at, OLD.updated_by, OLD.deleted_at, OLD.deleted_by) + OR NEW.row_version IS DISTINCT FROM OLD.row_version + 1) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request immutable state refused.' USING ERRCODE = '23514'; END IF; + -- The refusal record changes on a closure's refusal arrow alone. + IF (NEW.last_refusal IS DISTINCT FROM OLD.last_refusal + AND NOT (OLD.kind = 'closure' AND OLD.status = 'scheduled' AND NEW.status = 'scheduled')) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request refusal record refused.' USING ERRCODE = '23514'; END IF; + -- Never earlier than the row's last stamp, which an application clock up to five minutes ahead wrote. + NEW.updated_at := GREATEST(clock_timestamp(), COALESCE(OLD.updated_at, OLD.created_at)); + NEW.updated_by := '00000000-0000-7000-8000-000000000001'::uuid; + IF OLD.kind = 'erasure' AND OLD.origin <> 'closure_fanout' AND OLD.status = 'awaiting_privileged_step' + AND NEW.status = 'completed' THEN + -- An erasure's privileged step (ADR-0106 § 8, ADR-0108 § 8). The tenant side's retained record stays as + -- its participants wrote it; the redaction sets the audit log's four kinds and nothing else (ADR-0107 § 6). + IF ((NEW.result - ARRAY['audit_actor_reference','audit_entity_reference','audit_metadata_reference', + 'unscoped_audit_rows']) + IS DISTINCT FROM (OLD.result - ARRAY['audit_actor_reference','audit_entity_reference', + 'audit_metadata_reference','unscoped_audit_rows'])) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request result refused.' USING ERRCODE = '23514'; END IF; + NEW.completed_at := NEW.updated_at; + ELSIF OLD.kind = 'closure' AND OLD.status = 'scheduled' AND NEW.status = 'scheduled' THEN + -- A closure's refusal record (ADR-0106 § 7, ADR-0107 § 7): a Begin that refuses leaves the request + -- scheduled with its closed code, so the person can act on it. A code is set or replaced, never + -- cleared: a later Begin that succeeds moves the request on, and no application path writes a + -- closure's refusal. Recording the standing code again changes nothing and is refused. + IF (NEW.last_refusal NOT IN ('blocked_window','blocked_hold','blocked_last_administrator') + OR NEW.last_refusal IS NOT DISTINCT FROM OLD.last_refusal) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request refusal record refused.' USING ERRCODE = '23514'; END IF; + IF (NEW.result IS DISTINCT FROM OLD.result) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request result refused.' USING ERRCODE = '23514'; END IF; + IF (NEW.completed_at IS DISTINCT FROM OLD.completed_at) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request completion refused.' USING ERRCODE = '23514'; END IF; + ELSIF OLD.kind = 'closure' AND OLD.status = 'scheduled' AND NEW.status = 'fulfilling' THEN + -- A closure's Begin (ADR-0106 § 8, ADR-0107 § 7): once its window has passed, with the subject already + -- Closing, under the subject's exclusive User fence and the exclusive key of the request's tenant and + -- of every tenant in which the subject holds a Membership of any status. The result is not touched. + IF (NEW.result IS DISTINCT FROM OLD.result) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request result refused.' USING ERRCODE = '23514'; END IF; + IF (NEW.completed_at IS DISTINCT FROM OLD.completed_at) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request completion refused.' USING ERRCODE = '23514'; END IF; + IF (clock_timestamp() < OLD.execute_at) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request closure window refused.' USING ERRCODE = '23514'; END IF; + IF ((SELECT person.status FROM public.users AS person WHERE person.id = OLD.subject_user_id) + IS DISTINCT FROM 'Closing') IS NOT FALSE + THEN RAISE EXCEPTION 'Data request closure subject refused.' USING ERRCODE = '23514'; END IF; + IF public.fn_identity_lock_held('user', OLD.subject_user_id, true) IS NOT TRUE + THEN RAISE EXCEPTION 'Data request closure user fence refused.' USING ERRCODE = '23514'; END IF; + IF (public.fn_identity_lock_held('tenant', OLD.tenant_id, true) IS NOT TRUE + OR EXISTS (SELECT 1 FROM public.memberships AS member WHERE member.user_id = OLD.subject_user_id + GROUP BY member.tenant_id + HAVING public.fn_identity_lock_held('tenant', member.tenant_id, true) IS NOT TRUE)) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request closure tenant fence refused.' USING ERRCODE = '23514'; END IF; + ELSIF OLD.kind = 'closure' AND OLD.status = 'fulfilling' AND NEW.status = 'completed' THEN + -- A closure's Finalize (ADR-0107 § 7, ADR-0108 § 8): with the subject already Closed, under the fences + -- of Begin. The result records the redaction's four audit kinds and the unserved groups, nothing else. + IF ((NEW.result - ARRAY['audit_actor_reference','audit_entity_reference','audit_metadata_reference', + 'unscoped_audit_rows','unserved_group']) + IS DISTINCT FROM (OLD.result - ARRAY['audit_actor_reference','audit_entity_reference', + 'audit_metadata_reference','unscoped_audit_rows','unserved_group'])) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request result refused.' USING ERRCODE = '23514'; END IF; + IF ((SELECT person.status FROM public.users AS person WHERE person.id = OLD.subject_user_id) + IS DISTINCT FROM 'Closed') IS NOT FALSE + THEN RAISE EXCEPTION 'Data request closure subject refused.' USING ERRCODE = '23514'; END IF; + IF public.fn_identity_lock_held('user', OLD.subject_user_id, true) IS NOT TRUE + THEN RAISE EXCEPTION 'Data request closure user fence refused.' USING ERRCODE = '23514'; END IF; + IF (public.fn_identity_lock_held('tenant', OLD.tenant_id, true) IS NOT TRUE + OR EXISTS (SELECT 1 FROM public.memberships AS member WHERE member.user_id = OLD.subject_user_id + GROUP BY member.tenant_id + HAVING public.fn_identity_lock_held('tenant', member.tenant_id, true) IS NOT TRUE)) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request closure tenant fence refused.' USING ERRCODE = '23514'; END IF; + NEW.completed_at := NEW.updated_at; + ELSIF OLD.kind = 'erasure' AND OLD.origin = 'closure_fanout' AND OLD.status = 'awaiting_privileged_step' + AND NEW.status = 'completed' THEN + -- A closure's fan-out erasure, completed by that closure's Finalize alone (ADR-0107 § 7): the subject is + -- Closing or Closed, and the connection holds the subject's User fence and the request's tenant key, + -- both exclusively. The result changes only in the audit log's four kinds, as for any erasure. + IF ((NEW.result - ARRAY['audit_actor_reference','audit_entity_reference','audit_metadata_reference', + 'unscoped_audit_rows']) + IS DISTINCT FROM (OLD.result - ARRAY['audit_actor_reference','audit_entity_reference', + 'audit_metadata_reference','unscoped_audit_rows'])) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request result refused.' USING ERRCODE = '23514'; END IF; + IF ((SELECT person.status FROM public.users AS person WHERE person.id = OLD.subject_user_id) + NOT IN ('Closing','Closed')) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request closure subject refused.' USING ERRCODE = '23514'; END IF; + IF public.fn_identity_lock_held('user', OLD.subject_user_id, true) IS NOT TRUE + THEN RAISE EXCEPTION 'Data request closure user fence refused.' USING ERRCODE = '23514'; END IF; + IF public.fn_identity_lock_held('tenant', OLD.tenant_id, true) IS NOT TRUE + THEN RAISE EXCEPTION 'Data request closure tenant fence refused.' USING ERRCODE = '23514'; END IF; + NEW.completed_at := NEW.updated_at; + ELSE + -- Every other arrow, kind, origin and status (ADR-0106 § 8). + RAISE EXCEPTION 'Data request transition refused.' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + 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; + -- A request is born fulfilling only as a closure's fan-out erasure, with no window and no requester + -- (ADR-0107 § 7): such a row stands in for the erasure the profile clearing of a Revoked Membership requires. + 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.origin = 'closure_fanout' AND (NEW.kind IS DISTINCT FROM 'erasure' OR NEW.execute_at IS NOT NULL + OR NEW.requester_user_id IS NOT NULL)) + 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 subject is admitted in the one status its origin allows, read here under the User fence held above: + -- Closing for a closure's fan-out, Active for every other request (ADR-0107 § 7). A filing admitted while + -- the person was Active and fenced only after a Begin or a Finalize committed inserts nothing. + IF (public.fn_identity_user_status(NEW.subject_user_id) + IS DISTINCT FROM (CASE WHEN NEW.origin = 'closure_fanout' THEN 'Closing' ELSE 'Active' END)) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request subject is not admitted.' 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; + """; + + /// + /// The closure's Finalize storage (ADR-0107 §§ 7 and 8), a forward migration over 's: the platform + /// role reads a request's update stamp, which is a begun closure's Begin moment, and the closure arm of the request guard + /// completes every open closure of a Closed subject, a never-begun one included, under the same witnesses as the one it + /// finalizes. A unit test pins that is but for that arm's + /// condition and comment. + /// + internal static void InstallFinalize(MigrationBuilder migration) + { + ArgumentNullException.ThrowIfNull(migration); + migration.Sql(FinalizeGrants); + migration.Sql(FinalizeRequestGuard); + } + + /// + /// The update stamp alone: a begun closure's is its Begin moment, which Finalize's readiness compares a participant + /// erasure's completion with. It names no actor. + /// + private const string FinalizeGrants = """ + GRANT SELECT (updated_at) ON public.data_subject_requests TO learnstack_platform; + """; + + /// + /// with the closure's completion arm taking a never-begun closure of the subject too: a person + /// may hold one open closure in each group, and once the subject is Closed a closure still scheduled can never be + /// begun, so Finalize completes it with the one it finalizes, under the same witnesses. + /// + private const string FinalizeRequestGuard = """ + CREATE OR REPLACE 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 + -- The platform arm (ADR-0107 §§ 7 and 8, ADR-0108 § 8). learnstack_platform takes the operator's arrows below + -- and writes nothing else: every other column as the statement presents it, the version step, and the stamps + -- written here from the database clock and the system actor, so no caller supplies a time and the columns it + -- holds no grant on need none. A closure's arrows read their witnesses here, on this connection: the subject's + -- User status and the fences the connection holds, never a flag the caller passes. + IF session_user = 'learnstack_platform' AND current_user = 'learnstack_platform' THEN + IF (TG_TABLE_SCHEMA <> 'public' OR TG_TABLE_NAME <> 'data_subject_requests' OR TG_OP <> 'UPDATE') IS NOT FALSE + THEN RAISE EXCEPTION 'Data request mutation refused.' USING ERRCODE = '23514'; 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.progress, NEW.failure_reason, + NEW.created_at, NEW.created_by, NEW.updated_at, NEW.updated_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.progress, OLD.failure_reason, + OLD.created_at, OLD.created_by, OLD.updated_at, OLD.updated_by, OLD.deleted_at, OLD.deleted_by) + OR NEW.row_version IS DISTINCT FROM OLD.row_version + 1) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request immutable state refused.' USING ERRCODE = '23514'; END IF; + -- The refusal record changes on a closure's refusal arrow alone. + IF (NEW.last_refusal IS DISTINCT FROM OLD.last_refusal + AND NOT (OLD.kind = 'closure' AND OLD.status = 'scheduled' AND NEW.status = 'scheduled')) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request refusal record refused.' USING ERRCODE = '23514'; END IF; + -- Never earlier than the row's last stamp, which an application clock up to five minutes ahead wrote. + NEW.updated_at := GREATEST(clock_timestamp(), COALESCE(OLD.updated_at, OLD.created_at)); + NEW.updated_by := '00000000-0000-7000-8000-000000000001'::uuid; + IF OLD.kind = 'erasure' AND OLD.origin <> 'closure_fanout' AND OLD.status = 'awaiting_privileged_step' + AND NEW.status = 'completed' THEN + -- An erasure's privileged step (ADR-0106 § 8, ADR-0108 § 8). The tenant side's retained record stays as + -- its participants wrote it; the redaction sets the audit log's four kinds and nothing else (ADR-0107 § 6). + IF ((NEW.result - ARRAY['audit_actor_reference','audit_entity_reference','audit_metadata_reference', + 'unscoped_audit_rows']) + IS DISTINCT FROM (OLD.result - ARRAY['audit_actor_reference','audit_entity_reference', + 'audit_metadata_reference','unscoped_audit_rows'])) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request result refused.' USING ERRCODE = '23514'; END IF; + NEW.completed_at := NEW.updated_at; + ELSIF OLD.kind = 'closure' AND OLD.status = 'scheduled' AND NEW.status = 'scheduled' THEN + -- A closure's refusal record (ADR-0106 § 7, ADR-0107 § 7): a Begin that refuses leaves the request + -- scheduled with its closed code, so the person can act on it. A code is set or replaced, never + -- cleared: a later Begin that succeeds moves the request on, and no application path writes a + -- closure's refusal. Recording the standing code again changes nothing and is refused. + IF (NEW.last_refusal NOT IN ('blocked_window','blocked_hold','blocked_last_administrator') + OR NEW.last_refusal IS NOT DISTINCT FROM OLD.last_refusal) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request refusal record refused.' USING ERRCODE = '23514'; END IF; + IF (NEW.result IS DISTINCT FROM OLD.result) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request result refused.' USING ERRCODE = '23514'; END IF; + IF (NEW.completed_at IS DISTINCT FROM OLD.completed_at) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request completion refused.' USING ERRCODE = '23514'; END IF; + ELSIF OLD.kind = 'closure' AND OLD.status = 'scheduled' AND NEW.status = 'fulfilling' THEN + -- A closure's Begin (ADR-0106 § 8, ADR-0107 § 7): once its window has passed, with the subject already + -- Closing, under the subject's exclusive User fence and the exclusive key of the request's tenant and + -- of every tenant in which the subject holds a Membership of any status. The result is not touched. + IF (NEW.result IS DISTINCT FROM OLD.result) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request result refused.' USING ERRCODE = '23514'; END IF; + IF (NEW.completed_at IS DISTINCT FROM OLD.completed_at) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request completion refused.' USING ERRCODE = '23514'; END IF; + IF (clock_timestamp() < OLD.execute_at) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request closure window refused.' USING ERRCODE = '23514'; END IF; + IF ((SELECT person.status FROM public.users AS person WHERE person.id = OLD.subject_user_id) + IS DISTINCT FROM 'Closing') IS NOT FALSE + THEN RAISE EXCEPTION 'Data request closure subject refused.' USING ERRCODE = '23514'; END IF; + IF public.fn_identity_lock_held('user', OLD.subject_user_id, true) IS NOT TRUE + THEN RAISE EXCEPTION 'Data request closure user fence refused.' USING ERRCODE = '23514'; END IF; + IF (public.fn_identity_lock_held('tenant', OLD.tenant_id, true) IS NOT TRUE + OR EXISTS (SELECT 1 FROM public.memberships AS member WHERE member.user_id = OLD.subject_user_id + GROUP BY member.tenant_id + HAVING public.fn_identity_lock_held('tenant', member.tenant_id, true) IS NOT TRUE)) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request closure tenant fence refused.' USING ERRCODE = '23514'; END IF; + ELSIF OLD.kind = 'closure' AND OLD.status IN ('scheduled', 'fulfilling') AND NEW.status = 'completed' THEN + -- A closure's Finalize (ADR-0107 § 7, ADR-0108 § 8): with the subject already Closed, under the fences + -- of Begin, the closure it finalizes from fulfilling and every other closure of the subject from where + -- it stands, begun or not. The result records the redaction's four audit kinds and the unserved groups, + -- nothing else. + IF ((NEW.result - ARRAY['audit_actor_reference','audit_entity_reference','audit_metadata_reference', + 'unscoped_audit_rows','unserved_group']) + IS DISTINCT FROM (OLD.result - ARRAY['audit_actor_reference','audit_entity_reference', + 'audit_metadata_reference','unscoped_audit_rows','unserved_group'])) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request result refused.' USING ERRCODE = '23514'; END IF; + IF ((SELECT person.status FROM public.users AS person WHERE person.id = OLD.subject_user_id) + IS DISTINCT FROM 'Closed') IS NOT FALSE + THEN RAISE EXCEPTION 'Data request closure subject refused.' USING ERRCODE = '23514'; END IF; + IF public.fn_identity_lock_held('user', OLD.subject_user_id, true) IS NOT TRUE + THEN RAISE EXCEPTION 'Data request closure user fence refused.' USING ERRCODE = '23514'; END IF; + IF (public.fn_identity_lock_held('tenant', OLD.tenant_id, true) IS NOT TRUE + OR EXISTS (SELECT 1 FROM public.memberships AS member WHERE member.user_id = OLD.subject_user_id + GROUP BY member.tenant_id + HAVING public.fn_identity_lock_held('tenant', member.tenant_id, true) IS NOT TRUE)) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request closure tenant fence refused.' USING ERRCODE = '23514'; END IF; + NEW.completed_at := NEW.updated_at; + ELSIF OLD.kind = 'erasure' AND OLD.origin = 'closure_fanout' AND OLD.status = 'awaiting_privileged_step' + AND NEW.status = 'completed' THEN + -- A closure's fan-out erasure, completed by that closure's Finalize alone (ADR-0107 § 7): the subject is + -- Closing or Closed, and the connection holds the subject's User fence and the request's tenant key, + -- both exclusively. The result changes only in the audit log's four kinds, as for any erasure. + IF ((NEW.result - ARRAY['audit_actor_reference','audit_entity_reference','audit_metadata_reference', + 'unscoped_audit_rows']) + IS DISTINCT FROM (OLD.result - ARRAY['audit_actor_reference','audit_entity_reference', + 'audit_metadata_reference','unscoped_audit_rows'])) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request result refused.' USING ERRCODE = '23514'; END IF; + IF ((SELECT person.status FROM public.users AS person WHERE person.id = OLD.subject_user_id) + NOT IN ('Closing','Closed')) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request closure subject refused.' USING ERRCODE = '23514'; END IF; + IF public.fn_identity_lock_held('user', OLD.subject_user_id, true) IS NOT TRUE + THEN RAISE EXCEPTION 'Data request closure user fence refused.' USING ERRCODE = '23514'; END IF; + IF public.fn_identity_lock_held('tenant', OLD.tenant_id, true) IS NOT TRUE + THEN RAISE EXCEPTION 'Data request closure tenant fence refused.' USING ERRCODE = '23514'; END IF; + NEW.completed_at := NEW.updated_at; + ELSE + -- Every other arrow, kind, origin and status (ADR-0106 § 8). + RAISE EXCEPTION 'Data request transition refused.' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + 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; + -- A request is born fulfilling only as a closure's fan-out erasure, with no window and no requester + -- (ADR-0107 § 7): such a row stands in for the erasure the profile clearing of a Revoked Membership requires. + 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.origin = 'closure_fanout' AND (NEW.kind IS DISTINCT FROM 'erasure' OR NEW.execute_at IS NOT NULL + OR NEW.requester_user_id IS NOT NULL)) + 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 subject is admitted in the one status its origin allows, read here under the User fence held above: + -- Closing for a closure's fan-out, Active for every other request (ADR-0107 § 7). A filing admitted while + -- the person was Active and fenced only after a Begin or a Finalize committed inserts nothing. + IF (public.fn_identity_user_status(NEW.subject_user_id) + IS DISTINCT FROM (CASE WHEN NEW.origin = 'closure_fanout' THEN 'Closing' ELSE 'Active' END)) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request subject is not admitted.' 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; + """; + + /// + /// The guard's hardening, a forward migration of its own: replaces the function, and + /// nothing else changes. A unit test pins that it is but for its two changes. + /// + internal static void InstallHardening(MigrationBuilder migration) + { + ArgumentNullException.ThrowIfNull(migration); + migration.Sql(HardenedRequestGuard); + } + + /// + /// The request guard hardened (20261123130000_harden_closure_request_guard): but for + /// two changes to the application arms, which a unit test pins. The UPDATE arm refuses every write of a closure's row + /// except one that leaves it scheduled or cancels it, so a closure the platform made fulfilling is written + /// by the platform's arrows alone and its Begin moment, result and version are the ones Finalize reads. The INSERT arm + /// asks the subject's status after the snapshot, so the two refusals say nothing about the status of a person whose + /// snapshot is refused. + /// + private const string HardenedRequestGuard = """ + CREATE OR REPLACE 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 + -- The platform arm (ADR-0107 §§ 7 and 8, ADR-0108 § 8). learnstack_platform takes the operator's arrows below + -- and writes nothing else: every other column as the statement presents it, the version step, and the stamps + -- written here from the database clock and the system actor, so no caller supplies a time and the columns it + -- holds no grant on need none. A closure's arrows read their witnesses here, on this connection: the subject's + -- User status and the fences the connection holds, never a flag the caller passes. + IF session_user = 'learnstack_platform' AND current_user = 'learnstack_platform' THEN + IF (TG_TABLE_SCHEMA <> 'public' OR TG_TABLE_NAME <> 'data_subject_requests' OR TG_OP <> 'UPDATE') IS NOT FALSE + THEN RAISE EXCEPTION 'Data request mutation refused.' USING ERRCODE = '23514'; 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.progress, NEW.failure_reason, + NEW.created_at, NEW.created_by, NEW.updated_at, NEW.updated_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.progress, OLD.failure_reason, + OLD.created_at, OLD.created_by, OLD.updated_at, OLD.updated_by, OLD.deleted_at, OLD.deleted_by) + OR NEW.row_version IS DISTINCT FROM OLD.row_version + 1) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request immutable state refused.' USING ERRCODE = '23514'; END IF; + -- The refusal record changes on a closure's refusal arrow alone. + IF (NEW.last_refusal IS DISTINCT FROM OLD.last_refusal + AND NOT (OLD.kind = 'closure' AND OLD.status = 'scheduled' AND NEW.status = 'scheduled')) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request refusal record refused.' USING ERRCODE = '23514'; END IF; + -- Never earlier than the row's last stamp, which an application clock up to five minutes ahead wrote. + NEW.updated_at := GREATEST(clock_timestamp(), COALESCE(OLD.updated_at, OLD.created_at)); + NEW.updated_by := '00000000-0000-7000-8000-000000000001'::uuid; + IF OLD.kind = 'erasure' AND OLD.origin <> 'closure_fanout' AND OLD.status = 'awaiting_privileged_step' + AND NEW.status = 'completed' THEN + -- An erasure's privileged step (ADR-0106 § 8, ADR-0108 § 8). The tenant side's retained record stays as + -- its participants wrote it; the redaction sets the audit log's four kinds and nothing else (ADR-0107 § 6). + IF ((NEW.result - ARRAY['audit_actor_reference','audit_entity_reference','audit_metadata_reference', + 'unscoped_audit_rows']) + IS DISTINCT FROM (OLD.result - ARRAY['audit_actor_reference','audit_entity_reference', + 'audit_metadata_reference','unscoped_audit_rows'])) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request result refused.' USING ERRCODE = '23514'; END IF; + NEW.completed_at := NEW.updated_at; + ELSIF OLD.kind = 'closure' AND OLD.status = 'scheduled' AND NEW.status = 'scheduled' THEN + -- A closure's refusal record (ADR-0106 § 7, ADR-0107 § 7): a Begin that refuses leaves the request + -- scheduled with its closed code, so the person can act on it. A code is set or replaced, never + -- cleared: a later Begin that succeeds moves the request on, and no application path writes a + -- closure's refusal. Recording the standing code again changes nothing and is refused. + IF (NEW.last_refusal NOT IN ('blocked_window','blocked_hold','blocked_last_administrator') + OR NEW.last_refusal IS NOT DISTINCT FROM OLD.last_refusal) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request refusal record refused.' USING ERRCODE = '23514'; END IF; + IF (NEW.result IS DISTINCT FROM OLD.result) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request result refused.' USING ERRCODE = '23514'; END IF; + IF (NEW.completed_at IS DISTINCT FROM OLD.completed_at) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request completion refused.' USING ERRCODE = '23514'; END IF; + ELSIF OLD.kind = 'closure' AND OLD.status = 'scheduled' AND NEW.status = 'fulfilling' THEN + -- A closure's Begin (ADR-0106 § 8, ADR-0107 § 7): once its window has passed, with the subject already + -- Closing, under the subject's exclusive User fence and the exclusive key of the request's tenant and + -- of every tenant in which the subject holds a Membership of any status. The result is not touched. + IF (NEW.result IS DISTINCT FROM OLD.result) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request result refused.' USING ERRCODE = '23514'; END IF; + IF (NEW.completed_at IS DISTINCT FROM OLD.completed_at) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request completion refused.' USING ERRCODE = '23514'; END IF; + IF (clock_timestamp() < OLD.execute_at) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request closure window refused.' USING ERRCODE = '23514'; END IF; + IF ((SELECT person.status FROM public.users AS person WHERE person.id = OLD.subject_user_id) + IS DISTINCT FROM 'Closing') IS NOT FALSE + THEN RAISE EXCEPTION 'Data request closure subject refused.' USING ERRCODE = '23514'; END IF; + IF public.fn_identity_lock_held('user', OLD.subject_user_id, true) IS NOT TRUE + THEN RAISE EXCEPTION 'Data request closure user fence refused.' USING ERRCODE = '23514'; END IF; + IF (public.fn_identity_lock_held('tenant', OLD.tenant_id, true) IS NOT TRUE + OR EXISTS (SELECT 1 FROM public.memberships AS member WHERE member.user_id = OLD.subject_user_id + GROUP BY member.tenant_id + HAVING public.fn_identity_lock_held('tenant', member.tenant_id, true) IS NOT TRUE)) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request closure tenant fence refused.' USING ERRCODE = '23514'; END IF; + ELSIF OLD.kind = 'closure' AND OLD.status IN ('scheduled', 'fulfilling') AND NEW.status = 'completed' THEN + -- A closure's Finalize (ADR-0107 § 7, ADR-0108 § 8): with the subject already Closed, under the fences + -- of Begin, the closure it finalizes from fulfilling and every other closure of the subject from where + -- it stands, begun or not. The result records the redaction's four audit kinds and the unserved groups, + -- nothing else. + IF ((NEW.result - ARRAY['audit_actor_reference','audit_entity_reference','audit_metadata_reference', + 'unscoped_audit_rows','unserved_group']) + IS DISTINCT FROM (OLD.result - ARRAY['audit_actor_reference','audit_entity_reference', + 'audit_metadata_reference','unscoped_audit_rows','unserved_group'])) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request result refused.' USING ERRCODE = '23514'; END IF; + IF ((SELECT person.status FROM public.users AS person WHERE person.id = OLD.subject_user_id) + IS DISTINCT FROM 'Closed') IS NOT FALSE + THEN RAISE EXCEPTION 'Data request closure subject refused.' USING ERRCODE = '23514'; END IF; + IF public.fn_identity_lock_held('user', OLD.subject_user_id, true) IS NOT TRUE + THEN RAISE EXCEPTION 'Data request closure user fence refused.' USING ERRCODE = '23514'; END IF; + IF (public.fn_identity_lock_held('tenant', OLD.tenant_id, true) IS NOT TRUE + OR EXISTS (SELECT 1 FROM public.memberships AS member WHERE member.user_id = OLD.subject_user_id + GROUP BY member.tenant_id + HAVING public.fn_identity_lock_held('tenant', member.tenant_id, true) IS NOT TRUE)) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request closure tenant fence refused.' USING ERRCODE = '23514'; END IF; + NEW.completed_at := NEW.updated_at; + ELSIF OLD.kind = 'erasure' AND OLD.origin = 'closure_fanout' AND OLD.status = 'awaiting_privileged_step' + AND NEW.status = 'completed' THEN + -- A closure's fan-out erasure, completed by that closure's Finalize alone (ADR-0107 § 7): the subject is + -- Closing or Closed, and the connection holds the subject's User fence and the request's tenant key, + -- both exclusively. The result changes only in the audit log's four kinds, as for any erasure. + IF ((NEW.result - ARRAY['audit_actor_reference','audit_entity_reference','audit_metadata_reference', + 'unscoped_audit_rows']) + IS DISTINCT FROM (OLD.result - ARRAY['audit_actor_reference','audit_entity_reference', + 'audit_metadata_reference','unscoped_audit_rows'])) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request result refused.' USING ERRCODE = '23514'; END IF; + IF ((SELECT person.status FROM public.users AS person WHERE person.id = OLD.subject_user_id) + NOT IN ('Closing','Closed')) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request closure subject refused.' USING ERRCODE = '23514'; END IF; + IF public.fn_identity_lock_held('user', OLD.subject_user_id, true) IS NOT TRUE + THEN RAISE EXCEPTION 'Data request closure user fence refused.' USING ERRCODE = '23514'; END IF; + IF public.fn_identity_lock_held('tenant', OLD.tenant_id, true) IS NOT TRUE + THEN RAISE EXCEPTION 'Data request closure tenant fence refused.' USING ERRCODE = '23514'; END IF; + NEW.completed_at := NEW.updated_at; + ELSE + -- Every other arrow, kind, origin and status (ADR-0106 § 8). + RAISE EXCEPTION 'Data request transition refused.' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + 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; + -- A request is born fulfilling only as a closure's fan-out erasure, with no window and no requester + -- (ADR-0107 § 7): such a row stands in for the erasure the profile clearing of a Revoked Membership requires. + 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.origin = 'closure_fanout' AND (NEW.kind IS DISTINCT FROM 'erasure' OR NEW.execute_at IS NOT NULL + OR NEW.requester_user_id IS NOT NULL)) + 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; + -- The subject is admitted in the one status its origin allows, read here under the User fence held above: + -- Closing for a closure's fan-out, Active for every other request (ADR-0107 § 7). A filing admitted while + -- the person was Active and fenced only after a Begin or a Finalize committed inserts nothing. It is asked + -- after the snapshot, so a refused snapshot says nothing about the subject's status. + IF (public.fn_identity_user_status(NEW.subject_user_id) + IS DISTINCT FROM (CASE WHEN NEW.origin = 'closure_fanout' THEN 'Closing' ELSE 'Active' END)) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request subject is not admitted.' 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; + -- A closure is the application's only while it is scheduled (ADR-0107 § 7): the person cancels it, and once it + -- leaves scheduled every write of its row is the platform's arrows, so its Begin moment, its result and its + -- version change only as Finalize reads them. + IF (OLD.kind = 'closure' AND NOT (OLD.status = 'scheduled' AND NEW.status IN ('scheduled','cancelled'))) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request transition refused.' 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; + """; +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualIdentityStorageDdl.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualIdentityStorageDdl.cs index e95778efc..f828e7ca3 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualIdentityStorageDdl.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualIdentityStorageDdl.cs @@ -124,6 +124,78 @@ internal static void RestoreLegacyParentLifecycleLock(MigrationBuilder migration migration.Sql("CREATE OR REPLACE " + MutationGuardSql(correctParentMirror: true)); } + /// + /// ADR-0107 § 5: the one exception the erasure needs, a clearing UPDATE of a Revoked Membership's profile under the + /// erasure witness. Every other refusal of the function stays as it was. + /// + internal static void AdmitErasureProfileClearing(MigrationBuilder migration) + { + ArgumentNullException.ThrowIfNull(migration); + migration.Sql("CREATE OR REPLACE " + ErasureProfileClearingSql()); + } + + /// + /// The current guard with ADR-0107 § 5's witnessed exception. Composed from the earlier forward corrections, which + /// the applied migrations keep emitting unchanged, so the exception is the only difference. + /// + /// + /// The parent read also takes the Membership's person. A profile UPDATE of a Revoked parent passes only when it + /// clears exactly the three personal columns, judged in a block of its own so the profile's columns are never read + /// for an assignment row (the profile's other columns are refused or immutable above and by + /// fn_organization_id_immutable), the connection holds that person's User fence exclusively, and that person's + /// erasure request for the parent's own group is fulfilling; such an UPDATE then requires the tenant key + /// exclusively at the function's one fence assertion. The witness is a row and two held locks, read on the caller's + /// own transaction as the application role, never a transaction identifier. + /// + private static string ErasureProfileClearingSql() + { + var sql = MutationGuardSql(correctParentMirror: true, serializeParentLifecycle: true); + foreach (var (before, after) in ErasureProfileClearing) + { + if (sql.IndexOf(before, StringComparison.Ordinal) is var first && (first < 0 || first != sql.LastIndexOf(before, StringComparison.Ordinal))) + { + throw new InvalidOperationException("The contextual guard no longer holds, exactly once, the text the erasure exception amends."); + } + + sql = sql.Replace(before, after, StringComparison.Ordinal); + } + + return sql; + } + + private static readonly (string Before, string After)[] ErasureProfileClearing = + [ + (""" + has_history boolean; parent_fresh boolean; + """, """ + has_history boolean; parent_fresh boolean; parent_user uuid; erasure_clearing boolean := false; + """), + (""" + SELECT member.organization_id, member.status INTO parent_org, parent_status + """, """ + SELECT member.organization_id, member.status, member.user_id INTO parent_org, parent_status, parent_user + """), + (""" + IF TG_OP <> 'DELETE' AND parent_status = 'Revoked' THEN + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; + END IF; + """, """ + IF TG_TABLE_NAME = 'membership_profiles' AND TG_OP = 'UPDATE' AND parent_status = 'Revoked' THEN + erasure_clearing := NEW.display_name IS NULL AND NEW.preferred_locale IS NULL AND NEW.custom_fields = '[]'::jsonb + AND public.fn_identity_lock_held('user',parent_user,true) IS TRUE + AND EXISTS (SELECT 1 FROM public.data_subject_requests AS erasure + WHERE erasure.tenant_id = target_tenant AND erasure.subject_user_id = parent_user + AND erasure.organization_id IS NOT DISTINCT FROM parent_org + AND erasure.kind = 'erasure' AND erasure.status = 'fulfilling' + AND erasure.membership_snapshot @> jsonb_build_array(target_member::text)); + END IF; + IF TG_OP <> 'DELETE' AND parent_status = 'Revoked' AND erasure_clearing IS NOT TRUE THEN + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; + END IF; + require_exclusive := erasure_clearing IS TRUE; + """), + ]; + private static string MembershipAdmissionGuardSql(bool correctParentMirror) => MembershipAdmissionGuardDefinition .Replace("__MISSING_MEMBERSHIP_REFUSAL__", correctParentMirror ? MembershipParentRefusal : LegacyMembershipParentRefusal, StringComparison.Ordinal); 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 000000000..3eb6f3373 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/DataRequestConfigurations.cs @@ -0,0 +1,264 @@ +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 and participant progress.", + nameof(DataSubjectRequest.Kind), nameof(DataSubjectRequest.Origin), nameof(DataSubjectRequest.Status), + nameof(DataSubjectRequest.ExecuteAt), nameof(DataSubjectRequest.ProgressJson), + nameof(DataSubjectRequest.LastRefusal), nameof(DataSubjectRequest.FailureReason), nameof(DataSubjectRequest.CompletedAt)); + builder.DeclarePersonalData(PersonalDataCategory.Audit, + "Record of how many references to the person each closed retained kind holds in the group.", + nameof(DataSubjectRequest.ResultJson)); + } +} + +/// +/// 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"); + // 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) + .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.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"); + // 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, key-ring version label and expiry; no content or key.", + nameof(DataExportArtifact.Status), nameof(DataExportArtifact.KeyVersion), nameof(DataExportArtifact.ExpiresAt), + nameof(DataExportArtifact.PurgedAt)); + builder.DeclarePersonalData(PersonalDataCategory.Audit, + "Record of the size of the person's bundle and of the closed truncation statement: how many of the person's " + + "records each capped collection held.", + nameof(DataExportArtifact.ByteCount), nameof(DataExportArtifact.ChunkCount), nameof(DataExportArtifact.TruncationJson)); + } +} + +/// +/// 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/DataRequestOperatorDdl.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/DataRequestOperatorDdl.cs new file mode 100644 index 000000000..c0b574677 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/DataRequestOperatorDdl.cs @@ -0,0 +1,186 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +/// +/// P03-10 Step 2 storage for the operator's data-request acts (ADR-0107 § 8, ADR-0108 § 8): the request guard's +/// platform arm, the platform role's closed-column read of the artifact table, and the two partial indexes the +/// inspection pages. +/// +/// +/// +/// The platform arm. learnstack_platform already holds the request table's closed-column SELECT +/// and UPDATE of status, row version, completion time and result (), and the +/// guard refused every write of it. The guard is replaced with one branch for that role, ahead of the application's, +/// which admits exactly one arrow, erasure: awaiting_privileged_step → completed: every other column but the +/// result is unchanged, the result changes only in the audit log's four retained kinds, the version steps by one, and +/// the arm stamps completed_at, updated_at and updated_by itself. Trigger-assigned columns need no +/// column grant, so the platform's grant does not widen. The application's arms follow byte for byte, so the +/// application role cannot take the platform's arrow and the platform role cannot take one of the application's. +/// +/// +/// The artifact read. The inspection lists expired artifacts whose purge has not run, joined to their request +/// for its group: id, tenant_id, request_id, status and expires_at are what it +/// filters, joins, orders and shows, and nothing more is granted. No subject, size, key version, truncation or actor +/// column is readable (an artifact's subject is its request's, which the role reads already), and nothing of the +/// ticket or chunk tables; the lifecycle CHECK makes +/// status IN ('available','expired') the same rows as purged_at IS NULL, so the purge time is not granted +/// either. +/// +/// +/// The indexes. The three request lists filter one status and order by when the request fell due, +/// COALESCE(execute_at, created_at), then by id; the artifact list orders unpurged artifacts by expiry. Each is +/// a partial index on exactly the rows its list can show, so a page reads its rows in key order and never the table. +/// +/// +internal static class DataRequestOperatorDdl +{ + internal static void Install(MigrationBuilder migration) + { + ArgumentNullException.ThrowIfNull(migration); + migration.Sql(RequestGuard); + migration.Sql(ArtifactGrant); + migration.Sql(InspectionIndexes); + } + + /// + /// The request guard of with the platform arm ahead of the application's, whose + /// text is unchanged; a unit test compares the two byte for byte. + /// + private const string RequestGuard = """ + CREATE OR REPLACE 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 + -- The platform arm (ADR-0107 § 8, ADR-0108 § 8). learnstack_platform completes an erasure's privileged step + -- and writes nothing else: one arrow, the result's audit kinds, the version step, and the completion stamped + -- here from the database clock and the system actor, so no caller supplies a time and the columns it holds + -- no grant on need none. Step 3 adds the closure's arrows to the one marked condition below. + IF session_user = 'learnstack_platform' AND current_user = 'learnstack_platform' THEN + IF (TG_TABLE_SCHEMA <> 'public' OR TG_TABLE_NAME <> 'data_subject_requests' OR TG_OP <> 'UPDATE') IS NOT FALSE + THEN RAISE EXCEPTION 'Data request mutation refused.' USING ERRCODE = '23514'; 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.progress, NEW.last_refusal, + NEW.failure_reason, NEW.created_at, NEW.created_by, NEW.updated_at, NEW.updated_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.progress, OLD.last_refusal, + OLD.failure_reason, OLD.created_at, OLD.created_by, OLD.updated_at, OLD.updated_by, + OLD.deleted_at, OLD.deleted_by) + OR NEW.row_version IS DISTINCT FROM OLD.row_version + 1) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request immutable state refused.' USING ERRCODE = '23514'; END IF; + -- The tenant side's retained record stays as its participants wrote it; the redaction sets the audit log's + -- four kinds and nothing else (ADR-0107 § 6, ADR-0108 § 6). + IF ((NEW.result - ARRAY['audit_actor_reference','audit_entity_reference','audit_metadata_reference', + 'unscoped_audit_rows']) + IS DISTINCT FROM (OLD.result - ARRAY['audit_actor_reference','audit_entity_reference', + 'audit_metadata_reference','unscoped_audit_rows'])) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request result refused.' USING ERRCODE = '23514'; END IF; + -- The platform's arrows (ADR-0106 § 8). Step 3's closure Begin and Finalize join this condition. + -- A closure's fan-out erasure is completed by that closure's finalization alone (ADR-0107 § 7). + IF (NOT (OLD.kind = 'erasure' AND OLD.origin <> 'closure_fanout' AND OLD.status = 'awaiting_privileged_step' + AND NEW.status = 'completed')) + IS NOT FALSE + THEN RAISE EXCEPTION 'Data request transition refused.' USING ERRCODE = '23514'; END IF; + -- Never earlier than the row's last stamp, which an application clock up to five minutes ahead wrote. + NEW.updated_at := GREATEST(clock_timestamp(), COALESCE(OLD.updated_at, OLD.created_at)); + NEW.updated_by := '00000000-0000-7000-8000-000000000001'::uuid; + NEW.completed_at := NEW.updated_at; + RETURN NEW; + END IF; + 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; + -- A request is never born fulfilling until a closure's fan-out has its own witness (ADR-0107 § 7): such a row + -- would stand in for the erasure the profile clearing of a Revoked Membership requires, with no window. + 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 NULL 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; + """; + + /// + /// The inspection's closed-column read of the artifact table, and nothing on its tickets or chunks. + /// + private const string ArtifactGrant = """ + GRANT SELECT (id, tenant_id, request_id, status, expires_at) ON public.data_export_artifacts TO learnstack_platform; + """; + + private const string InspectionIndexes = """ + CREATE INDEX ix_data_subject_requests_operator_due ON public.data_subject_requests + (status, (COALESCE(execute_at, created_at)), id) + WHERE status IN ('scheduled','fulfilling','awaiting_privileged_step'); + CREATE INDEX ix_data_export_artifacts_unpurged_expiry ON public.data_export_artifacts (expires_at, id) + WHERE status IN ('available','expired'); + """; +} 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 000000000..dc91a9d1f --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/DataRequestStorageDdl.cs @@ -0,0 +1,518 @@ +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 ticket and chunk tables +/// ( adds its closed-column read of the artifact table); the request guard +/// refuses its writes except the one arrow that class installs, which an operator act's own arm admits. +/// +/// +/// 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. +/// +/// +/// The artifact bracket. An artifact is inserted only while its export is fulfilling and +/// commits only with that export completed, and an export commits completed only with its +/// artifact; no transaction-identity comparison is made, so the guard holds past the first xid epoch +/// and under the savepoints EF Core opens. The chunk and ticket +/// guards read their artifact FOR SHARE, so they serialize behind a revocation or purge in +/// flight, and a chunk is deleted only once its artifact is no longer available. +/// +/// +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(GroupPageIndex); + migration.Sql(ArtifactParentScope); + migration.Sql(TicketParentScope); + migration.Sql(ChunkParentScope); + migration.Sql(RequestGuard); + migration.Sql(ArtifactGuard); + migration.Sql(TicketGuard); + migration.Sql(ChunkGuard); + migration.Sql(Completeness); + migration.Sql(CompletedExportArtifact); + } + + /// + /// 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; + """; + + /// + /// The administrator's page of a group, newest first: equality on the tenant and the group's organization, then a + /// seek below the cursor's UUIDv7 in index order, so a page reads its rows and not the group's whole history. The + /// subject's page uses the subject index. + /// + private const string GroupPageIndex = """ + CREATE INDEX ix_data_subject_requests_group_page ON public.data_subject_requests (tenant_id, organization_id, id); + """; + + // 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; + -- A request is never born fulfilling until a closure's fan-out has its own witness (ADR-0107 § 7): such a row + -- would stand in for the erasure the profile clearing of a Revoked Membership requires, with no window. + 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 NULL 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; + 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, and only then. The deferred completeness check + -- requires the same request to be completed when the transaction commits, so an artifact is never + -- stored for a request that ends fulfilling, failed or rolled back. + SELECT request.kind, request.subject_user_id, request.status + INTO request_kind, request_subject, request_status + 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 request_status <> 'fulfilling') 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.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.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) + 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). FOR SHARE waits for a revocation or + -- purge in flight and reads the status it commits, so a ticket is never minted over a withdrawn artifact. + 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 + FOR SHARE; + 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; + -- Both arms read the artifact FOR SHARE, which conflicts with the row lock of a revocation or purge in + -- flight: the statement waits for it and then reads the status it committed. + IF TG_OP = 'DELETE' THEN + -- A chunk leaves only an artifact already withdrawn or expired (the store saves the transition first): + -- the ciphertext of an available artifact is never replaced or removed piecemeal. + SELECT artifact.status INTO artifact_status + FROM public.data_export_artifacts AS artifact + WHERE artifact.tenant_id = OLD.tenant_id AND artifact.id = OLD.artifact_id + FOR SHARE; + IF (NOT FOUND OR artifact_status = 'available') IS NOT FALSE + THEN RAISE EXCEPTION 'Data export chunk deletion refused.' USING ERRCODE = '23514'; END IF; + RETURN OLD; + END IF; + -- A chunk is written only onto an available artifact, so never onto one being withdrawn. + 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 + FOR SHARE; + 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. An artifact + /// inserted by the transaction also needs its request completed by it: the artifact guard admits the + /// insert only while the request is fulfilling, and this is the other half of that bracket. + /// + 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; + artifact_request uuid; request_status text; 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, artifact.request_id INTO artifact_status, artifact_chunks, artifact_request + FROM public.data_export_artifacts AS artifact + WHERE artifact.tenant_id = target_tenant AND artifact.id = target_artifact; + IF TG_TABLE_NAME = 'data_export_artifacts' AND TG_OP = 'INSERT' THEN + SELECT request.status INTO request_status FROM public.data_subject_requests AS request + WHERE request.tenant_id = target_tenant AND request.id = artifact_request; + IF (request_status IS DISTINCT FROM 'completed') IS NOT FALSE + THEN RAISE EXCEPTION 'Data export artifact request is not completed.' + USING ERRCODE = '23514', CONSTRAINT = 'data_export_artifact_request'; END IF; + END IF; + 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(); + """; + + /// + /// The reverse half of the bracket: an export that reaches completed has its artifact, of any + /// status, when the transaction commits. With the artifact guard and the completeness check above, a + /// completed export and its artifact commit together or not at all. + /// + private const string CompletedExportArtifact = """ + CREATE FUNCTION public.fn_identity_data_export_request_artifact() RETURNS trigger + LANGUAGE plpgsql VOLATILE SECURITY INVOKER SET search_path = pg_catalog AS $complete$ + BEGIN + IF NOT EXISTS (SELECT 1 FROM public.data_export_artifacts AS artifact + WHERE artifact.tenant_id = NEW.tenant_id AND artifact.request_id = NEW.id) + THEN RAISE EXCEPTION 'Data export request completed without its artifact.' + USING ERRCODE = '23514', CONSTRAINT = 'data_export_request_artifact'; END IF; + RETURN NULL; + END $complete$; + REVOKE ALL ON FUNCTION public.fn_identity_data_export_request_artifact() FROM PUBLIC; + CREATE CONSTRAINT TRIGGER tg_data_subject_requests_export_artifact AFTER UPDATE ON public.data_subject_requests + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + WHEN (NEW.kind = 'export' AND NEW.status = 'completed' AND OLD.status IS DISTINCT FROM 'completed') + EXECUTE FUNCTION public.fn_identity_data_export_request_artifact(); + """; +} 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 f66e48991..25d81dd48 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 000000000..376f4ebe5 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122013001_add_data_subject_requests.Designer.cs @@ -0,0 +1,1773 @@ +// +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, 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, expiry and the closed truncation statement (collection names and counts); 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, expiry and the closed truncation statement (collection names and counts); 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, expiry and the closed truncation statement (collection names and counts); 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, expiry and the closed truncation statement (collection names and counts); 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, expiry and the closed truncation statement (collection names and counts); 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("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") + .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"); + + 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"); + }); + }); + + 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 000000000..d207cd34c --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122013001_add_data_subject_requests.cs @@ -0,0 +1,218 @@ +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"), + 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), + 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.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 }, + 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/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 000000000..4ace5b7a2 --- /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/Migrations/20261122200000_grant_platform_data_request_operations.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122200000_grant_platform_data_request_operations.cs new file mode 100644 index 000000000..b161cb693 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122200000_grant_platform_data_request_operations.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("20261122200000_grant_platform_data_request_operations")] +public sealed class grant_platform_data_request_operations : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) => DataRequestOperatorDdl.Install(migrationBuilder); + + protected override void Down(MigrationBuilder migrationBuilder) => + // Forward-only (ADR-0107 § 8): the platform arm and the artifact read are retired by a reviewed forward + // migration, so a reversal cannot strand an erasure awaiting the privileged step with no writer to complete it. + throw new NotSupportedException("The platform data-request operations require a reviewed forward migration."); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122203000_admit_erasure_profile_clearing.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122203000_admit_erasure_profile_clearing.cs new file mode 100644 index 000000000..fc31ed793 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261122203000_admit_erasure_profile_clearing.cs @@ -0,0 +1,21 @@ +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations; + +/// +/// ADR-0107 § 5: the contextual mutation guard admits a clearing UPDATE of a Revoked Membership's profile under the +/// erasure witness, the one database exception a tenant erasure needs. +/// +[DbContext(typeof(IdentityDbContext))] +[Migration("20261122203000_admit_erasure_profile_clearing")] +public sealed class admit_erasure_profile_clearing : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) => ContextualIdentityStorageDdl.AdmitErasureProfileClearing(migrationBuilder); + + protected override void Down(MigrationBuilder migrationBuilder) => + // Forward-only, like every recent Identity head: an erasure that cleared a Revoked profile under this exception + // cannot be undone by narrowing the guard again, so a change to it is a reviewed forward migration. + throw new NotSupportedException("The erasure profile clearing requires a reviewed forward migration."); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261123100000_admit_account_closure.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261123100000_admit_account_closure.cs new file mode 100644 index 000000000..79cabece3 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261123100000_admit_account_closure.cs @@ -0,0 +1,21 @@ +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations; + +/// +/// ADR-0107 §§ 7 and 8: the platform role's closed-column grants, the one users trigger exception, the request +/// guard's closure arrows and the INSERT arm's User status witness that a global account closure needs. +/// +[DbContext(typeof(IdentityDbContext))] +[Migration("20261123100000_admit_account_closure")] +public sealed class admit_account_closure : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) => AccountClosureStorageDdl.Install(migrationBuilder); + + protected override void Down(MigrationBuilder migrationBuilder) => + // Forward-only, like every recent Identity head: a User a closure made Closing or Closed has no way back, so + // narrowing the exception again could strand a closure half done; a change to it is a reviewed forward migration. + throw new NotSupportedException("The account closure storage requires a reviewed forward migration."); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261123110000_refuse_closing_provider_event_delivery.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261123110000_refuse_closing_provider_event_delivery.cs new file mode 100644 index 000000000..b2f26e1f7 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261123110000_refuse_closing_provider_event_delivery.cs @@ -0,0 +1,21 @@ +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations; + +/// +/// ADR-0107 §§ 7 and 9: the delayed tenant mirror of a provider fact reads the affected person's status in the database, +/// under the person's shared User fence, so a delivery after a closure began refuses the person. +/// +[DbContext(typeof(IdentityDbContext))] +[Migration("20261123110000_refuse_closing_provider_event_delivery")] +public sealed class refuse_closing_provider_event_delivery : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) => ProviderEventSubjectStatusDdl.Install(migrationBuilder); + + protected override void Down(MigrationBuilder migrationBuilder) => + // Forward-only, like every recent Identity head: removing the definer would let a delayed mirror write a closed + // person's observation again; a change to it is a reviewed forward migration. + throw new NotSupportedException("The provider event subject status requires a reviewed forward migration."); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261123120000_admit_closure_finalize.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261123120000_admit_closure_finalize.cs new file mode 100644 index 000000000..972390560 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261123120000_admit_closure_finalize.cs @@ -0,0 +1,22 @@ +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations; + +/// +/// ADR-0107 §§ 7 and 8: the closure's Finalize completes every open closure of the Closed subject, a never-begun one +/// included, under the same witnesses as the closure it finalizes, and reads a begun closure's Begin moment. +/// +[DbContext(typeof(IdentityDbContext))] +[Migration("20261123120000_admit_closure_finalize")] +public sealed class admit_closure_finalize : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) => AccountClosureStorageDdl.InstallFinalize(migrationBuilder); + + protected override void Down(MigrationBuilder migrationBuilder) => + // Forward-only, like every recent Identity head: a closure Finalize completed from scheduled has no way back, and + // narrowing the arm again could strand a closure behind a Closed account; a change to it is a reviewed forward + // migration. + throw new NotSupportedException("The closure finalize storage requires a reviewed forward migration."); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261123130000_harden_closure_request_guard.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261123130000_harden_closure_request_guard.cs new file mode 100644 index 000000000..b5f650c94 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261123130000_harden_closure_request_guard.cs @@ -0,0 +1,22 @@ +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations; + +/// +/// ADR-0107 §§ 7 and 8: the request guard's application arms refuse every write of a closure's row but one that keeps it +/// scheduled or cancels it, so a begun closure is written by the platform's arrows alone, and the INSERT arm asks the +/// subject's status only after the snapshot. +/// +[DbContext(typeof(IdentityDbContext))] +[Migration("20261123130000_harden_closure_request_guard")] +public sealed class harden_closure_request_guard : Migration +{ + protected override void Up(MigrationBuilder migrationBuilder) => AccountClosureStorageDdl.InstallHardening(migrationBuilder); + + protected override void Down(MigrationBuilder migrationBuilder) => + // Forward-only, like every recent Identity head: reopening a begun closure to the application role would let a write + // move the Begin moment Finalize reads; a change to the guard is a reviewed forward migration. + throw new NotSupportedException("The closure request guard hardening 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 f330f2953..61f60cb0f 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,463 @@ 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, 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, expiry and the closed truncation statement (collection names and counts); 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, expiry and the closed truncation statement (collection names and counts); 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, expiry and the closed truncation statement (collection names and counts); 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, expiry and the closed truncation statement (collection names and counts); 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, expiry and the closed truncation statement (collection names and counts); 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("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") + .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"); + + 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"); + }); + }); + + 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 +1615,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/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 000000000..113fa6cae --- /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 000000000..7535a76b6 --- /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/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ProviderEventSubjectStatusDdl.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ProviderEventSubjectStatusDdl.cs new file mode 100644 index 000000000..e4292450a --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ProviderEventSubjectStatusDdl.cs @@ -0,0 +1,55 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +/// +/// ADR-0107 §§ 7 and 9: the delayed tenant mirror of a provider fact refuses a person whose User is no longer Active, as +/// provider intake already does. The mirror's delivery asks this definer for the affected person's status, read in the +/// database under the person's User fence held shared, so it orders against a closure's Begin and Finalize, which hold +/// that fence exclusively. +/// +/// +/// +/// Why a definer. The application role reads no other person's users row, and the request guard's User +/// status witness answers only inside a trigger under the exclusive User fence, so neither serves a delivery. This one +/// returns the status alone, of the affected person of one target only: a target of the tenant the delivery announced, +/// already enqueued, which is exactly the target the mirror's delivery reads. Anything else is NULL, which the reader +/// treats as not Active. +/// +/// +/// Why the fence. Intake takes the same shared User key before it reads the status (ADR-0097), so a delivery that +/// read Active commits before a Begin can make the User Closing, and its row is then one Finalize's redaction selects; a +/// delivery that waited for a Begin or a Finalize reads the status it committed. The key is the transaction's, released at +/// the delivery's commit, and taken after nothing else of the Identity families, so it orders no cycle. +/// +/// +internal static class ProviderEventSubjectStatusDdl +{ + internal static void Install(MigrationBuilder migration) + { + ArgumentNullException.ThrowIfNull(migration); + migration.Sql(SubjectStatus); + } + + private const string SubjectStatus = """ + CREATE FUNCTION public.fn_identity_provider_event_subject_status(target uuid) RETURNS text + LANGUAGE plpgsql VOLATILE STRICT SECURITY DEFINER SET search_path = pg_catalog + AS $$ + DECLARE affected uuid; selected text; + BEGIN + SELECT t.affected_user_id INTO affected FROM public.identity_provider_event_targets AS t + WHERE t.id = target AND t.tenant_id = NULLIF(pg_catalog.current_setting('app.tenant_id', true), '')::uuid + AND t.enqueued_at IS NOT NULL; + IF affected IS NULL THEN + RETURN NULL; + END IF; + PERFORM pg_catalog.pg_advisory_xact_lock_shared(public.fn_identity_contextual_lock_key('user', affected)); + SELECT person.status INTO selected FROM public.users AS person WHERE person.id = affected; + RETURN selected; + END; + $$; + ALTER FUNCTION public.fn_identity_provider_event_subject_status(uuid) OWNER TO learnstack_migration; + REVOKE ALL ON FUNCTION public.fn_identity_provider_event_subject_status(uuid) FROM PUBLIC; + GRANT EXECUTE ON FUNCTION public.fn_identity_provider_event_subject_status(uuid) TO learnstack_app; + """; +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/ProviderEvents/ProviderEventTargetStore.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/ProviderEvents/ProviderEventTargetStore.cs index 08617cc0d..2de1b034e 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/ProviderEvents/ProviderEventTargetStore.cs +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/ProviderEvents/ProviderEventTargetStore.cs @@ -61,8 +61,11 @@ public async Task ReadAsync(Guid targetId, CancellationT } try { + // ADR-0107 §§ 7, 9: the affected person's status, from the confined definer, under the person's User fence held + // shared until this delivery commits; anything but Active refuses the mirror. await using var command = new NpgsqlCommand(""" - SELECT id,event_id,tenant_id,authority_id,realm_id,provider_event_id,affected_user_id,source_occurred_at,source_kind,receipt_id + SELECT id,event_id,tenant_id,authority_id,realm_id,provider_event_id,affected_user_id,source_occurred_at,source_kind,receipt_id, + public.fn_identity_provider_event_subject_status(id) IS NOT DISTINCT FROM 'Active' FROM public.identity_provider_event_targets WHERE id=@target AND event_id=@event AND tenant_id=@tenant AND enqueued_at IS NOT NULL """, (NpgsqlConnection)unit.Connection, (NpgsqlTransaction)unit.Transaction!) { CommandTimeout = 5 }; @@ -74,7 +77,7 @@ FROM public.identity_provider_event_targets throw new InvalidOperationException("Provider observation has no exact retained target."); var fact = new ProviderEventAuditFact(row.GetGuid(0), row.GetGuid(9), row.GetGuid(1), TenantId.From(row.GetGuid(2)), IdentityAuthorityId.From(row.GetGuid(3)), row.GetString(4), row.GetGuid(5), UserId.From(row.GetGuid(6)), - row.GetFieldValue(7), kind); + row.GetFieldValue(7), kind, row.GetBoolean(10)); cancellationToken.ThrowIfCancellationRequested(); if (!unit.IsTenantContextIssuedOn(unit.Transaction) || unit.IsRollbackOnly) throw new InvalidOperationException("Provider observation lost its delivery owner."); diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application.Contracts/IdentityLifecycle/IIdentityScopeLifecycleReader.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application.Contracts/IdentityLifecycle/IIdentityScopeLifecycleReader.cs index ec77aff8e..d7e671e22 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application.Contracts/IdentityLifecycle/IIdentityScopeLifecycleReader.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application.Contracts/IdentityLifecycle/IIdentityScopeLifecycleReader.cs @@ -2,6 +2,7 @@ using LearnStack.SharedKernel.Identifiers; using LearnStack.SharedKernel.Permissions; using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Tenancy; namespace LearnStack.Modules.Tenancy.Application.Contracts.IdentityLifecycle; @@ -12,14 +13,36 @@ public sealed record IdentityScopeLifecycle( bool OrganizationBelongsToTenant, bool OrganizationAllowsOrdinaryWork); +/// One scope group whose lifecycle the platform scope asks about: a tenant and one organization, or none. +/// A real tenant, never the platform sentinel. +/// The organization, or for the tenant-wide group. +public sealed record IdentityLifecycleScope(TenantId TenantId, OrganizationId? OrganizationId); + public interface IIdentityScopeLifecycleReader { + /// The most groups one platform-scope read answers; the closure's participant read is bounded the same. + public const int MaximumPlatformScopes = 1024; + Task ReadAsync(TenantId tenantId, OrganizationId? organizationId, CancellationToken cancellationToken = default); /// Reads on the authorization source's actual isolated child; it never uses the ambient business owner. Task ReadAuthorizationAsync(IUnitOfWork child, AuthorizationCandidate candidate, CancellationToken cancellationToken = default); + + /// + /// The same four facts for each of , in their order, read in one statement on an entered + /// platform scope's own transaction (ADR-0107 § 7: a closure reads each participant tenant's lifecycle through this + /// port, so no cross-module join exists). It announces nothing and needs no announcement: the platform role reads the + /// Tenancy tables by its own grant. A tenant-wide scope's organization facts are false, as + /// answers them. + /// + /// + /// The list is empty or longer than , or a scope names no real tenant or an + /// unassigned organization. + /// + Task> ReadOnPlatformScopeAsync(IPlatformAdminScopeHandle handle, + IReadOnlyList scopes, CancellationToken cancellationToken = default); } /// A payload-free authorization read failure; failed actual disposal must retain its source owner. diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs index 69d989413..9bf995184 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Audit/TenancyAuditCatalogSource.cs @@ -152,6 +152,25 @@ public void Describe(IAuditCatalogBuilder builder) "platform.federation.disable", OperationType.SecurityEvent, OperationClass.Must) .DeclareOffPath( "platform.federation.disable_attempt", OperationType.SecurityEvent, OperationClass.Must) + // The two operator data-request operations of ADR-0107 § 8. Every platform off-path slug is declared from + // this source (the platform scope's tests build a Tenancy-only catalogue), whichever module the slug names: + // an inspection is audited by the scope's entry row, and `audit.redaction.apply` is the erasure completion's + // result row, whose module is `audit` because the operator result write refuses `identity` + // (ADR-0044 Amendment 17, ADR-0108 § 1). + .DeclareOffPath( + "platform.data_request.inspect", OperationType.SecurityEvent, OperationClass.Must) + .DeclareOffPath( + "audit.redaction.apply", OperationType.SecurityEvent, OperationClass.Must) + // The two operator closure operations of ADR-0107 § 7, whose rows name the platform sentinel tenant: Begin's + // result row, and Finalize's intent row on its attempt slug, written at the scope handle's checkpoint after + // the redaction it records, and its result row. Module `platform`, because the operator writes refuse + // `identity` (ADR-0044 Amendment 17, ADR-0107 § 8). + .DeclareOffPath( + "platform.closure.begin", OperationType.SecurityEvent, OperationClass.Must) + .DeclareOffPath( + "platform.closure.finalize_attempt", OperationType.SecurityEvent, OperationClass.Must) + .DeclareOffPath( + "platform.closure.finalize", OperationType.SecurityEvent, OperationClass.Must) .DeclareOffPath( "tenancy.tenant_assertion.reject", OperationType.SecurityEvent, OperationClass.Must) .DeclareOffPath( 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 000000000..409182334 --- /dev/null +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/DataRequests/TenancyUserDataParticipant.cs @@ -0,0 +1,126 @@ +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. +/// +/// +/// Retained report. The subject's own consent rows are consent_evidence, and the consent table is left +/// out of attribution_reference: ck_membership_field_consents_actor makes every row's actor and creator +/// its own subject and the table is append-only, so no consent row can attribute another person's consent to the +/// subject. Every other tenant-owned row of the context with a UserId naming the subject (a feature flag the +/// subject last changed, a setting or locale they created) is counted by the generic counter, once per row. +/// +/// +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) => UserDataParticipantGuard.RequireGroup(subject, tenant); +} + +/// Registers the Tenancy module's participant and user-reference locator from its own boundary (ADR-0107 § 1, ADR-0108 § 7). +public static class TenancyDataRequestRegistration +{ + public static IServiceCollection AddTenancyUserDataParticipant(this IServiceCollection services) + { + ArgumentNullException.ThrowIfNull(services); + services.TryAddEnumerable(ServiceDescriptor.Scoped()); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + return services; + } +} diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/DataRequests/TenancyUserReferenceLocator.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/DataRequests/TenancyUserReferenceLocator.cs new file mode 100644 index 000000000..70d245d1c --- /dev/null +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/DataRequests/TenancyUserReferenceLocator.cs @@ -0,0 +1,33 @@ +using LearnStack.Modules.Tenancy.Domain; +using LearnStack.SharedKernel.DataProtection; + +namespace LearnStack.Modules.Tenancy.Infrastructure.DataRequests; + +/// +/// Where the Tenancy module's audited aggregates hold a person or Membership reference in their audit snapshots +/// (ADR-0108 § 7). +/// +/// +/// A tenant's feature flags are contained in its snapshot, keyed by flag, so their updater is a member path. A +/// consent's Membership is a plain Guid the capture already writes as the redaction sentinel; it is declared +/// anyway, so the census holds it to the same rule as every typed reference and a change to the marker cannot leave it +/// in the clear. +/// +public sealed class TenancyUserReferenceLocator : IUserReferenceLocator +{ + public IReadOnlyCollection Redactable { get; } = + [ + .. UserReferenceDeclarations.Attribution(typeof(Tenant), typeof(Organization), typeof(TenantSetting), + typeof(MembershipFieldConsent)), + new(typeof(Tenant), UserReferencePath.Member(nameof(Tenant.FeatureFlags), nameof(TenantFeatureFlag.UpdatedBy)), + UserReferenceKind.User), + new(typeof(MembershipFieldConsent), UserReferencePath.Of(nameof(MembershipFieldConsent.SubjectUserId)), + UserReferenceKind.User), + new(typeof(MembershipFieldConsent), UserReferencePath.Of(nameof(MembershipFieldConsent.ActorUserId)), + UserReferenceKind.User), + new(typeof(MembershipFieldConsent), UserReferencePath.Of(nameof(MembershipFieldConsent.MembershipId)), + UserReferenceKind.Membership), + ]; + + public IReadOnlyCollection Retained { get; } = []; +} diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/IdentityScopeLifecycleReader.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/IdentityScopeLifecycleReader.cs index c894594f6..79c1baa75 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/IdentityScopeLifecycleReader.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/IdentityScopeLifecycleReader.cs @@ -4,14 +4,34 @@ using LearnStack.SharedKernel.Identifiers; using LearnStack.SharedKernel.Permissions; using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Tenancy; using Npgsql; using NpgsqlTypes; namespace LearnStack.Modules.Tenancy.Infrastructure.Persistence; -/// One uncached statement over Tenancy's own tables, on the caller's announced app transaction. +/// +/// One uncached statement over Tenancy's own tables, on the caller's announced app transaction, or for many scopes at once +/// on an entered platform scope's transaction. +/// public sealed class IdentityScopeLifecycleReader(IUnitOfWork unit) : IIdentityScopeLifecycleReader { + // The platform form: the same four facts per scope, one row per scope in the scopes' order. The tenant-wide scope travels + // as the nil identifier, which no organization has, so it joins no organization and its facts are false as above. The + // tenant and organization rows are read by their primary keys. + private const string PlatformLifecycleSql = """ + SELECT scope.position, + t.id IS NOT NULL AND t.deleted_at IS NULL, + t.id IS NOT NULL AND t.deleted_at IS NULL AND t.status IN ('Trial', 'Active'), + o.id IS NOT NULL, + o.id IS NOT NULL AND o.deleted_at IS NULL AND o.status = 'Active' + FROM unnest(@tenants::uuid[], @organizations::uuid[]) WITH ORDINALITY AS scope(tenant_id, organization_id, position) + LEFT JOIN public.tenants AS t ON t.id = scope.tenant_id + LEFT JOIN public.organizations AS o + ON o.tenant_id = t.id AND o.id = NULLIF(scope.organization_id, '00000000-0000-0000-0000-000000000000'::uuid) + ORDER BY scope.position + """; + private const string LifecycleSql = """ SELECT t.id IS NOT NULL AND t.deleted_at IS NULL, t.id IS NOT NULL AND t.deleted_at IS NULL AND t.status IN ('Trial', 'Active'), @@ -100,6 +120,38 @@ public async Task ReadAuthorizationAsync(IUnitOfWork chi return facts; } + public async Task> ReadOnPlatformScopeAsync(IPlatformAdminScopeHandle handle, + IReadOnlyList scopes, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(handle); + ArgumentNullException.ThrowIfNull(scopes); + if (scopes.Count is 0 or > IIdentityScopeLifecycleReader.MaximumPlatformScopes) + throw new ArgumentException("A platform lifecycle read names between one and the bounded number of scopes.", nameof(scopes)); + + var tenants = new Guid[scopes.Count]; + var organizations = new Guid[scopes.Count]; + for (var index = 0; index < scopes.Count; index++) + { + var scope = scopes[index] ?? throw new ArgumentException("A platform lifecycle read names no empty scope.", nameof(scopes)); + if (!StronglyTypedId.IsAssigned(scope.TenantId) || scope.TenantId == TenantId.PlatformSentinel + || scope.OrganizationId is { } unassigned && !StronglyTypedId.IsAssigned(unassigned)) + throw new ArgumentException("A platform lifecycle read names real tenants and assigned organizations.", nameof(scopes)); + tenants[index] = scope.TenantId.Value; + organizations[index] = scope.OrganizationId?.Value ?? Guid.Empty; + } + + // The handle's own statement facade: no announcement, and a failed statement leaves the scope to be abandoned by + // its owner, who decides whether the fault is retryable. + var rows = await handle.QueryAsync(PlatformLifecycleSql, + [new PlatformSqlParameter("tenants", tenants), new PlatformSqlParameter("organizations", organizations)], + reader => (Position: reader.GetInt64(0), Facts: new IdentityScopeLifecycle( + reader.GetBoolean(1), reader.GetBoolean(2), reader.GetBoolean(3), reader.GetBoolean(4))), + cancellationToken); + if (rows.Count != scopes.Count || rows.Where((row, index) => row.Position != index + 1).Any()) + throw new InfrastructureException("Identity scope lifecycle is unavailable."); + return [.. rows.Select(row => row.Facts)]; + } + private static async ValueTask TryDisposeAsync(IAsyncDisposable? resource) { if (resource is null) return true; diff --git a/backend/tests/Fixtures/InvitationEmailFixtureConfiguration.cs b/backend/tests/Fixtures/InvitationEmailFixtureConfiguration.cs index d30edab45..0d9ed68af 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/AccountRemovalAdapterConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/AccountRemovalAdapterConventionTests.cs new file mode 100644 index 000000000..6134b8a0c --- /dev/null +++ b/backend/tests/LearnStack.Tests.Architecture/AccountRemovalAdapterConventionTests.cs @@ -0,0 +1,356 @@ +using System.Reflection; +using System.Text.RegularExpressions; +using FluentAssertions; +using LearnStack.Infrastructure.Identity.AccountRemoval; +using LearnStack.SharedKernel.Identity; +using Xunit; + +namespace LearnStack.Tests.Architecture; + +/// +/// ADR-0107 § 7: the confined Keycloak account-removal adapter alone holds the manage-users realm client and its +/// secret key, builds only the token route and the single user-deletion route, sends only the token POST and the deletion +/// DELETE, reads no DeploymentMode, and the port it implements has one method and a closed set of holders. The client's role +/// can also create and update users, so every rule here narrows who can reach it. Each rule carries a planted control. The +/// federation adapter's own rules, including the transport allow-list this adapter's file is on, are in +/// FederationAdapterConventionTests. +/// +public sealed partial class AccountRemovalAdapterConventionTests +{ + private const string AdapterDirectory = "LearnStack.Infrastructure/Identity/AccountRemoval/"; + private const string RoutesSource = AdapterDirectory + "KeycloakAccountRemovalRoutes.cs"; + private const string AdapterSource = AdapterDirectory + "KeycloakAccountRemoval.cs"; + private const string OptionsSource = AdapterDirectory + "KeycloakAccountRemovalOptions.cs"; + private const string OwnerDirectory = "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/"; + private const string OwnerFilePrefix = OwnerDirectory + "AccountClosureOperatorOperations"; + private const string OwnerFinalizeSource = OwnerFilePrefix + ".Finalize.cs"; + + [Fact] + public void Account_Removal_Client_Is_Held_Only_By_The_Adapter() + { + ClientOffenders(Sources()).Should().BeEmpty( + "Fix: only the confined adapter names learnstack-account-removal and reads AccountRemoval:ClientSecret (ADR-0107 § 7); " + + "every other caller selects it through AccountRemovalAdapterFactory"); + } + + [Fact] + public void The_client_holder_detector_refuses_a_planted_holder() + { + var planted = new Dictionary + { + [RoutesSource] = "internal const string ClientId = \"learnstack-account-removal\";", + [AdapterSource] = "internal const string SecretKey = \"AccountRemoval:ClientSecret\";", + ["LearnStack.Api/Identity/Planted.cs"] = "var id = \"learnstack-account-removal\";", + ["Modules/Identity/LearnStack.Modules.Identity.Application/Planted.cs"] = "secrets.GetSecret(\"AccountRemoval:ClientSecret\");", + ["LearnStack.Infrastructure/Identity/Federation/Planted.cs"] = "var id = \"learnstack-account-removal\";", + ["LearnStack.Api/Identity/CommentOnly.cs"] = "// the \"learnstack-account-removal\" client is named here in prose only", + ["LearnStack.Api/Identity/Clean.cs"] = "var id = \"learnstack-federation-admin\"; secrets.GetSecret(\"Federation:ClientSecret\");", + }; + ClientOffenders(planted).Should().Equal("LearnStack.Api/Identity/Planted.cs", + "LearnStack.Infrastructure/Identity/Federation/Planted.cs", "Modules/Identity/LearnStack.Modules.Identity.Application/Planted.cs"); + } + + [Fact] + public void Account_Removal_Adapter_Admits_Only_The_Token_And_User_Routes() + { + var routes = typeof(AccountRemovalAdapterFactory).Assembly + .GetType("LearnStack.Infrastructure.Identity.AccountRemoval.KeycloakAccountRemovalRoutes", true)!; + routes.GetMethods(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly) + .Where(method => method.ReturnType == typeof(Uri)).Select(method => method.Name).Order(StringComparer.Ordinal) + .Should().Equal(["Token", "User"], "the token endpoint and the deletion of one user are the only routes"); + RouteOffenders(Sources()).Should().BeEmpty( + "Fix: build every provider route in KeycloakAccountRemovalRoutes, which admits only the token endpoint and users/{id} (ADR-0107 § 7)"); + } + + [Fact] + public void The_route_detector_refuses_planted_routes() + { + var planted = new Dictionary + { + [RoutesSource] = "new(options.AdminRealm, \"users/\" + id); const string role = \"manage-users\"; // \"users/x/reset-password\"", + [OptionsSource] = "new Uri(root + \"/admin/realms/learnstack/\");", + [AdapterDirectory + "Planted.cs"] = "new Uri(admin, \"users/\" + id + \"/role-mappings\");", + [AdapterSource] = "var uri = new Uri(\"https://kc/admin/realms/learnstack/clients\");", + [AdapterDirectory + "Sessions.cs"] = "new Uri(admin, \"users/\" + id + \"/logout\");", + [AdapterDirectory + "Groups.cs"] = "new Uri(admin, \"groups\");", + [AdapterDirectory + "Roles.cs"] = "new Uri(admin, \"roles-by-id/x\");", + [AdapterDirectory + "Clean.cs"] = "throw new ArgumentException(\"Account removal subject is not a provider user identifier.\");", + [AdapterDirectory + "Claim.cs"] = "root.TryGetProperty(\"roles\", out var roles);", + [AdapterDirectory + "Build.cs"] = "var uri = new Uri(options.AdminRealm, segment);", + [AdapterDirectory + "Builder.cs"] = "var uri = new UriBuilder(options.Issuer).Uri;", + ["LearnStack.Infrastructure/Identity/Federation/Elsewhere.cs"] = "new Uri(admin, \"users/\" + id);", + }; + planted[RoutesSource] += " new(options.AdminRealm, \"users/\" + id + \"/credentials\");"; + RouteOffenders(planted).Should().Equal(new[] + { + AdapterSource, AdapterDirectory + "Build.cs", AdapterDirectory + "Builder.cs", AdapterDirectory + "Claim.cs", + AdapterDirectory + "Groups.cs", AdapterDirectory + "Planted.cs", AdapterDirectory + "Roles.cs", RoutesSource, + AdapterDirectory + "Sessions.cs", + }.Order(StringComparer.Ordinal)); + } + + [Fact] + public void Account_Removal_Adapter_Sends_Only_The_Token_Post_And_The_User_Delete() + { + VerbOffenders(Sources()).Should().BeEmpty( + "Fix: the adapter's client can also create and update users; it sends the token POST and the deletion DELETE and no other verb (ADR-0107 § 7)"); + var adapter = Sources()[AdapterSource]; + adapter.Should().Contain("HttpMethod.Post").And.Contain("HttpMethod.Delete", + "the premise: the scan reads the file that sends the two admitted requests"); + } + + [Fact] + public void The_verb_detector_refuses_a_planted_verb() + { + VerbOffenders(new Dictionary + { + [AdapterSource] = "new HttpRequestMessage(HttpMethod.Put, uri); new HttpRequestMessage(HttpMethod.Delete, uri);", + [AdapterDirectory + "Create.cs"] = "new HttpRequestMessage(HttpMethod.Post, users); client.PostAsync(users, body);", + [AdapterDirectory + "Read.cs"] = "client.GetAsync(uri); new HttpRequestMessage(HttpMethod.Get, uri);", + [AdapterDirectory + "Custom.cs"] = "new HttpMethod(\"PATCH\");", + [AdapterDirectory + "Json.cs"] = "await client.PutAsJsonAsync(uri, body);", + [AdapterDirectory + "Clean.cs"] = "new HttpRequestMessage(HttpMethod.Delete, uri); new HttpRequestMessage(HttpMethod.Post, token);", + ["LearnStack.Api/Elsewhere.cs"] = "client.GetAsync(uri);", + }).Should().Equal(AdapterDirectory + "Create.cs", AdapterDirectory + "Custom.cs", AdapterDirectory + "Json.cs", AdapterSource, + AdapterDirectory + "Read.cs"); + } + + [Fact] + public void Account_Removal_Adapter_Does_Not_Read_DeploymentMode() + { + DeploymentModeOffenders(Sources()).Should().BeEmpty( + "Fix: the composition root selects the adapter and the Development loopback rule; the adapter never reads DeploymentMode"); + var types = typeof(AccountRemovalAdapterFactory).Assembly.GetTypes() + .Where(type => type.Namespace == typeof(AccountRemovalAdapterFactory).Namespace); + types.Should().NotBeEmpty("the premise: the namespace holds the adapter"); + types.SelectMany(type => type.GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) + .Select(field => field.FieldType) + .Concat(type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) + .SelectMany(constructor => constructor.GetParameters()).Select(parameter => parameter.ParameterType))) + .Should().NotContain(type => type.Name == "DeploymentMode"); + } + + [Fact] + public void The_deployment_mode_detector_refuses_a_planted_read() + { + DeploymentModeOffenders(new Dictionary + { + [AdapterSource] = "if (mode == DeploymentMode.SaaS) return;", + [AdapterDirectory + "Other.cs"] = "var m = DeploymentMode.SelfHosted;", + ["LearnStack.Api/Composition/AccountRemovalComposition.cs"] = "configuration.RequireDeploymentMode();", + }).Should().Equal(AdapterSource, AdapterDirectory + "Other.cs"); + } + + [Fact] + public void Account_Removal_Port_Has_One_Method_And_A_Closed_Set_Of_Holders() + { + typeof(IIdentityProviderAccountRemoval).GetMethods().Select(method => method.Name).Order(StringComparer.Ordinal) + .Should().Equal(["CanRemove", "RemoveAsync"], + "the client behind the port can create and update users, so the port deletes one account and does nothing else; " + + "its one other member is the closure Begin's local preflight, which sends nothing"); + typeof(IIdentityProviderAccountRemoval).GetMethod("CanRemove")!.ReturnType.Should().Be( + "the preflight answers synchronously, so it cannot reach the provider"); + typeof(IIdentityProviderAccountRemoval).GetProperties().Should().BeEmpty(); + PortHolders(Sources()).Should().BeEmpty( + "Fix: the port is named only by its declaration, its default, the adapter and its composition, and the closure's Finalize " + + "owner (ADR-0107 § 7: one caller). A new holder needs a deliberate entry in AdmittedPortHolders and the ADR amendment that admits it"); + } + + [Fact] + public void The_port_holder_detector_refuses_a_planted_holder() + { + PortHolders(new Dictionary + { + ["LearnStack.SharedKernel/Identity/IIdentityProviderAccountRemoval.cs"] = "public interface IIdentityProviderAccountRemoval { }", + ["LearnStack.Api/Identity/Planted.cs"] = "class C(IIdentityProviderAccountRemoval remover) { }", + ["Modules/Identity/LearnStack.Modules.Identity.Application/Planted.cs"] = "services.GetService();", + ["Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Planted.cs"] = "var x = typeof(RefusingIdentityProviderAccountRemoval);", + ["LearnStack.Api/Identity/Clean.cs"] = "// IIdentityProviderAccountRemoval is mentioned in a comment only\nvar federation = typeof(IFederationOperator);", + }).Should().Equal("LearnStack.Api/Identity/Planted.cs", "Modules/Identity/LearnStack.Modules.Identity.Application/Planted.cs", + "Modules/Tenancy/LearnStack.Modules.Tenancy.Application/Planted.cs"); + } + + [Fact] + public void Account_Removal_Port_Is_Called_Only_From_The_Closure_Finalize() + { + var sources = Sources(); + CallSiteOffenders(sources).Should().BeEmpty( + "Fix: the port's one method deletes an account with a manage-users credential and has one call, in the closure owner's " + + "Finalize part, after the redaction checkpoint (ADR-0107 § 7). The captured port is held only by the owner's partial " + + "files and is used only as the receiver of a call, never passed on or kept"); + sources.Should().ContainKey(OwnerFinalizeSource, "the premise: the scan reads the file that makes the one call"); + CallCount(SourceText.WithoutCommentsOrLiterals(sources[OwnerFinalizeSource])).Should().Be(1, "the premise: Finalize makes the call, once"); + } + + [Fact] + public void The_call_site_detector_refuses_planted_departures() + { + const string Constructor = "public sealed partial class AccountClosureOperatorOperations(IIdentityProviderAccountRemoval accountRemoval) { }"; + const string Finalize = "var outcome = await accountRemoval.RemoveAsync(providerSubject, cancellationToken);"; + Dictionary Owner(string file, string text) => new() + { + [OwnerFilePrefix + ".cs"] = Constructor, + [OwnerFinalizeSource] = Finalize, + [OwnerFilePrefix + file] = text, + }; + + // The clean shape, with prose, a literal and a comment that merely say the words, and a file that does not name the port. + CallSiteOffenders(new Dictionary + { + [OwnerFilePrefix + ".cs"] = Constructor, + [OwnerFinalizeSource] = Finalize + " // accountRemoval.RemoveAsync(again) in a comment\nvar prose = \"accountRemoval.RemoveAsync(\";", + [OwnerFilePrefix + ".Begin.cs"] = "var judged = Judge(subject); /* accountRemoval.RemoveAsync( */", + [AdapterDirectory + "AccountRemovalAdapterFactory.cs"] = "public const string PortName = \"accountRemoval\";", + ["LearnStack.Api/Identity/Clean.cs"] = "var accountRemovalSettings = 1; // accountRemoval", + }).Should().BeEmpty(); + + CallSiteOffenders(Owner(".Begin.cs", "var outcome = await accountRemoval.RemoveAsync(subject, cancellationToken);")) + .Should().Equal(OwnerFilePrefix + ".Begin.cs"); + CallSiteOffenders(Owner(".Begin.cs", "var outcome = await accountRemoval . RemoveAsync (subject, ct);")) + .Should().Equal(OwnerFilePrefix + ".Begin.cs"); + CallSiteOffenders(new Dictionary { [OwnerFilePrefix + ".cs"] = Constructor, [OwnerFinalizeSource] = Finalize + Finalize }) + .Should().Equal(OwnerFinalizeSource); + CallSiteOffenders(new Dictionary { [OwnerFilePrefix + ".cs"] = Constructor, [OwnerFinalizeSource] = "var nothing = 1;" }) + .Should().Equal(OwnerFinalizeSource); + CallSiteOffenders(Owner(".Begin.cs", "var port = accountRemoval;")).Should().Equal(OwnerFilePrefix + ".Begin.cs"); + CallSiteOffenders(Owner(".Begin.cs", "Run(() => accountRemoval);")).Should().Equal(OwnerFilePrefix + ".Begin.cs"); + CallSiteOffenders(Owner(".Begin.cs", "Helper(accountRemoval, subject);")).Should().Equal(OwnerFilePrefix + ".Begin.cs"); + CallSiteOffenders(Owner(".Begin.cs", "var remove = accountRemoval.RemoveAsync;")).Should().Equal(OwnerFilePrefix + ".Begin.cs"); + CallSiteOffenders(new Dictionary + { + [OwnerFilePrefix + ".cs"] = Constructor, + [OwnerFinalizeSource] = Finalize, + ["LearnStack.Api/Identity/Planted.cs"] = "await accountRemoval.RemoveAsync(subject, ct);", + [OwnerDirectory + "IdentityDeletion.cs"] = "var port = accountRemoval;", + }).Should().Equal("LearnStack.Api/Identity/Planted.cs", OwnerDirectory + "IdentityDeletion.cs"); + } + + private static Dictionary Sources() => + Directory.EnumerateFiles(SourceScan.SourceRoot, "*.cs", SearchOption.AllDirectories) + .Where(path => !path.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal) + && !path.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal)) + .ToDictionary(path => Path.GetRelativePath(SourceScan.SourceRoot, path).Replace(Path.DirectorySeparatorChar, '/'), File.ReadAllText); + + /// A source with its whole-line comments removed: these files argue in prose about the very literals they confine. + private static string Code(string source) => WholeLineComment().Replace(source, string.Empty); + + private static List ClientOffenders(IReadOnlyDictionary sources) => + [.. sources.Where(pair => pair.Key.EndsWith(".cs", StringComparison.Ordinal) + && (Code(pair.Value).Contains("learnstack-account-removal", StringComparison.Ordinal) && pair.Key != RoutesSource + || Code(pair.Value).Contains("AccountRemoval:ClientSecret", StringComparison.Ordinal) && pair.Key != AdapterSource)) + .Select(pair => pair.Key).Order(StringComparer.Ordinal)]; + + /// Every string literal in the adapter directory that names an Admin, user, client, role, group or session path. + private static List RouteOffenders(IReadOnlyDictionary sources) + { + var admitted = new HashSet(StringComparer.Ordinal) { "users/" }; + var offenders = new SortedSet(StringComparer.Ordinal); + foreach (var (path, text) in sources.Where(pair => pair.Key.StartsWith(AdapterDirectory, StringComparison.Ordinal))) + { + foreach (Match literal in StringLiteral().Matches(Code(text))) + { + var value = literal.Groups["value"].Value; + var routeLike = RouteSegment().IsMatch(value); + if (!routeLike) continue; + // "roles" is the token claim the adapter narrows; it is a route-like word, never a route, because no URI is built here. + var allowed = path == RoutesSource && admitted.Contains(value) || path == OptionsSource && value == "/admin/realms/learnstack/" + || path == AdapterSource && value == "roles"; + if (!allowed) offenders.Add(path); + } + // Every URI is derived from the realm in the routes and options files; no other file builds or extends one. + if (path != RoutesSource && path != OptionsSource && UriConstruction().IsMatch(Code(text))) offenders.Add(path); + } + return [.. offenders]; + } + + private static List VerbOffenders(IReadOnlyDictionary sources) => + [.. sources.Where(pair => pair.Key.StartsWith(AdapterDirectory, StringComparison.Ordinal) && NonAdmittedVerb().IsMatch(Code(pair.Value))) + .Select(pair => pair.Key).Order(StringComparer.Ordinal)]; + + private static List DeploymentModeOffenders(IReadOnlyDictionary sources) => + [.. sources.Where(pair => pair.Key.StartsWith(AdapterDirectory, StringComparison.Ordinal) + && pair.Value.Contains("DeploymentMode", StringComparison.Ordinal)) + .Select(pair => pair.Key).Order(StringComparer.Ordinal)]; + + /// + /// Every production file that may name the port or its concrete types, with its role. The closure owner is the one + /// caller ADR-0107 § 7 admits: its constructor file takes the port, and its Finalize part calls it through that field + /// without naming the type, so the Finalize file is not a holder and stays out of this list. + /// + private static readonly HashSet AdmittedPortHolders = new(StringComparer.Ordinal) + { + "LearnStack.SharedKernel/Identity/IIdentityProviderAccountRemoval.cs", + "LearnStack.SharedKernel/Identity/RefusingIdentityProviderAccountRemoval.cs", + AdapterSource, + AdapterDirectory + "AccountRemovalAdapterFactory.cs", + "LearnStack.Api/Composition/AccountRemovalComposition.cs", + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityFoundationRegistration.cs", + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/AccountClosureOperatorOperations.cs", + }; + + /// + /// The one call. accountRemoval is the closure owner's captured port: only the owner's partial files (the constructor, + /// Begin and Finalize parts) may name it, only as the receiver of a call (never aliased, passed on or captured), and its one + /// method is called exactly once, in the Finalize part. A file that names the port types is already confined by + /// ; this rule covers the files that reach the port without naming a type. + /// + private static List CallSiteOffenders(IReadOnlyDictionary sources) + { + var offenders = new SortedSet(StringComparer.Ordinal); + foreach (var (path, text) in sources.Where(pair => pair.Key.EndsWith(".cs", StringComparison.Ordinal))) + { + var code = SourceText.WithoutCommentsOrLiterals(text); + var isOwner = path.StartsWith(OwnerFilePrefix, StringComparison.Ordinal); + if (CapturedPort().IsMatch(code) && !isOwner) + offenders.Add(path); + else if (isOwner && CapturedPortUse().Matches(code).Any(use => !use.Groups["receiver"].Success && !use.Groups["declaration"].Success)) + offenders.Add(path); + if (CallCount(code) != (path == OwnerFinalizeSource ? 1 : 0)) + offenders.Add(path); + } + + return [.. offenders]; + } + + private static int CallCount(string code) => CapturedPortCall().Count(code); + + private static List PortHolders(IReadOnlyDictionary sources) => + [.. sources.Where(pair => !AdmittedPortHolders.Contains(pair.Key) && AccountRemovalNames().IsMatch(Code(pair.Value))) + .Select(pair => pair.Key).Order(StringComparer.Ordinal)]; + + [GeneratedRegex(@"^\s*//.*$", RegexOptions.Multiline)] + private static partial Regex WholeLineComment(); + + [GeneratedRegex("\"(?(?:[^\"\\\\]|\\\\.)*)\"")] + private static partial Regex StringLiteral(); + + /// A string that names an Admin API path segment: realm, user, client, role, group, session, credential or flow. + [GeneratedRegex("(?:^|/)(?:admin/realms|users|clients|roles|roles-by-id|groups|sessions|logout|credentials|role-mappings|identity-provider|authentication|required-actions|execute-actions|reset-password)(?:/|$)")] + private static partial Regex RouteSegment(); + + /// A URI built or extended: the realm and token members of the options, a new Uri(, or a UriBuilder. + [GeneratedRegex(@"\bAdminRealm\b|\bTokenEndpoint\b|new\s+Uri\s*\(|\bUriBuilder\b")] + private static partial Regex UriConstruction(); + + /// A verb other than POST and DELETE: an HttpMethod member, a constructed method, or a verb-named client helper. + [GeneratedRegex(@"\bHttpMethod\.(Get|Put|Patch|Head|Options|Trace|Connect)\b|new\s+HttpMethod\s*\(|\.(Get|Put|Patch|Head|Post|Delete)(String|ByteArray|Stream|FromJson|AsJson)?Async\s*\(")] + private static partial Regex NonAdmittedVerb(); + + [GeneratedRegex(@"\b(IIdentityProviderAccountRemoval|RefusingIdentityProviderAccountRemoval|KeycloakAccountRemoval|AccountRemovalAdapterFactory)\b")] + private static partial Regex AccountRemovalNames(); + + /// The closure owner's captured port, by its parameter name, outside comments and literals. + [GeneratedRegex(@"\baccountRemoval\b")] + private static partial Regex CapturedPort(); + + /// + /// Each use of the captured port: as the receiver of a member access (accountRemoval.) or in the constructor's own + /// parameter declaration (the port type then the name). Any other use matches neither group: an alias, an argument, a capture. + /// + [GeneratedRegex(@"(?\bIIdentityProviderAccountRemoval\s+accountRemoval\b)|\baccountRemoval\b(?\s*\.\s*\w+\s*\()?")] + private static partial Regex CapturedPortUse(); + + /// A call of the port's deleting method through the captured port, with any spacing. + [GeneratedRegex(@"\baccountRemoval\s*\.\s*RemoveAsync\s*\(")] + private static partial Regex CapturedPortCall(); +} diff --git a/backend/tests/LearnStack.Tests.Architecture/AggregateWriteTests.cs b/backend/tests/LearnStack.Tests.Architecture/AggregateWriteTests.cs index 189472e1e..19cf271c7 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,85 @@ 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)]); + // ADR-0107 § 5: the erasure job is a one-root message handler; the Membership, Invitation and export-request writes + // are the Identity participant's, through the erasure service, which is no message handler. Its roots are counted + // here so the hole stays visible: it writes exactly these three and no other. + AggregatesWrittenBy(typeof(DataErasureJobHandlers).GetConstructors().Single()) + .Should().BeEquivalentTo([typeof(DataSubjectRequest)], "the erasure job writes the request root only"); + // ADR-0107 § 7: a closure's per-group fan-out is an operator act in the operator-act namespace, not a data-request + // handler: it writes the request root only, the fan-out it creates and the erasure it cancels and replaces. + var fanOut = typeof(DataRequestService).Assembly.GetType( + "LearnStack.Modules.Identity.Application.OperatorActs.FanOutClosureCommandHandler", throwOnError: true)!; + IsMessageHandler(fanOut).Should().BeTrue(); + AggregatesWrittenBy(fanOut.GetConstructors().Single()) + .Should().BeEquivalentTo([typeof(DataSubjectRequest)], "a closure's fan-out writes the request root only"); + IsMessageHandler(typeof(DataErasureService)).Should().BeFalse("the erasure service is reached only through the participant"); + AggregatesWrittenBy(typeof(DataErasureService).GetConstructors().Single()) + .Should().BeEquivalentTo([typeof(DataSubjectRequest), typeof(Membership), typeof(Invitation)], + "the erasure cancels an export request, erases Memberships and revokes invitations, and nothing else"); + var handlers = typeof(DataRequestService).Assembly.GetTypes() + .Where(type => type.Namespace == typeof(DataRequestService).Namespace && IsMessageHandler(type) + && type != typeof(DataExportJobHandlers) && type != typeof(DataErasureJobHandlers)) + .ToList(); + 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(17, "the seventeen live-session data-request operations each have one thin handler"); + retained.Should().HaveCount(10, "the ten 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 = 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. @@ -331,6 +411,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/AuditConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs index 3409a5f05..9662ccba7 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs @@ -450,10 +450,10 @@ private sealed class AuditEntryWriterProbe(AuditDbContext context) public void AuditEntry_Is_AppendOnly() { // No UPDATE and no DELETE against audit_log anywhere in backend/src, and the - // exception list is CLOSED and NAMED: the GDPR redaction handler, the retention - // purge job, and a module's IUserReferenceLocator. None of the three ships yet — - // they land in Phase 11 and Phase 03 — so today the honest expectation is that - // there are no sites at all, and the list exists so that adding one is a decision + // exception list is CLOSED and NAMED: the one redaction executor of ADR-0108, which + // updates the six granted columns and never deletes. Modules only declare where their + // references live (IUserReferenceLocator) and never name the table; Phase 11's + // retention purge adds its own path when it lands, so adding a site is a decision // rather than an edit. // // The database-level guard is AuditLog_Update_Is_Column_Restricted; this is the @@ -461,17 +461,32 @@ public void AuditEntry_Is_AppendOnly() // policy is consulted. var offenders = new List(); var sawTheStore = false; + var sanctioned = new HashSet(StringComparer.Ordinal); foreach (var file in SourceFiles()) { var code = SourceText.WithoutComments(File.ReadAllText(file)); - var relative = Path.GetRelativePath(RepositoryPaths.BackendSrc(), file); + var relative = Path.GetRelativePath(RepositoryPaths.BackendSrc(), file).Replace('\\', '/'); sawTheStore |= code.Contains("INSERT INTO audit_log", StringComparison.Ordinal); - if (AuditLogMutation().IsMatch(code) && !SanctionedRedactionSites.Contains(relative)) + if (!AuditLogMutation().IsMatch(code)) + { + continue; + } + + if (!SanctionedRedactionSites.Contains(relative)) { offenders.Add(relative); + continue; + } + + // A redaction site rewrites columns; the DELETE the platform role holds is the + // retention purge's, and ADR-0108 keeps the executor from it. + sanctioned.Add(relative); + if (AuditLogDelete().IsMatch(code)) + { + offenders.Add(relative + " (a DELETE at a redaction site)"); } } @@ -479,9 +494,14 @@ public void AuditEntry_Is_AppendOnly() // must at least have read the one statement that does write audit_log. sawTheStore.Should().BeTrue("the premise: the sweep read PostgresAuditStore's INSERT"); + // And each sanctioned site is a file that still updates the log, so an entry left + // behind by a rename cannot later exempt an unrelated file of the same name. + sanctioned.Should().BeEquivalentTo(SanctionedRedactionSites, + "every sanctioned site exists and carries the UPDATE it is sanctioned for"); + offenders.Should().BeEmpty( - "audit_log is append-only; the three sanctioned redaction sites land with " - + "Phase 03 and Phase 11, and widening that list requires an ADR"); + "audit_log is append-only; the one sanctioned redaction site is the ADR-0108 " + + "executor, and widening that list requires an ADR"); } [Fact] @@ -510,6 +530,11 @@ public void The_AppendOnly_Sweep_Can_Actually_Fail() AuditLogMutation().IsMatch("DELETE FROM audit_log_archive").Should().BeFalse(); AuditLogMutation().IsMatch("UPDATE \"audit_log_archive\" SET x = 1").Should().BeFalse(); AuditLogMutation().IsMatch("UPDATE public.audit_log2 SET x = 1").Should().BeFalse(); + + // The redaction site's own refusal: a DELETE beside its UPDATE, however it is spelled. + AuditLogDelete().IsMatch("delete from only public . audit_log where id = @id").Should().BeTrue(); + AuditLogDelete().IsMatch("UPDATE audit_log AS a SET ip_address = NULL").Should().BeFalse(); + AuditLogDelete().IsMatch("DELETE FROM audit_log_archive").Should().BeFalse(); } [Fact] @@ -530,16 +555,21 @@ public void IAuditStore_Exposes_No_Update_Method() } /// - /// The files the standard's three sites are, by exact path under backend/src. + /// The files that may update audit_log, by exact path under backend/src. /// /// - /// Empty, because none of them exists yet: Phase 03's GDPR redaction handler and each - /// module's IUserReferenceLocator, and Phase 11's retention purge. The first to - /// land adds its own path here, so it is exempted by NAME — never by a substring, which - /// the first version used and which exempted any file in the Audit module whose path - /// happened to contain "Redaction" (the fourth review of Packet 9). + /// One: the redaction executor of ADR-0108 § 2, which replaces the three sites the + /// corpus once named (a redaction handler, each module's IUserReferenceLocator, + /// the retention purge) with one Audit-owned file; a locator only declares paths. + /// Phase 11's retention purge adds its own path when it lands. A site is exempted by + /// NAME — never by a substring, which the first version used and which exempted any file + /// in the Audit module whose path happened to contain "Redaction" (the fourth review of + /// Packet 9). /// - private static readonly HashSet SanctionedRedactionSites = new(StringComparer.Ordinal); + private static readonly HashSet SanctionedRedactionSites = new(StringComparer.Ordinal) + { + "LearnStack.Infrastructure.Audit/AuditRedactionExecutor.cs", + }; private static IEnumerable SourceFiles() => Directory @@ -556,6 +586,12 @@ private static IEnumerable SourceFiles() => RegexOptions.IgnoreCase)] private static partial Regex AuditLogMutation(); + /// A DELETE whose target is audit_log itself, spelled as reads it. + [GeneratedRegex( + @"\bDELETE\s+FROM(?:\s+ONLY)?\s+(?:""?[A-Za-z_][A-Za-z0-9_]*""?\s*\.\s*)?""?audit_log""?(?![A-Za-z0-9_])", + RegexOptions.IgnoreCase)] + private static partial Regex AuditLogDelete(); + /// /// The seven `OperationType` spellings the standard's table carries. /// diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ConsentAndCustomFields.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ConsentAndCustomFields.cs index 65f546107..890b1a753 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ConsentAndCustomFields.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ConsentAndCustomFields.cs @@ -32,6 +32,46 @@ 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), + "CreateErasure" => typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.CreateRetainedDataErasureCommand), + "CreateClosure" => typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.CreateRetainedAccountClosureCommand), + "Cancel" => typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.CancelRetainedDataRequestCommand), + "RevokeExport" => typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.RevokeRetainedDataExportCommand), + "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.DescriptorInterpreter.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.DescriptorInterpreter.cs index 9ce7f96e5..f771d1d67 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.ProtectedAdministration.Controls.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ProtectedAdministration.Controls.cs index 15451dab7..eadf9eba5 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 aeba99c19..6649e8468 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 faad4e8cb..6b9a82a58 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ProtectedDescriptors.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.ProtectedDescriptors.cs @@ -34,8 +34,25 @@ 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"), + new(30, "CreateRetainedDataExport", 8, "DataSubjectRequest", null), + new(31, "CancelRetainedDataRequest", 8, "DataSubjectRequest", "ExpectedVersion"), + new(32, "CreateOwnDataErasure", 8, "DataSubjectRequest", null), + new(33, "CreateDataErasureForSubject", 8, "DataSubjectRequest", null), + new(34, "CreateRetainedDataErasure", 8, "DataSubjectRequest", null), + new(35, "RevokeRetainedDataExport", 8, "DataSubjectRequest", "ExpectedArtifactVersion"), + new(36, "CreateOwnAccountClosure", 8, "DataSubjectRequest", null), + new(37, "CreateRetainedAccountClosure", 8, "DataSubjectRequest", null), ]; + /// The keyed creations: the three 201 creations and ADR-0106 § 10's eight 202 data-request creations. + private static bool Creates(int operation) => operation is 7 or 11 or 15 or 24 or 25 or 30 or 32 or 33 or 34 or 36 or 37; + 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 +80,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 +125,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 +133,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 +167,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 or 30 or 32 or 33 or 34 or 36 or 37 => "DataRequest(awaitsender.Send(command,cancellationToken),null)", + 26 or 27 or 31 => "DataRequest(awaitsender.Send(command,cancellationToken),command.RequestId)", + 28 or 29 or 35 => "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 b458c984a..7d74b29dd 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticatedHttpSurfaceTests.cs @@ -251,6 +251,80 @@ 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", "CreateErasure", "POST", "identity/me/data-requests", "erasures", + "CreateOwnDataErasure", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.CreateOwnDataErasureCommand), "LearnStackOperation:identity.data_request.create_own_erasure", + typeof(LearnStack.Api.Identity.DataErasureAcceptedResponse), 202, 32, new(OperationClass.Must, OperationType.Create, "identity.data_request.create_erasure", typeof(LearnStack.Modules.Identity.Domain.DataSubjectRequest))), + new("LearnStack.Api.Identity.OwnDataRequestsController", "CreateClosure", "POST", "identity/me/data-requests", "closures", + "CreateOwnAccountClosure", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.CreateOwnAccountClosureCommand), "LearnStackOperation:identity.data_request.create_own_closure", + typeof(LearnStack.Api.Identity.AccountClosureAcceptedResponse), 202, 36, new(OperationClass.Must, OperationType.Create, "identity.data_request.create_closure", 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", "CreateErasure", "POST", "identity/data-requests", "erasures", + "CreateDataErasureForSubject", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.CreateDataErasureForSubjectCommand), "LearnStackOperation:identity.data_request.create_erasure", + typeof(LearnStack.Api.Identity.DataErasureAcceptedResponse), 202, 33, new(OperationClass.Must, OperationType.Create, "identity.data_request.create_erasure", 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-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", "CreateErasure", "POST", "identity/data-request-entry", "erasures", + "CreateRetainedDataErasure", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.CreateRetainedDataErasureCommand), "LearnStackOperation:identity.data_request.create_retained_erasure", + typeof(LearnStack.Api.Identity.DataErasureAcceptedResponse), 202, 34, new(OperationClass.Must, OperationType.Create, "identity.data_request.create_erasure", typeof(LearnStack.Modules.Identity.Domain.DataSubjectRequest))), + new("LearnStack.Api.Identity.DataRequestEntryController", "CreateClosure", "POST", "identity/data-request-entry", "closures", + "CreateRetainedAccountClosure", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.CreateRetainedAccountClosureCommand), "LearnStackOperation:identity.data_request.create_retained_closure", + typeof(LearnStack.Api.Identity.AccountClosureAcceptedResponse), 202, 37, new(OperationClass.Must, OperationType.Create, "identity.data_request.create_closure", 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", "RevokeExport", "POST", "identity/data-request-entry", "revocations", + "RevokeRetainedDataExport", typeof(LearnStack.Modules.Identity.Application.Contracts.DataRequests.RevokeRetainedDataExportCommand), "LearnStackOperation:identity.data_request.revoke_retained_export", + typeof(LearnStack.Api.Identity.AdministrationVersionReceipt), 200, 35, new(OperationClass.Must, OperationType.Delete, "identity.data_export.revoke", typeof(LearnStack.Modules.Identity.Domain.DataExportArtifact))), + 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", @@ -305,9 +379,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(96, "the census closes the surface at 96 MVC actions"); + Endpoints.Select(endpoint => endpoint.Request).Distinct().Should().HaveCount(91, + "Standard 21 publishes 91 distinct IRequest roots for the 96 actions"); }); /// ADR-0064's controls mutate the same production route census. @@ -459,7 +533,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(70, "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 twenty-four data-request requests (fifteen live, nine retained-entry) has its own thin handler"); Violations(modules, facts).Should().BeEmpty(); AssertPolicyMetadataControls(modules, facts); AssertControllerMetadataControls(modules, facts); @@ -675,6 +749,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 000000000..91c1adf54 --- /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 7ee15dbda..966a80e19 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 60e4ecbec..715c982ea 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/BackgroundJobAdmissionBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobAdmissionBoundaryTests.cs index f04b745fd..cec7405f4 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 2a128949c..42fbed1ac 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; @@ -35,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", "CreateErasure", "CreateClosure", "List", "Get", "Cancel", "Revoke"]), + ("LearnStack.Api.Identity.OwnDataExportTicketsController", ["MintTicket"]), + ("LearnStack.Api.Identity.OwnDataExportChunksController", ["ReadChunk"]), + ("LearnStack.Api.Identity.DataRequestsController", ["Create", "CreateErasure", "List", "Get", "Cancel", "Revoke"]), + ("LearnStack.Api.Identity.DataRequestEntryController", ["Scopes", "Requests", "CreateExport", "CreateErasure", "CreateClosure", "Cancel", "RevokeExport", "MintTicket", "ReadChunk"]), ("LearnStack.Api.PublicReads.PublicSignInController", ["Get", "Head"]), ("LearnStack.Api.Identity.FederationController", ["Get", "Configure", "RotateSecret", "Rename", "StartTest", "RecordTestResult", "Activate", "Disable", "Enable", "Delete", "Resume"]), @@ -167,7 +175,12 @@ 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", + "identity.data_erasure_tenant.v1", "identity.data_erasure_organization.v1"); + CheckDataExportJobManifest(registry); + CheckDataErasureJobManifest(registry); foreach (var (key, scope, prepare, finalize) in new[] { ("identity.invitation_email_tenant.v1", BackgroundJobScope.TenantWide, typeof(PrepareTenantInvitationEmailCommand), typeof(FinalizeTenantInvitationEmailCommand)), @@ -206,6 +219,128 @@ 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"); + } + } + + /// + /// ADR-0107 § 2, § 5: the erasure adds exactly two transactional, identifier-only, version-1 definitions, one per scope + /// group, with no capacity group and no nested request; their declaration source is bound like the export's. + /// + private static void CheckDataErasureJobManifest(BackgroundJobDefinitionRegistry registry) + { + foreach (var (key, scope, root) in new[] + { + ("identity.data_erasure_tenant.v1", BackgroundJobScope.TenantWide, typeof(RunTenantDataErasureCommand)), + ("identity.data_erasure_organization.v1", BackgroundJobScope.Organization, typeof(RunOrganizationDataErasureCommand)), + }) + { + registry.TryGet(key, out var definition).Should().BeTrue(); + definition!.OwnerModule.Should().Be("identity"); + definition.ParameterType.Should().Be(); + 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/DataErasureJobRegistration.cs")); + DataErasureManifestSourceIsBound(source).Should().BeTrue(); + foreach (var (before, after) in new[] + { + ("BackgroundJobScope.Organization, typeof(RunOrganizationDataErasureCommand)", "BackgroundJobScope.TenantWide, typeof(RunOrganizationDataErasureCommand)"), + ("BackgroundJobDefinitionReadiness.Active", "BackgroundJobDefinitionReadiness.Pending"), + ("\"transactional\"", "\"external\""), + ("BackgroundJobProfileRegistration.Transactional(root)", "BackgroundJobProfileRegistration.Transactional(typeof(object))"), + ("typeof(DataErasureJobParameters), scope", "typeof(DataExportJobParameters), scope"), + }) + { + var dirty = source.Replace(before, after, StringComparison.Ordinal); + dirty.Should().NotBe(source); + DataErasureManifestSourceIsBound(dirty).Should().BeFalse("the two erasure declarations cannot broaden their scope, readiness, queue, parameters or root"); + } + } + + private static bool DataErasureManifestSourceIsBound(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(DataErasureJobKeys.TenantErasure.Value, BackgroundJobScope.TenantWide, typeof(RunTenantDataErasureCommand))", + "Definition(DataErasureJobKeys.OrganizationErasure.Value, BackgroundJobScope.Organization, typeof(RunOrganizationDataErasureCommand))", + }; + return definition?.ExpressionBody is { } body && SyntaxFactory.AreEquivalent(body.Expression, SyntaxFactory.ParseExpression( + "new(key, typeof(DataErasureJobHandlers), typeof(DataErasureJobParameters), scope, BackgroundJobDefinitionReadiness.Active, " + + "\"transactional\", BackgroundJobProfileRegistration.Transactional(root))")) + && calls.Length == 2 && calls.Select((call, index) => SyntaxFactory.AreEquivalent(call, SyntaxFactory.ParseExpression(expectedCalls[index]))).All(equal => equal); + } + + 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 +393,22 @@ 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"); + var dataErasure = types[("LearnStack.Modules.Identity.Infrastructure", typeof(DataErasureJobRegistration).FullName!)]; + var dataErasureDefinition = dataErasure.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, data-export and data-erasure business-definition constructors", + constructions.Select(site => MethodId(site.Owner)), + [MethodId(invitationDefinition), MethodId(dataExportDefinition), MethodId(dataErasureDefinition)]); 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.Owner != dataErasureDefinition + || site.Instruction.OpCode != OpCodes.Newobj)) offenders.Add("Production business/recurrence declaration: " + MethodId(site.Owner)); } diff --git a/backend/tests/LearnStack.Tests.Architecture/DataErasureWitnessConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/DataErasureWitnessConventionTests.cs new file mode 100644 index 000000000..ee28b46a3 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Architecture/DataErasureWitnessConventionTests.cs @@ -0,0 +1,102 @@ +using System.Reflection; +using FluentAssertions; +using LearnStack.Modules.Identity.Domain; +using Mono.Cecil; +using Mono.Cecil.Cil; +using Xunit; + +namespace LearnStack.Tests.Architecture; + +/// +/// ADR-0107 § 5: the erasure domain operations run only under the erasure witness, and the witness has one production +/// minter. These rules pin the closed owners: the witness's private construction, its one minting source and the one +/// capture site, and the one service that calls each erasure operation; a planted extra minter or caller is detected. +/// +public sealed class DataErasureWitnessConventionTests +{ + private const string Witness = "LearnStack.Modules.Identity.Domain.DataErasureWitness"; + private const string Service = "LearnStack.Modules.Identity.Application.DataRequests.DataErasureService"; + private const string Source = Service + "/FulfillingErasure"; + + /// The erasure operations and the one service method that calls each. + private static readonly (string Type, string Method, string Caller)[] Operations = + [ + ("LearnStack.Modules.Identity.Domain.Membership", nameof(Membership.RemoveAssignmentsForErasure), Service + ".EraseMembershipsAsync"), + ("LearnStack.Modules.Identity.Domain.Membership", nameof(Membership.ClearProfileForErasure), Service + ".EraseMembershipsAsync"), + ("LearnStack.Modules.Identity.Domain.Membership", nameof(Membership.RevokeForErasure), Service + ".EraseMembershipsAsync"), + ("LearnStack.Modules.Identity.Domain.Invitation", nameof(Invitation.RevokeForErasure), Service + ".RevokeIssuedInvitationsAsync"), + ]; + + [Fact] + public void Erasure_witness_has_a_private_construction_and_one_production_minting_source() + { + typeof(DataErasureWitness).IsSealed.Should().BeTrue(); + typeof(DataErasureWitness).GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) + .Should().ContainSingle().Which.IsPrivate.Should().BeTrue(); + typeof(DataErasureWitness).GetProperties().Should().OnlyContain(property => property.SetMethod == null); + ProductionAssemblies.All().SelectMany(assembly => assembly.GetTypes()) + .Where(type => !type.IsAbstract && typeof(DataErasureWitness.MintingSource).IsAssignableFrom(type)) + .Select(type => type.FullName!.Replace('+', '/')).Should().Equal(Source); + foreach (var (type, method, _) in Operations) + typeof(Membership).Assembly.GetType(type)!.GetMethod(method)!.GetParameters() + .Should().Contain(parameter => parameter.ParameterType == typeof(DataErasureWitness), $"{method} runs only under the witness"); + } + + /// The canonical rule: the capture, the construction and each erasure operation have closed callers. + [Fact] + public void Erasure_Operations_Run_Only_Under_The_Erasure_Witness() + { + 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 != "" + && !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().Equal(Source + ".Mint"); + Callers(Witness, ".ctor").Should().Equal(Witness + "/MintingSource.Capture"); + foreach (var (type, method, caller) in Operations) + Callers(type, method).Should().Equal([caller], $"only the erasure service calls {method}"); + + var domain = modules.Single(module => module.Assembly.Name.Name == "LearnStack.Modules.Identity.Domain"); + var membership = domain.Types.Single(type => type.FullName == "LearnStack.Modules.Identity.Domain.Membership"); + var target = membership.Methods.Single(method => method.Name == nameof(Membership.ClearProfileForErasure)); + var probe = new TypeDefinition("ReviewProbe", "ErasureBorrower", Mono.Cecil.TypeAttributes.Class, domain.TypeSystem.Object); + var borrow = new MethodDefinition("Borrow", Mono.Cecil.MethodAttributes.Static, domain.TypeSystem.Void); + borrow.Body.Instructions.Add(Instruction.Create(OpCodes.Call, target)); + borrow.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + probe.Methods.Add(borrow); + domain.Types.Add(probe); + Callers("LearnStack.Modules.Identity.Domain.Membership", nameof(Membership.ClearProfileForErasure)) + .Should().Contain("ReviewProbe.ErasureBorrower.Borrow", "a planted caller must stay visible to the census"); + domain.Types.Remove(probe); + + // A file-local type is emitted under a mangled name that starts with '<'; it is as real a caller as any. + var local = new TypeDefinition("", "F0123456789ABCDEF__ErasureBorrower", Mono.Cecil.TypeAttributes.Class, domain.TypeSystem.Object); + var borrowLocal = new MethodDefinition("Borrow", Mono.Cecil.MethodAttributes.Static, domain.TypeSystem.Void); + borrowLocal.Body.Instructions.Add(Instruction.Create(OpCodes.Call, target)); + borrowLocal.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + local.Methods.Add(borrowLocal); + domain.Types.Add(local); + Callers("LearnStack.Modules.Identity.Domain.Membership", nameof(Membership.ClearProfileForErasure)) + .Should().Contain("F0123456789ABCDEF__ErasureBorrower.Borrow", "a file-local caller must stay visible to the census"); + domain.Types.Remove(local); + + var witness = domain.Types.SelectMany(Flatten).Single(type => type.FullName == Witness); + var minter = witness.NestedTypes.Single(type => type.Name == "MintingSource"); + var rogue = new TypeDefinition("ReviewProbe", "ErasureMinter", Mono.Cecil.TypeAttributes.Class, minter); + domain.Types.Add(rogue); + modules.SelectMany(module => module.Types).SelectMany(Flatten) + .Where(type => !type.IsAbstract && type.BaseType?.FullName == minter.FullName).Select(type => type.FullName) + .Should().BeEquivalentTo([Source, "ReviewProbe.ErasureMinter"], "a planted minter must stay visible to the census"); + domain.Types.Remove(rogue); + } + finally { foreach (var module in modules) module.Dispose(); } + } + + private static IEnumerable Flatten(TypeDefinition type) => new[] { type }.Concat(type.NestedTypes.SelectMany(Flatten)); +} diff --git a/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs index 936f21007..97b2375bf 100644 --- a/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs @@ -234,6 +234,8 @@ [.. sources.Where(pair => pair.Key.StartsWith(AdapterDirectory, StringComparison { [FetcherSource] = "the only tenant-URL fetcher: ADR-0099 § Bounded egress guards every address it dials", [AdapterSource] = "the federation admin client: the fixed tenant-realm issuer only (KeycloakFederationOptions)", + ["LearnStack.Infrastructure/Identity/AccountRemoval/KeycloakAccountRemoval.cs"] = + "the closure's account-removal client (ADR-0107 § 7): the fixed tenant-realm issuer only (KeycloakAccountRemovalOptions)", ["LearnStack.Infrastructure/Identity/ProviderEvents/KeycloakIdentityEventProvider.cs"] = "the provider event reader (ADR-0097): the fixed tenant-realm issuer only", ["LearnStack.Api/Authentication/TenantAuthenticationBackchannel.cs"] = diff --git a/backend/tests/LearnStack.Tests.Architecture/GlobalIdentityModelTests.cs b/backend/tests/LearnStack.Tests.Architecture/GlobalIdentityModelTests.cs index 3f2bc2346..64d7abfe5 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/IdempotencyConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/IdempotencyConventionTests.cs index 6402323cd..996cc3fb7 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), typeof(ReadRetainedDataRequestReceiptQuery), ]; [Fact] @@ -49,6 +51,8 @@ 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"); @@ -194,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)) @@ -225,6 +234,20 @@ 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), + [ProtectedAdministrationOperation.CreateRetainedDataExport] = typeof(ReadRetainedDataRequestReceiptQuery), + [ProtectedAdministrationOperation.CancelRetainedDataRequest] = typeof(ReadRetainedDataRequestReceiptQuery), + [ProtectedAdministrationOperation.CreateOwnDataErasure] = typeof(ReadOwnDataRequestReceiptQuery), + [ProtectedAdministrationOperation.CreateDataErasureForSubject] = typeof(ReadDataRequestReceiptQuery), + [ProtectedAdministrationOperation.CreateRetainedDataErasure] = typeof(ReadRetainedDataRequestReceiptQuery), + [ProtectedAdministrationOperation.RevokeRetainedDataExport] = typeof(ReadRetainedDataRequestReceiptQuery), + [ProtectedAdministrationOperation.CreateOwnAccountClosure] = typeof(ReadOwnDataRequestReceiptQuery), + [ProtectedAdministrationOperation.CreateRetainedAccountClosure] = typeof(ReadRetainedDataRequestReceiptQuery), }; private static string[] AdmissionOffenders(ModuleDefinition[] modules) @@ -375,7 +398,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 0cf7c2023..ebbbaad64 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.AuthorizationEvidence.cs @@ -33,6 +33,8 @@ 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 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"; @@ -57,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), @@ -74,6 +78,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 +137,8 @@ private static readonly (string Owner, string Method, int Count)[] CurrentDecisi (InvitationEntryWriteStore, "UpdateAsync", 1), (InvitationAuthorization, "Matches", 1), (FederationAuthorization, "Matches", 1), + (DataRequestAuthorization, "Matches", 1), + (RetainedDataRequestAdmission, "For", 1), (InvitationPolicyAuthorization, "OwnAsync", 1), (ReadAuthorization, "Matches", 1), (NavigationReader, "Matches", 1), @@ -386,15 +394,18 @@ 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), + (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/IdentityAuditConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.cs index 85caaf697..7dc8100b4 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 export or erasure 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 74b4ce7b0..d140dde2b 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs @@ -120,6 +120,18 @@ 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. The export job takes it only in its + // write phase, after the bundle is built and the retained references are counted with no fence held. + "LearnStack.Modules.Identity.Application.DataRequests.DataExportJobHandlers.WriteAsync", + "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.CreateAsync", + "LearnStack.Modules.Identity.Application.DataRequests.DataRequestService.CancelAsync", + // ADR-0107 § 5: the erasure job takes the subject's User fence and then the tenant key exclusively, before its + // request row lock; every write it and its participants make runs under that one plan. + "LearnStack.Modules.Identity.Application.DataRequests.DataErasureJobHandlers.EraseAsync", ]; // A retained-plan check is not another acquisition: the guards, bounded // reader and two separately confined source/witness pairs must recheck it. @@ -149,6 +161,12 @@ 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.CreateAsync", + "LearnStack.Modules.Identity.Application.DataRequests.DataRequestService.CancelAsync", + "LearnStack.Modules.Identity.Application.DataRequests.DataRequestFailureReconciler.ReconcileAsync", + "LearnStack.Modules.Identity.Application.DataRequests.DataErasureJobHandlers.EraseAsync", ]; // 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/IdentityPlatformFenceConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/IdentityPlatformFenceConventionTests.cs new file mode 100644 index 000000000..44f319e57 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Architecture/IdentityPlatformFenceConventionTests.cs @@ -0,0 +1,225 @@ +using FluentAssertions; +using Mono.Cecil; +using Xunit; + +namespace LearnStack.Tests.Architecture; + +/// +/// The closure's fence acquirer on the platform connection (ADR-0107 § 7), the census leg beside +/// Identity_Membership_Invariants_Use_Fresh_Ordered_Locks: one class, one method body, in a READ COMMITTED +/// transaction the person's User key and then, within the closure's bounds, every participant tenant's key ascending, each +/// transaction-scoped and each wait bounded by the transaction's own lock_timeout. +/// +/// +/// +/// Why a leg of its own. The ordinary acquirer is IIdentityMutationLocks, which fences one tenant inside a +/// tenant-announced application transaction, and the existing census pins its callers. A closure spans every tenant of the +/// person on a connection that announces nothing, so its acquirer is a separate class that census never sees; this one +/// pins that it is the only one, and the order it takes the keys in. +/// +/// +/// What "the only one" means mechanically. In the production IL, the methods that derive both a User key and a +/// Tenant key are the ordinary acquirer and this one; in the production source, the only file that names the platform +/// scope's handle and derives identity lock keys is this one. A second platform acquirer, or a closure owner that took a +/// key itself, fails one of the two. The session-level advisory calls are refused everywhere by the existing census. +/// +/// +public sealed class IdentityPlatformFenceConventionTests +{ + private const string AcquirerFile = + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/PlatformIdentityFences.cs"; + + private const string LockKeyType = "LearnStack.SharedKernel.Identity.IdentityAdvisoryLockKey"; + + [Fact] + public void The_Closure_Fences_Are_Taken_By_One_Platform_Acquirer_User_First_Then_Each_Tenant_Ascending_For_The_Transaction() + { + var users = Callers(LockKeyType, "ForUser"); + var tenants = Callers(LockKeyType, "ForTenant"); + users.Intersect(tenants, StringComparer.Ordinal).Should().BeEquivalentTo( + [ + "LearnStack.Infrastructure.Persistence.IdentityMutationLocks.AcquireAsync", + "LearnStack.Modules.Identity.Infrastructure.DataRequests.PlatformIdentityFences.AcquireCoreAsync", + ], + "the methods that take a User key and then tenant keys are the application acquirer and the closure's, and no other"); + + SourceScan.FilesContaining(SourceScan.SourceRoot, "IPlatformAdminScopeHandle", except: null) + .Intersect(SourceScan.FilesContaining(SourceScan.SourceRoot, "IdentityAdvisoryLockKey", except: null)) + .Should().Equal([AcquirerFile], "no other holder of the platform scope's handle derives an identity lock key"); + + var source = File.ReadAllText(Path.Combine(SourceScan.SourceRoot, AcquirerFile.Replace('/', Path.DirectorySeparatorChar))); + AcquirerViolations(source).Should().BeEmpty(); + } + + [Theory] + [InlineData("tenants first", "await handle.ExecuteAsync(TakeExclusive, [new PlatformSqlParameter(\"key\", userKey)], cancellationToken);", "")] + [InlineData("a shared key", "SELECT pg_catalog.pg_advisory_xact_lock(@key)", "SELECT pg_catalog.pg_advisory_xact_lock_shared(@key)")] + [InlineData("a session key", "SELECT pg_catalog.pg_advisory_xact_lock(@key)", "SELECT pg_catalog.pg_advisory_lock(@key)")] + [InlineData("an unbounded wait", "SELECT pg_catalog.set_config('lock_timeout', '3s', true)", "SELECT 1")] + [InlineData("a session-wide bound", "set_config('lock_timeout', '3s', true)", "set_config('lock_timeout', '3s', false)")] + [InlineData("descending tenants", ".OrderBy(IdentityAdvisoryLockKey.ForTenant)", ".OrderByDescending(IdentityAdvisoryLockKey.ForTenant)")] + [InlineData("participants read before the User key", "var participants = await ReadParticipantsAsync(handle, subject, cancellationToken);", "")] + [InlineData("no isolation asked", "SELECT pg_catalog.current_setting('transaction_isolation')", "SELECT 'read committed'")] + [InlineData("another isolation admitted", "\"read committed\"", "\"repeatable read\"")] + [InlineData("isolation asked after the User key", "var isolation = await handle.QueryAsync(ReadCommitted, null, reader => reader.GetString(0), cancellationToken);", "")] + [InlineData("tenant keys past the bounds", "requestTenant is not { } request || !participants.WithinBounds", "requestTenant is not { } request")] + public void The_Acquirer_Census_Finds_A_Planted_Departure(string departure, string original, string planted) + { + var source = File.ReadAllText(Path.Combine(SourceScan.SourceRoot, AcquirerFile.Replace('/', Path.DirectorySeparatorChar))); + source.Should().Contain(original, departure); + const string Returned = " return new PlatformIdentityFenceSet(subject, participants.Groups, tenants, WithinBounds: true);"; + const string Bound = " await handle.ExecuteAsync(BoundTheWait, null, cancellationToken);"; + const string UserKey = " var participants = await ReadParticipantsAsync(handle, subject, cancellationToken);"; + var changed = departure switch + { + // Move the User key below the tenant loop, the participant read above the User key, or the isolation question + // below the User key. + "tenants first" => source.Replace(original, planted, StringComparison.Ordinal).Replace( + Returned, " " + original + "\n" + Returned, StringComparison.Ordinal), + "participants read before the User key" => source.Replace(original, planted, StringComparison.Ordinal).Replace( + Bound, " " + original + "\n" + Bound, StringComparison.Ordinal), + "isolation asked after the User key" => source.Replace(original, planted, StringComparison.Ordinal).Replace( + UserKey, " " + original + "\n" + UserKey, StringComparison.Ordinal), + _ => source.Replace(original, planted, StringComparison.Ordinal), + }; + + changed.Should().NotBe(source, departure); + AcquirerViolations(changed).Should().NotBeEmpty(departure); + } + + /// + /// The closure's Finalize takes its fences only through the acquirer, once in each of its two transactions: the User key + /// alone before its redaction and intent checkpoint, which changes no User and no request and so holds no participant + /// tenant's key while it redacts, and every key after the provider call and before the User moves to Closed, because the + /// first transaction's key ended at the checkpoint's commit. The database refuses the second transaction's changes + /// without the keys; this pins the source that takes them. + /// + [Fact] + public void The_Closure_Finalize_Takes_Its_Fences_Through_The_Acquirer_Once_In_Each_Transaction() + { + var source = File.ReadAllText(Path.Combine(SourceScan.SourceRoot, FinalizeFile.Replace('/', Path.DirectorySeparatorChar))); + FinalizeViolations(source).Should().BeEmpty(); + } + + [Theory] + [InlineData("no second acquisition", "var again = await PlatformIdentityFences.AcquireAsync(handle, request.Subject, request.Tenant, cancellationToken);", + "var again = fences;")] + [InlineData("the first acquisition after the checkpoint", "var fences = await PlatformIdentityFences.AcquireUserAsync(handle, request.Subject, cancellationToken);", + "var fences = (PlatformIdentityFenceSet)null!;")] + [InlineData("the first acquisition fences every tenant", "var fences = await PlatformIdentityFences.AcquireUserAsync(handle, request.Subject, cancellationToken);", + "var fences = await PlatformIdentityFences.AcquireAsync(handle, request.Subject, request.Tenant, cancellationToken);")] + [InlineData("the second acquisition fences the User alone", "var again = await PlatformIdentityFences.AcquireAsync(handle, request.Subject, request.Tenant, cancellationToken);", + "var again = await PlatformIdentityFences.AcquireUserAsync(handle, request.Subject, cancellationToken);")] + [InlineData("a key taken by hand", "var again = await PlatformIdentityFences.AcquireAsync(handle, request.Subject, request.Tenant, cancellationToken);", + "await handle.ExecuteAsync(\"SELECT pg_catalog.pg_advisory_xact_lock(@key)\", null, cancellationToken); var again = await PlatformIdentityFences.AcquireAsync(handle, request.Subject, request.Tenant, cancellationToken);")] + public void The_Finalize_Census_Finds_A_Planted_Departure(string departure, string original, string planted) + { + var source = File.ReadAllText(Path.Combine(SourceScan.SourceRoot, FinalizeFile.Replace('/', Path.DirectorySeparatorChar))); + source.Should().Contain(original, departure); + var changed = source.Replace(original, planted, StringComparison.Ordinal); + + changed.Should().NotBe(source, departure); + FinalizeViolations(changed).Should().NotBeEmpty(departure); + } + + private const string FinalizeFile = + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/AccountClosureOperatorOperations.Finalize.cs"; + + /// + /// What Finalize's code must say, read without comments and whitespace: exactly two acquisitions, the User key alone + /// before the redaction and the checkpoint, every key after the provider call and before the account moves, and no + /// advisory key of its own. + /// + private static List FinalizeViolations(string source) + { + var code = SourceText.WithoutWhitespace(SourceText.WithoutComments(source)); + var violations = new List(); + const string AcquireUser = "awaitPlatformIdentityFences.AcquireUserAsync(handle,request.Subject,cancellationToken);"; + const string Acquire = "awaitPlatformIdentityFences.AcquireAsync(handle,request.Subject,request.Tenant,cancellationToken);"; + if (CountOf(code, AcquireUser) != 1 || CountOf(code, Acquire) != 1 || CountOf(code, "PlatformIdentityFences.Acquire") != 2) + violations.Add("Finalize takes the User fence alone once and every fence once, through the acquirer, once a transaction"); + if (System.Text.RegularExpressions.Regex.IsMatch(code, "advisory|IdentityAdvisoryLockKey", System.Text.RegularExpressions.RegexOptions.IgnoreCase)) + violations.Add("Finalize takes no advisory key and derives no lock key itself"); + + string[] order = + [ + AcquireUser, + "awaitRedactAsync(", + "awaithandle.WriteIntentAsync(", + "awaitRemoveAccountAsync(providerSubject,cancellationToken);", + Acquire, + "awaithandle.ExecuteAsync(CloseAccount,", + ]; + var position = -1; + foreach (var step in order) + { + position = code.IndexOf(step, position + 1, StringComparison.Ordinal); + if (position < 0) + { + violations.Add("the fences, the redaction, the checkpoint, the provider, the fences again, then the account's move"); + break; + } + } + + return violations; + } + + /// + /// What the acquirer's code must say, read without comments and whitespace: the transaction's isolation asked first and + /// only READ COMMITTED admitted, a transaction-scoped bound, the exclusive transaction-scoped key only, and in order the + /// isolation, the bound, the User key, the participant read, the refusal of the tenant keys past the closure's bounds, + /// the ascending tenant order and the tenant keys. + /// + private static List AcquirerViolations(string source) + { + var code = SourceText.WithoutWhitespace(SourceText.WithoutComments(source)); + var violations = new List(); + string Squeeze(string text) => SourceText.WithoutWhitespace(text); + + if (CountOf(code, Squeeze("\"SELECT pg_catalog.current_setting('transaction_isolation')\"")) != 1 + || CountOf(code, Squeeze("string.Equals(isolation[0], \"read committed\", StringComparison.Ordinal)")) != 1) + violations.Add("the transaction's isolation is asked once, and only READ COMMITTED is admitted"); + if (CountOf(code, Squeeze("\"SELECT pg_catalog.set_config('lock_timeout', '3s', true)\"")) != 1) + violations.Add("the wait is bounded once, by a transaction-local lock_timeout"); + if (CountOf(code, Squeeze("\"SELECT pg_catalog.pg_advisory_xact_lock(@key)\"")) != 1 + || code.Contains("advisory_xact_lock_shared", StringComparison.OrdinalIgnoreCase) + || System.Text.RegularExpressions.Regex.IsMatch(code, @"pg_(?:try_)?advisory_(?:lock|unlock)", System.Text.RegularExpressions.RegexOptions.IgnoreCase)) + violations.Add("every key is exclusive and transaction-scoped"); + + string[] order = + [ + "varisolation=awaithandle.QueryAsync(ReadCommitted,null,reader=>reader.GetString(0),cancellationToken);", + "awaithandle.ExecuteAsync(BoundTheWait,null,cancellationToken);", + "awaithandle.ExecuteAsync(TakeExclusive,[newPlatformSqlParameter(\"key\",userKey)],cancellationToken);", + "varparticipants=awaitReadParticipantsAsync(handle,subject,cancellationToken);", + "if(requestTenantisnot{}request||!participants.WithinBounds)", + ".OrderBy(IdentityAdvisoryLockKey.ForTenant)", + "foreach(vartenantintenants)", + "newPlatformSqlParameter(\"key\",IdentityAdvisoryLockKey.ForTenant(tenant))", + ]; + var positions = order.Select(step => code.IndexOf(step, StringComparison.Ordinal)).ToArray(); + if (positions.Any(position => position < 0) || positions.Zip(positions.Skip(1)).Any(pair => pair.First >= pair.Second)) + violations.Add("the isolation, the bound, then the User key, then the participants under it, the bounds, then each tenant key ascending"); + if (CountOf(code, "IdentityAdvisoryLockKey.ForUser(") != 1) + violations.Add("one User key, the person's"); + return violations; + } + + private static int CountOf(string code, string needle) + { + var count = 0; + for (var index = code.IndexOf(needle, StringComparison.Ordinal); index >= 0; index = code.IndexOf(needle, index + 1, StringComparison.Ordinal)) + count++; + return count; + } + + private static string[] Callers(string typeName, string methodName) => ProductionAssemblies.All().SelectMany(assembly => + { + using var module = ModuleDefinition.ReadModule(assembly.Location); + return module.Types.Where(type => type.Name != "") + .SelectMany(type => Il.Methods(type).Where(method => method.Definition.HasBody + && method.Definition.Body.Instructions.Any(instruction => instruction.Operand is MethodReference call + && call.DeclaringType.FullName == typeName && call.Name == methodName)) + .Select(method => type.FullName + "." + method.DeclaredAs.TrimStart('.'))).ToArray(); + }).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToArray(); +} diff --git a/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs index e39fd8a3a..c2a8508d9 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/OperationPermissionConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/OperationPermissionConventionTests.cs index 059c5845c..51aae8cd5 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(CreateDataErasureForSubjectCommand), 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.Http.cs b/backend/tests/LearnStack.Tests.Architecture/OperationPolicyOwnershipTests.Http.cs index 95aabae0a..c678b23e0 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 737a7374d..808810852 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 = [ @@ -300,7 +303,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), @@ -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), @@ -317,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/OutboxDispatchObservationTests.cs b/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchObservationTests.cs index d9ff20860..021a92da4 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/OwnDataRequestScopeConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/OwnDataRequestScopeConventionTests.cs new file mode 100644 index 000000000..257e45557 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Architecture/OwnDataRequestScopeConventionTests.cs @@ -0,0 +1,227 @@ +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; +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 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(CreateRetainedDataErasureCommand), typeof(CreateRetainedAccountClosureCommand), + typeof(CancelRetainedDataRequestCommand), typeof(RevokeRetainedDataExportCommand), typeof(MintRetainedDataExportTicketCommand), + typeof(ReadRetainedDataExportChunkCommand), typeof(ReadRetainedDataRequestReceiptQuery)], + "the retained entry reaches exactly its nine operations and the receipt read of its five keyed ones"); + policies.Where(policy => policy.Kind == OperationPolicyKind.OwnDataRequest).Select(policy => policy.RequestType) + .Should().BeEquivalentTo([typeof(CreateOwnDataExportCommand), typeof(CreateOwnDataErasureCommand), + typeof(CreateOwnAccountClosureCommand), 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().Equal(typeof(OwnDataRequestSubjectSource)); + types.Where(type => !type.IsAbstract && typeof(IOwnDataRequestScopeSource).IsAssignableFrom(type)) + .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)) + .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", "Revoke"); + 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().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", + Unit + ".ValidateOperationReadScope", Unit + ".IsOwnDataRequestOwner"); + Callers("LearnStack.SharedKernel.Persistence.IOwnDataRequestUnitOfWork", "BeginOwnDataRequestTransactionAsync") + .Should().Equal("LearnStack.Application.Persistence.TransactionExecutionCoordinator.ExecuteCoreAsync"); + Callers("LearnStack.SharedKernel.Persistence.IOwnDataRequestUnitOfWork", "IsOwnDataRequestOwner") + .Should().BeEquivalentTo("LearnStack.Application.Persistence.TransactionExecutionCoordinator.ExecuteFrameAsync", + "LearnStack.Modules.Identity.Application.DataRequests.RetainedDataRequestAdmission.For"); + Callers("LearnStack.SharedKernel.Tenancy.TenantContextFactory", "CreateForOwnDataRequestScope") + .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().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().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().Contain("ReviewProbe.DataRequestMinter").And.HaveCount(2); + module.Types.Remove(rogueMinter); + 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); + 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"); + } + + /// + /// 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 or OwnDataRequestPurpose.Revoke)", "false"), + ("_request is not (CreateRetainedDataExportCommand or CreateRetainedDataErasureCommand or CreateRetainedAccountClosureCommand\n or CancelRetainedDataRequestCommand or RevokeRetainedDataExportCommand)", "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" + + "orOwnDataRequestPurpose.Revoke)", StringComparison.Ordinal) + && replay.Contains("_requestisnot(CreateRetainedDataExportCommandorCreateRetainedDataErasureCommandorCreateRetainedAccountClosureCommand" + + "orCancelRetainedDataRequestCommandorRevokeRetainedDataExportCommand)", 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() + { + 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"); + 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.Architecture/PersistenceConventionTests.Enrollment.cs b/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.Enrollment.cs index eb659f6f0..a3b186937 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.Architecture/PersistenceConventionTests.ReadModes.cs b/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.ReadModes.cs index 5c780d100..d009d1300 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/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.cs index 743c6291c..9be6929e7 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.Architecture/PlatformAdminScopeConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs index afca3a2bd..ec087ddbc 100644 --- a/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/PlatformAdminScopeConventionTests.cs @@ -264,6 +264,18 @@ public void Only_The_Operator_Services_Hold_The_Platform_Scope() KillswitchWriterFile, DeliveryInspectionFile, FederationOperationsFile, + DataRequestOperationsFile, + // ADR-0107 § 7: the closure's owner enters the scope; its Begin, its Finalize and its fence acquirer + // work on the handle the owner entered, and Tenancy's lifecycle port reads on a handle it is given, as + // does Identity's own port over it (the module-dependency rule keeps Tenancy's contract out of + // Identity.Infrastructure). None of them can enter a scope of its own. + ClosureOperationsFile, + ClosureBeginFile, + ClosureFinalizeFile, + ClosureFencesFile, + "Modules/Tenancy/LearnStack.Modules.Tenancy.Application.Contracts/IdentityLifecycle/IIdentityScopeLifecycleReader.cs", + "Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/IdentityScopeLifecycleReader.cs", + "Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests/IClosureGroupLifecycleReader.cs", ], "each new operator service is added here deliberately, with its denied proof"); } @@ -273,14 +285,17 @@ public void Only_The_Operator_Onboarding_Routes_Run_An_Operator_Act() { // ADR-0102: the executor is the one place an operator's tenant reaches the pipeline, and an admission is // the only thing that lets it run. The files that name it in code are the executor, the registration beside - // the source it enters and the onboarding routes, and nothing else: a second caller is a second route to an - // act, and is added here deliberately with its own denied proof. + // the source it enters, the onboarding routes and the closure's fan-out (ADR-0107 § 7), which runs one + // admitted act per participant group and is reached only from the closure's Begin owner, and nothing else: + // a second caller is a second route to an act, and is added here deliberately with its own denied proof. The + // fan-out's is ClosureFanOutTests' gate refusal: an operator without the write key starts no group. SourceScan.FilesContaining(SourceScan.SourceRoot, "PlatformOperatorActExecutor", except: null) .Should().BeEquivalentTo( [ "LearnStack.Infrastructure/PlatformOperator/PlatformOperatorActExecutor.cs", "LearnStack.Infrastructure/PlatformOperator/PlatformOperatorOperationSource.cs", "LearnStack.Api/Platform/PlatformOperatorEndpoints.Onboarding.cs", + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/ClosureFanOut.cs", ], "each new caller of an operator act is added here deliberately, with its denied proof"); } @@ -362,9 +377,127 @@ public void The_Federation_Port_Census_Finds_A_Planted_Holder_Of_Either_Port_Or_ } } + [Fact] + public void Only_The_Data_Request_Routes_And_Their_Owner_Name_The_Data_Request_Operator_Port_And_Only_It_Redacts() + { + // ADR-0107 § 8 and ADR-0108 § 2: the inspection and the erasure completion are reachable from the data-request + // routes alone, through the one owner, and the scope's redaction is called by that owner and by the closure's + // Finalize and by nothing else. The first scan names the owner's class, which the port's name contains, so a holder + // of the concrete owner is found too. The scope also refuses the redaction to any other admitted operation, and each + // of the two its other's plans, at run time; this keeps the set of files that could ask for it closed as well. + SourceScan.FilesContaining(SourceScan.SourceRoot, "DataRequestOperatorOperations", except: null) + .Should().BeEquivalentTo( + [ + "LearnStack.SharedKernel/Platform/IDataRequestOperatorOperations.cs", + DataRequestOperationsFile, + CompositionFile, + "LearnStack.Api/Platform/PlatformOperatorEndpoints.DataRequests.cs", + ], + "each new caller of a data-request operator act is added here deliberately, with its denied proof"); + SourceScan.FilesContaining(SourceScan.SourceRoot, "RedactAuditAsync", except: null) + .Should().BeEquivalentTo( + ["LearnStack.SharedKernel/Tenancy/IPlatformAdminScope.cs", ScopeFile, DataRequestOperationsFile, ClosureFinalizeFile], + "the erasure owner and the closure's Finalize are the two callers of the scope's redaction (ADR-0108 § 2), each " + + "refused the other's plans at run time"); + + // And the executor behind the scope's redaction is held by the scope alone: its port and its one implementation + // are named only where they are declared, by the composition that registers them and by the scope that calls the + // port. A module that injected the port would otherwise reach RedactAsync without the scope's handle (the + // executor's own run-time checks would still refuse it; this closes the set of files that could try). + SourceScan.FilesContaining(SourceScan.SourceRoot, "IAuditRedactor", except: null) + .Should().BeEquivalentTo( + [AuditRedactionPortFile, AuditRedactionExecutorFile, CompositionFile, ScopeFile], + "the redaction port is declared, implemented, registered and called by the scope, and named nowhere else"); + SourceScan.FilesContaining(SourceScan.SourceRoot, "AuditRedactionExecutor", except: null) + .Should().BeEquivalentTo([AuditRedactionExecutorFile, CompositionFile], + "the executor is constructed only by the composition root"); + } + + [Fact] + public void Only_The_Closure_Route_And_Its_Owner_Name_The_Closure_Operator_Port() + { + // ADR-0107 §§ 7 and 8: a person's closure begins and finalizes from its operator routes alone, through the one owner, + // whose Begin and Finalize are parts of the one class and each name it in their declaration. The scan names + // the owner's class, which the port's name contains, so a holder of the concrete owner is found too. + SourceScan.FilesContaining(SourceScan.SourceRoot, "AccountClosureOperatorOperations", except: null) + .Should().BeEquivalentTo( + [ + "LearnStack.SharedKernel/Platform/IAccountClosureOperatorOperations.cs", + ClosureOperationsFile, + ClosureBeginFile, + ClosureFinalizeFile, + CompositionFile, + "LearnStack.Api/Platform/PlatformOperatorEndpoints.Closure.cs", + ], + "each new caller of a closure operator act is added here deliberately, with its denied proof"); + + var planted = Directory.CreateTempSubdirectory("closure-holder-"); + try + { + File.WriteAllText(Path.Combine(planted.FullName, "ViaPort.cs"), "class A(IAccountClosureOperatorOperations operations) { }"); + File.WriteAllText(Path.Combine(planted.FullName, "ViaOwner.cs"), "class B(AccountClosureOperatorOperations owner) { }"); + File.WriteAllText(Path.Combine(planted.FullName, "Commented.cs"), "class C { /* AccountClosureOperatorOperations */ }"); + + SourceScan.FilesContaining(planted.FullName, "AccountClosureOperatorOperations", except: null) + .Should().BeEquivalentTo(["ViaPort.cs", "ViaOwner.cs"]); + } + finally + { + planted.Delete(recursive: true); + } + } + + [Fact] + public void The_Data_Request_Port_Census_Finds_A_Planted_Holder_Of_The_Port_The_Owner_Or_The_Redaction() + { + var planted = Directory.CreateTempSubdirectory("data-request-holder-"); + try + { + File.WriteAllText(Path.Combine(planted.FullName, "ViaPort.cs"), "class A(IDataRequestOperatorOperations operations) { }"); + File.WriteAllText(Path.Combine(planted.FullName, "ViaOwner.cs"), "class B(DataRequestOperatorOperations owner) { }"); + File.WriteAllText(Path.Combine(planted.FullName, "ViaHandle.cs"), + "class C { Task R(IPlatformAdminScopeHandle handle, AuditRedactionPlan plan) => handle.RedactAuditAsync(plan); }"); + File.WriteAllText(Path.Combine(planted.FullName, "Commented.cs"), + "class D { /* handle.RedactAuditAsync(plan) and IDataRequestOperatorOperations, IAuditRedactor */ }"); + File.WriteAllText(Path.Combine(planted.FullName, "ViaRedactor.cs"), "class E(IAuditRedactor redactor) { }"); + File.WriteAllText(Path.Combine(planted.FullName, "ViaExecutor.cs"), + "class F(IEnumerable locators) { object G() => new AuditRedactionExecutor(locators); }"); + + SourceScan.FilesContaining(planted.FullName, "DataRequestOperatorOperations", except: null) + .Should().BeEquivalentTo(["ViaPort.cs", "ViaOwner.cs"]); + SourceScan.FilesContaining(planted.FullName, "RedactAuditAsync", except: null).Should().BeEquivalentTo(["ViaHandle.cs"], + "a call in code is found and a mention in a comment is not"); + SourceScan.FilesContaining(planted.FullName, "IAuditRedactor", except: null).Should().BeEquivalentTo(["ViaRedactor.cs"]); + SourceScan.FilesContaining(planted.FullName, "AuditRedactionExecutor", except: null).Should().BeEquivalentTo(["ViaExecutor.cs"]); + } + finally + { + planted.Delete(recursive: true); + } + } + private const string FederationOperationsFile = "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Federation/FederationBrokerOperations.cs"; + private const string AuditRedactionPortFile = "LearnStack.SharedKernel/Audit/AuditRedaction.cs"; + + private const string AuditRedactionExecutorFile = "LearnStack.Infrastructure.Audit/AuditRedactionExecutor.cs"; + + private const string DataRequestOperationsFile = + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/DataRequestOperatorOperations.cs"; + + private const string ClosureOperationsFile = + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/AccountClosureOperatorOperations.cs"; + + private const string ClosureBeginFile = + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/AccountClosureOperatorOperations.Begin.cs"; + + private const string ClosureFinalizeFile = + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/AccountClosureOperatorOperations.Finalize.cs"; + + private const string ClosureFencesFile = + "Modules/Identity/LearnStack.Modules.Identity.Infrastructure/DataRequests/PlatformIdentityFences.cs"; + private const string KillswitchWriterFile = "Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/KillswitchToggle.cs"; diff --git a/backend/tests/LearnStack.Tests.Architecture/ProviderEventFlowConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/ProviderEventFlowConventionTests.cs index cfd9ddb09..876853849 100644 --- a/backend/tests/LearnStack.Tests.Architecture/ProviderEventFlowConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/ProviderEventFlowConventionTests.cs @@ -67,6 +67,10 @@ public void Provider_Event_Mirror_Is_Attributed_And_Idempotent() using var census = new CallCensus(); census.Callers("LearnStack.SharedKernel.Audit.IAuditStateCapture", "AttachProviderEvent") .Should().Equal("LearnStack.Modules.Audit.Application.ProviderEvents.ProviderEventObservationHandler.HandleAsync"); + // ADR-0107 §§ 7, 9: the same subscriber, and nothing else, withholds the observation of a person whose User is no + // longer Active, with the evidence it alone mints. + census.Callers("LearnStack.SharedKernel.Audit.IAuditStateCapture", "WithholdProviderEvent") + .Should().Equal("LearnStack.Modules.Audit.Application.ProviderEvents.ProviderEventObservationHandler.HandleAsync"); census.Callers("LearnStack.Api.Identity.ProviderEventProductionBinding", "Bind") .Should().Equal("LearnStack.Api.Identity.ProviderEventMirrorService.ProduceAsync"); census.Callers("LearnStack.SharedKernel.Audit.ProviderEventAuditEvidence/MintingSource", "Observe") diff --git a/backend/tests/LearnStack.Tests.Architecture/TenancyConventionTests.ScopeCarrier.cs b/backend/tests/LearnStack.Tests.Architecture/TenancyConventionTests.ScopeCarrier.cs index 362ea69e0..46b322723 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/TenancyConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/TenancyConventionTests.cs index dcacc4f48..d6acbb68a 100644 --- a/backend/tests/LearnStack.Tests.Architecture/TenancyConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/TenancyConventionTests.cs @@ -252,6 +252,13 @@ public void The_Setter_Scan_Can_Actually_Fail() AnnouncesBeyondFixedSeedScope(FixedSeedOwner, fixedSeedSource.Replace("_depth != 1", "false", StringComparison.Ordinal)).Should().BeTrue( "a weakened same-owner gate loses the scope-only carrier recognition"); + Announces("SELECT pg_catalog.set_config('lock_timeout', '3s', true)").Should().BeFalse("a wait bound announces nothing"); + foreach (var statement in new[] + { + "SELECT set_config('lock_timeout', '3s', true), set_config('app.tenant_id', @tenant, true)", + "SELECT set_config(@name, @value, true)", "SELECT set_config('statement_timeout', '3s', true)", + }) + Announces(statement).Should().BeTrue("only the literal lock_timeout bound is exempt"); foreach (var statement in new[] { "SELECT set_config('app.tenant_id', @tenant, true)", "SET LOCAL app.scope = 'tenant'" }) AnnouncesBeyondFixedSeedScope(FixedSeedOwner, fixedSeedSource + "\nclass ExtraSetter { void Run() { Execute(\"" + statement + "\"); } }").Should().BeTrue( @@ -263,10 +270,13 @@ public void The_Setter_Scan_Can_Actually_Fail() /// The SET form must carry a value — = or TO — because the same words /// appear in prose a message hands a developer: ModuleDbContextRegistration throws /// "…it never saw SET LOCAL app.tenant_id", which announces nothing. Comments are stripped - /// before the scan; strings are not, because a setter IS a string. + /// before the scan; strings are not, because a setter IS a string. The one literal exemption is + /// set_config('lock_timeout', …), which bounds a wait and announces no tenant, organization or scope + /// (the closure's fence acquirer takes it before its first key); a variable name, a different setting or a + /// computed first argument still matches. /// [GeneratedRegex( - @"set_config\s*\(|\bSET\s+(?:LOCAL\s+|SESSION\s+)?app\.[A-Za-z_][A-Za-z0-9_]*\s*(?:=|\bTO\b)", + @"set_config\s*\((?!\s*'lock_timeout'\s*,)|\bSET\s+(?:LOCAL\s+|SESSION\s+)?app\.[A-Za-z_][A-Za-z0-9_]*\s*(?:=|\bTO\b)", RegexOptions.IgnoreCase)] private static partial Regex SessionSetter(); diff --git a/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.Organizations.cs b/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.Organizations.cs index ee8821d65..005238253 100644 --- a/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.Organizations.cs +++ b/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.Organizations.cs @@ -43,6 +43,20 @@ SELECT 1 FROM public.organizations AS organization WHERE ROW(tenant_id,id)>ROW(@afterTenant,@afterOrganization) AND ROW(tenant_id,id)<=ROW(@upperTenant,@upperOrganization) ORDER BY tenant_id,id LIMIT @limit """; + // ADR-0107 § 7: the same facts for many scopes on an entered platform scope; both key columns join, and the tenant-wide + // scope travels as the nil identifier no organization has. + private const string OrganizationIdentityPlatformLifecycleSql = """ + SELECT scope.position, + t.id IS NOT NULL AND t.deleted_at IS NULL, + t.id IS NOT NULL AND t.deleted_at IS NULL AND t.status IN ('Trial', 'Active'), + o.id IS NOT NULL, + o.id IS NOT NULL AND o.deleted_at IS NULL AND o.status = 'Active' + FROM unnest(@tenants::uuid[], @organizations::uuid[]) WITH ORDINALITY AS scope(tenant_id, organization_id, position) + LEFT JOIN public.tenants AS t ON t.id = scope.tenant_id + LEFT JOIN public.organizations AS o + ON o.tenant_id = t.id AND o.id = NULLIF(scope.organization_id, '00000000-0000-0000-0000-000000000000'::uuid) + ORDER BY scope.position + """; private const string OrganizationIdentityLifecycleSql = """ SELECT t.id IS NOT NULL AND t.deleted_at IS NULL, t.id IS NOT NULL AND t.deleted_at IS NULL AND t.status IN ('Trial', 'Active'), @@ -92,6 +106,8 @@ private sealed record OrganizationSqlSubject(string Path, string Type, string Me "SELECT tenant_id,id FROM organizations ORDER BY tenant_id DESC,id DESC LIMIT 1"), new(OrganizationIdentityLifecycle, "LearnStack.Modules.Tenancy.Infrastructure.Persistence.IdentityScopeLifecycleReader", "LifecycleSql", OrganizationIdentityLifecycleSql), + new(OrganizationIdentityLifecycle, "LearnStack.Modules.Tenancy.Infrastructure.Persistence.IdentityScopeLifecycleReader", + "PlatformLifecycleSql", OrganizationIdentityPlatformLifecycleSql), new(OrganizationSelfDiscovery, "LearnStack.Modules.Tenancy.Infrastructure.Persistence.PreContextSelfDiscoveryScopeReader", "LabelsSql", OrganizationSelfDiscoverySql), new(OrganizationWriteStores, "LearnStack.Modules.Tenancy.Infrastructure.Persistence.OrganizationWriteStore", @@ -194,6 +210,14 @@ private static string[] OrganizationReadOffenders(IEnumerable<(string Path, stri "command.Parameters.AddWithValue(\"tenant\", candidate.TenantId.Value)", "command.Parameters.AddWithValue(\"organization\", NpgsqlDbType.Uuid, candidate.OrganizationId is { } organization ? organization.Value : DBNull.Value)", "command.ExecuteReaderAsync(cancellationToken)"); + Require(OrganizationIdentityLifecycle, "IdentityScopeLifecycleReader", "ReadOnPlatformScopeAsync", + """ + handle.QueryAsync(PlatformLifecycleSql, + [new PlatformSqlParameter("tenants", tenants), new PlatformSqlParameter("organizations", organizations)], + reader => (Position: reader.GetInt64(0), Facts: new IdentityScopeLifecycle( + reader.GetBoolean(1), reader.GetBoolean(2), reader.GetBoolean(3), reader.GetBoolean(4))), + cancellationToken) + """); Require(OrganizationSelfDiscovery, "PreContextSelfDiscoveryScopeReader", "ReadAsync", "deadline.CancelAfter(TimeSpan.FromSeconds(5))", "self.BeginSelfDiscoveryTransactionAsync(witness, deadline.Token)", @@ -206,6 +230,10 @@ private static string[] OrganizationReadOffenders(IEnumerable<(string Path, stri && lifecycleRoot.DescendantTokens().Count(token => token.IsKind(SyntaxKind.IdentifierToken) && token.ValueText == "LifecycleSql") != 3) offenders.Add(OrganizationIdentityLifecycle + ": the SQL constant must have exactly its declaration and two executed argument uses"); + if (roots.TryGetValue(OrganizationIdentityLifecycle, out var platformRoot) + && platformRoot.DescendantTokens().Count(token => token.IsKind(SyntaxKind.IdentifierToken) + && token.ValueText == "PlatformLifecycleSql") != 2) + offenders.Add(OrganizationIdentityLifecycle + ": the platform SQL constant must have exactly its declaration and one executed argument use"); if (roots.TryGetValue(OrganizationSelfDiscovery, out var selfRoot) && selfRoot.DescendantTokens().Count(token => token.IsKind(SyntaxKind.IdentifierToken) && token.ValueText == "LabelsSql") != 2) @@ -236,6 +264,7 @@ void Require(string path, string type, string method, params string[] calls) "ReadAsync" when path == OrganizationSelfDiscovery => ("OwnMembershipScopeWitness witness, CancellationToken cancellationToken = default", "Task", SyntaxKind.PublicKeyword, true), "ReadAsync" => ("TenantId tenantId, OrganizationId? organizationId, CancellationToken cancellationToken = default", "Task", SyntaxKind.PublicKeyword, true), "ReadAuthorizationAsync" => ("IUnitOfWork child, AuthorizationCandidate candidate, CancellationToken cancellationToken = default", "Task", SyntaxKind.PublicKeyword, true), + "ReadOnPlatformScopeAsync" => ("IPlatformAdminScopeHandle handle, IReadOnlyList scopes, CancellationToken cancellationToken = default", "Task>", SyntaxKind.PublicKeyword, true), _ => throw new InvalidOperationException("Unknown organization binding owner."), }; if (ownerMethod.Body is null || ownerMethod.TypeParameterList is not null @@ -245,7 +274,11 @@ void Require(string path, string type, string method, params string[] calls) || ownerMethod.Modifiers.Any(token => token.IsKind(SyntaxKind.StaticKeyword)) || ownerMethod.Modifiers.Any(token => token.IsKind(SyntaxKind.AsyncKeyword)) != isAsync) { offenders.Add(path + ": changed binding owner signature " + method); return; } - if (path == OrganizationIdentityLifecycle) + if (path == OrganizationIdentityLifecycle && method == "ReadOnPlatformScopeAsync" + && ownerMethod.DescendantNodes().OfType().Any(item => + SyntaxFactory.AreEquivalent(item.Type, SyntaxFactory.ParseTypeName("NpgsqlCommand")))) + offenders.Add(path + ": the platform read runs on the handle it is given and builds no command of its own"); + if (path == OrganizationIdentityLifecycle && method != "ReadOnPlatformScopeAsync") { var construction = method == "ReadAsync" ? "new NpgsqlCommand(LifecycleSql, (NpgsqlConnection)unit.Connection, (NpgsqlTransaction)transaction) { CommandTimeout = 10 }" @@ -512,7 +545,7 @@ private static bool OrganizationSqlUseIsExact(string path, string member, Litera return OrganizationLockedReadIsExact(literal.SyntaxTree.GetRoot()); if (path == OrganizationOccurrences && member == "OrganizationLifecyclePageSql") return literal.Parent is EqualsValueClauseSyntax; - if (path == OrganizationIdentityLifecycle && member == "LifecycleSql" + if (path == OrganizationIdentityLifecycle && member is "LifecycleSql" or "PlatformLifecycleSql" || path == OrganizationSelfDiscovery && member == "LabelsSql") return literal.Parent is EqualsValueClauseSyntax { @@ -592,7 +625,7 @@ private static string OrganizationTypeIdentity(TypeDeclarationSyntax type) => st public void Organization_reader_census_rejects_missing_keys_extra_readers_and_unbounded_pages() { var production = OrganizationSources(); - OrganizationReadOffenders(production).Should().BeEmpty("all eight direct runtime SQL subjects, both composed page owners, and all four exact migration owners must exist: {0}", + OrganizationReadOffenders(production).Should().BeEmpty("all nine direct runtime SQL subjects, both composed page owners, and all four exact migration owners must exist: {0}", string.Join("\n", OrganizationReadOffenders(production))); foreach (var subject in OrganizationSqlSubjects) { diff --git a/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.cs b/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.cs index 9d090183f..7296e7336 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.Architecture/UserDataParticipantCensusTests.cs b/backend/tests/LearnStack.Tests.Architecture/UserDataParticipantCensusTests.cs new file mode 100644 index 000000000..76b9e60ff --- /dev/null +++ b/backend/tests/LearnStack.Tests.Architecture/UserDataParticipantCensusTests.cs @@ -0,0 +1,168 @@ +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; + } + + /// + /// Each module assembly that references another module's assembly holding one of ; + /// the locator census applies the same rule to IUserReferenceLocator types. + /// + internal 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.Architecture/UserReferenceLocatorCensusTests.cs b/backend/tests/LearnStack.Tests.Architecture/UserReferenceLocatorCensusTests.cs new file mode 100644 index 000000000..f14bb6501 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Architecture/UserReferenceLocatorCensusTests.cs @@ -0,0 +1,690 @@ +using System.Reflection; +using FluentAssertions; +using LearnStack.Api.Composition; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Domain; +using LearnStack.SharedKernel.Identifiers; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Xunit; +using IdentityDomain = LearnStack.Modules.Identity.Domain; +using TenancyDomain = LearnStack.Modules.Tenancy.Domain; + +namespace LearnStack.Tests.Architecture; + +/// +/// ADR-0107 § 1 and ADR-0108 § 7: every person reference an audited entity carries into its audit snapshot is declared, +/// redactable or retained, by its own module's registered , and no module references +/// another module's locator. Each detector is proved able to fail by a planted violation. +/// +/// +/// +/// Derived from the models, not listed. The audited entities are the declared types of the merged audit +/// catalogue; their person references are read from each module's mapped model by CLR type (, the +/// Identity MembershipId) and, for a reference stored as a plain the types cannot see (the +/// consent's [PiiSensitive] Membership), by name: a property whose name ends in UserId +/// or MembershipId. A contained collection is walked by the capture's own containment rule (a non-root entity +/// exactly one relationship reaches through its principal's navigation), with the foreign key to its owner left out as +/// the capture leaves it out, so its members' references are the paths Navigation/*/Property. +/// +/// +/// A reference the grammar cannot express fails the census, declared or not, until the grammar grows: inside a contained +/// single navigation or one level deeper; in a contained member's own key, which the capture writes as a JSON object key +/// and a changes path segment; in a part of an entity's composite key, which the capture joins into +/// entity_id and every changes path; and in a collection of identifiers (an array or list of +/// , MembershipId or , a uuid[] included) unless it is a mapped +/// jsonb array an Elements declaration covers. An array of identifiers held in a jsonb string is +/// invisible to a type census, so an Elements declaration is instead checked to name a mapped jsonb +/// property. +/// +/// +/// No unclassified identifier. A name is a weak signal, so every other plain of an audited +/// entity or of what it contains fails as an unclassified identifier unless it is its entity's or member's own +/// single-column key or is on , the explicit list of identifiers that name no person; every +/// strongly typed identifier type other than the person kinds fails the same way unless it is on +/// . A retained reference must be its entity's whole single-column key: a part of a +/// composite key is not the row's entity_id. +/// +/// +public sealed class UserReferenceLocatorCensusTests +{ + [Fact] + public void Every_PII_Module_RegistersUserReferenceLocator() + { + var locators = RegisteredLocators(); + var catalog = new UserReferenceCatalog(locators.Select(locator => locator.Instance)); + var models = ProductionModels(); + var references = models.SelectMany(model => References(model, [])).ToList(); + + references.Select(reference => reference.Module).Distinct().Should().BeEquivalentTo(ReferencingModules, + "every module whose audited entities hold a person reference is in the census"); + references.Should().Contain(new PersonReference("Tenancy", typeof(TenancyDomain.Tenant), + "FeatureFlags/*/UpdatedBy", UserReferenceKind.User, IsKey: false), "the census walks contained collections"); + references.Should().Contain(new PersonReference("Tenancy", typeof(TenancyDomain.MembershipFieldConsent), + "MembershipId", UserReferenceKind.Membership, IsKey: false), "the census reads a plain Guid reference by its name"); + references.Should().Contain(new PersonReference("Identity", typeof(IdentityDomain.Membership), "Id", + UserReferenceKind.Membership, IsKey: true), "the census sees an entity whose own key is a person reference"); + Offenders(models, locators, catalog).Should().BeEmpty(); + + // Planted: a module that stops registering its locator is named, with each of its references. + foreach (var module in references.Select(reference => reference.Module).Distinct()) + { + var missing = locators.Where(locator => locator.Module != module).ToList(); + Offenders(models, missing, new UserReferenceCatalog(missing.Select(locator => locator.Instance))) + .Should().Contain("Missing user reference locator: " + module) + .And.Contain(offender => offender.StartsWith("Undeclared person reference: ", StringComparison.Ordinal)); + } + + // Planted: a synthetic module whose audited entities hold a typed, an untyped and a contained person reference, a + // plain Guid no name classifies, a contained collection keyed by a person, a composite key holding a person, two + // collections of identifiers (a uuid[] and a jsonb array) and an identifier type no allowance names, and that + // registers no locator; then one that declares them with a wrong kind, a stale path, another module's entity, the + // person part of the composite key and the jsonb array, and retains a reference that is not the entity's key. + var planted = new ModuleModel("Planted", PlantedModel(), [typeof(PlantedAggregate), typeof(PlantedGrant)]); + var unplanted = Offenders([.. models, planted], locators, catalog); + unplanted.Should() + .Contain("Missing user reference locator: Planted") + .And.Contain("Undeclared person reference: PlantedAggregate.Owner") + .And.Contain("Undeclared person reference: PlantedAggregate.DelegateMembershipId") + .And.Contain("Undeclared person reference: PlantedAggregate.Members/*/Reviewer") + .And.Contain("Person reference outside the path grammar: PlantedAggregate.Lead/Approver") + .And.Contain("Unclassified identifier: PlantedAggregate.ReviewedBy") + .And.Contain("Unclassified identifier: PlantedGrant.ScopeId") + .And.Contain("Person reference in a contained member's key, outside the path grammar: PlantedAggregate.Seats/Holder") + .And.Contain("Person reference in an entity's composite key, outside the path grammar: PlantedGrant.Holder") + .And.Contain("Identifier collection outside the path grammar: PlantedAggregate.Watchers") + .And.Contain("Identifier collection outside the path grammar: PlantedAggregate.Followers") + .And.Contain("Unclassified identifier type: PlantedPersonId (PlantedAggregate.Instructor)"); + unplanted.Should().NotContain(offender => offender.Contains(".Members/*/Id", StringComparison.Ordinal) + || offender.Contains(".Lead/Id", StringComparison.Ordinal) || offender.EndsWith("PlantedAggregate.Id", StringComparison.Ordinal), + "an entity's or a contained member's own single-column key is its identity, not a reference"); + var wrong = new RegisteredLocator("Planted", new PlantedLocator()); + Offenders([.. models, planted], [.. locators, wrong], + new UserReferenceCatalog([.. locators.Select(locator => locator.Instance), wrong.Instance])).Should() + .Contain("Wrong kind for PlantedAggregate.Owner: Membership, the model holds User") + .And.Contain("Stale declaration: PlantedAggregate.Retired") + .And.Contain("Locator of Planted declares another module's entity: Membership") + .And.Contain("Retained reference is not the entity's own key: PlantedAggregate.DelegateMembershipId") + .And.Contain("Person reference in an entity's composite key, outside the path grammar: PlantedGrant.Holder", + "a declared part of a composite key is still refused: it stays in entity_id and in every changes path") + .And.Contain("Identifier collection outside the path grammar: PlantedAggregate.Watchers", + "a uuid[] column is no jsonb array a declaration reaches") + .And.NotContain("Identifier collection outside the path grammar: PlantedAggregate.Followers", + "a jsonb array of identifiers a declaration covers is in the grammar") + .And.Contain("Person reference in a contained member's key, outside the path grammar: PlantedAggregate.Seats/Holder", + "a declared member key is still refused: the key text stays in the JSON object key and the changes path") + .And.NotContain("Missing user reference locator: Planted"); + Offenders(models, [.. locators, locators[0] with { }], catalog).Should() + .Contain("More than one user reference locator: " + locators[0].Module); + } + + [Fact] + public void No_Module_References_Another_Modules_User_Reference_Locator() + { + var locators = RegisteredLocators().Select(locator => locator.Instance.GetType()).ToArray(); + var references = Modules.Names + .SelectMany(module => Legs.Select(leg => Assembly.Load("LearnStack.Modules." + module + "." + leg))) + .ToDictionary(assembly => assembly.GetName().Name!, + assembly => (IReadOnlyCollection)assembly.GetReferencedAssemblies().Select(name => name.Name!).ToArray(), + StringComparer.Ordinal); + + UserDataParticipantCensusTests.ReferenceOffenders(locators, references).Should().BeEmpty(); + + // Planted: Education reaching Tenancy's locator assembly is named. + var tenancy = locators.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], + }; + UserDataParticipantCensusTests.ReferenceOffenders(locators, planted).Should().ContainSingle() + .Which.Should().Be("LearnStack.Modules.Education.Infrastructure references " + tenancy); + } + + private static readonly string[] Legs = ["Domain", "Application.Contracts", "Application", "Infrastructure"]; + + private static readonly string[] ReferencingModules = ["Customization", "Education", "Identity", "Tenancy"]; + + /// + /// The plain properties of audited entities that name no person, each with why. Every other plain + /// that is not its entity's (or contained member's) own single-column key is a person reference + /// until it is declared or listed here, so a ReviewedBy added as a fails the census. Read + /// from the models; strongly typed identifiers are classified by type in . + /// + private static readonly Dictionary NotAPerson = new(StringComparer.Ordinal) + { + ["MembershipFieldConsent.DefinitionId"] = "the custom field definition the consent is for, a tenant definition", + }; + + /// + /// The strongly typed identifiers of audited entities that name no person, by type, each with why. Read from the + /// models: a type is listed when an audited entity holds it other than as its own key, so a new identifier type an + /// entity holds (an InstructorId over a person) fails the census until it is declared a person reference or + /// listed here. and Identity's MembershipId are person kinds, never listed. + /// + private static readonly Dictionary NotAPersonType = new(StringComparer.Ordinal) + { + ["AuditEntryId"] = "an audit row: the User's creation evidence", + ["BackgroundJobId"] = "a background job: an invitation's current delivery job", + ["CourseId"] = "a course: a lesson's course", + ["DataExportArtifactId"] = "an export artifact: a download ticket's artifact", + ["DataSubjectRequestId"] = "a data request: an export artifact's request", + ["FederationOperationId"] = "a federation connection's pending operation", + ["FederationTestAttemptId"] = "a federation connection's test attempt", + ["IdentityAuthorityId"] = "an identity authority (issuer) a User or an authority row names", + ["InvitationEmailReceiptId"] = "an invitation's delivery receipt", + ["InvitationGenerationId"] = "an invitation's generation", + ["MembershipFieldConsentId"] = "a consent act: a consent's predecessor", + ["OrganizationId"] = "an organization (branch) of the tenant", + ["RoleId"] = "a role: an invitation's or an assignment's role", + ["TenantId"] = "the tenant", + }; + + /// Every locator the API composition registers, Identity's and the root's own, with its module. + private static List RegisteredLocators() + { + var services = new ServiceCollection(); + services.AddIdentityContextualFoundation(); + services.AddDataExportCustody(new ConfigurationBuilder().Build()); + return + [ + .. services.Where(descriptor => descriptor.ServiceType == typeof(IUserReferenceLocator)) + .Select(descriptor => descriptor.ImplementationType + ?? throw new InvalidOperationException("A locator is registered by its concrete type.")) + .Select(type => new RegisteredLocator(ModuleOf(type.Assembly), (IUserReferenceLocator)Activator.CreateInstance(type)!)), + ]; + } + + /// Each mapped module's model with the entity types the merged audit catalogue declares from its domain. + private static List ProductionModels() + { + var audited = AuditCatalogDiscovery.Catalogue().All + .Select(entry => entry.EntityType).OfType().Distinct().ToList(); + return + [ + .. Modules.Mapped.Select(module => + { + using var context = module.Context(); + return new ModuleModel(ModuleOf(module.Domain)!, context.GetService().Model, + [.. audited.Where(type => type.Assembly == module.Domain)]); + }), + ]; + } + + private static List Offenders(IReadOnlyCollection models, IReadOnlyCollection locators, + UserReferenceCatalog catalog) + { + var offenders = new List(); + var found = models.SelectMany(model => References(model, offenders)).ToList(); + foreach (var locator in locators) + { + if (locator.Module is null) + { + offenders.Add("User reference locator outside a module boundary: " + locator.Instance.GetType().FullName); + } + + foreach (var entity in locator.Instance.Redactable.Select(declaration => declaration.EntityType) + .Concat(locator.Instance.Retained.Select(reference => reference.EntityType)).Distinct() + .Where(entity => ModuleOf(entity.Assembly) != locator.Module)) + { + offenders.Add("Locator of " + locator.Module + " declares another module's entity: " + entity.Name); + } + } + + foreach (var module in locators.Where(locator => locator.Module is not null).GroupBy(locator => locator.Module!) + .Where(group => group.Count() > 1)) + { + offenders.Add("More than one user reference locator: " + module.Key); + } + + foreach (var reference in found) + { + var declared = catalog.Redactable.FirstOrDefault(declaration => + declaration.EntityType == reference.Entity && declaration.Path.ToString() == reference.Path); + var retained = catalog.Retained.FirstOrDefault(kept => + kept.EntityType == reference.Entity && kept.Path.ToString() == reference.Path); + if (declared is not null) + { + if (declared.Kind != reference.Kind) + { + offenders.Add($"Wrong kind for {reference.Entity.Name}.{reference.Path}: {declared.Kind}, the model holds {reference.Kind}"); + } + } + else if (retained is not null) + { + if (!reference.IsKey) + { + offenders.Add($"Retained reference is not the entity's own key: {reference.Entity.Name}.{reference.Path}"); + } + } + else + { + offenders.Add($"Undeclared person reference: {reference.Entity.Name}.{reference.Path}"); + } + } + + var byModule = models.ToDictionary(model => model.Module, StringComparer.Ordinal); + foreach (var declaration in catalog.Redactable.Where(declaration => + !found.Any(reference => reference.Entity == declaration.EntityType && reference.Path == declaration.Path.ToString()) + && !IsJsonArrayDeclaration(declaration, byModule))) + { + offenders.Add($"Stale declaration: {declaration.EntityName}.{declaration.Path}"); + } + + foreach (var kept in catalog.Retained.Where(kept => !found.Any(reference => + reference.Entity == kept.EntityType && reference.Path == kept.Path.ToString() && reference.IsKey))) + { + offenders.Add($"Stale retained reference: {kept.EntityName}.{kept.Path}"); + } + + foreach (var module in found.Select(reference => reference.Module).Distinct() + .Where(module => !locators.Any(locator => locator.Module == module))) + { + offenders.Add("Missing user reference locator: " + module); + } + + foreach (var collection in models.SelectMany(model => model.Collections)) + { + var declared = catalog.Redactable.FirstOrDefault(declaration => declaration.EntityType == collection.Entity + && declaration.Path.Shape == UserReferenceShape.Elements && declaration.Path.Property == collection.Property); + if (!collection.Jsonb || declared is null) + { + offenders.Add($"Identifier collection outside the path grammar: {collection.Entity.Name}.{collection.Property}"); + } + else if (collection.Kind is { } kind && kind != declared.Kind) + { + offenders.Add($"Wrong kind for {collection.Entity.Name}.{declared.Path}: {declared.Kind}, the model holds {kind}"); + } + } + + var typed = models.SelectMany(model => model.TypedIdentifiers).ToList(); + offenders.AddRange(typed.Where(identifier => !NotAPersonType.ContainsKey(identifier.Type.Name)) + .Select(identifier => $"Unclassified identifier type: {identifier.Type.Name} ({identifier.Path})").Order(StringComparer.Ordinal)); + offenders.AddRange(NotAPersonType.Keys.Where(name => !typed.Any(identifier => identifier.Type.Name == name)) + .Order(StringComparer.Ordinal).Select(name => "Stale identifier type allowance: " + name)); + + var identifiers = models.SelectMany(model => model.Identifiers).ToHashSet(StringComparer.Ordinal); + offenders.AddRange(identifiers.Where(identifier => !NotAPerson.ContainsKey(identifier)).Order(StringComparer.Ordinal) + .Select(identifier => "Unclassified identifier: " + identifier)); + offenders.AddRange(NotAPerson.Keys.Where(identifier => !identifiers.Contains(identifier)).Order(StringComparer.Ordinal) + .Select(identifier => "Stale identifier allowance: " + identifier)); + + return offenders; + } + + /// + /// The person references of a module's audited entities as the capture writes them: each entity's own properties, + /// and its contained collections' members' properties without the foreign key to the owner. + /// + private static IEnumerable References(ModuleModel model, List offenders) + { + foreach (var type in model.Audited) + { + // An audited type the module does not map is captured from no tracker, so its rows carry no snapshot. + if (model.Model.FindEntityType(type) is not { } entity) + { + continue; + } + + var key = entity.FindPrimaryKey()?.Properties ?? []; + var ownKey = OwnKey(key); + foreach (var property in entity.GetProperties()) + { + if (CollectionKindOf(property) is { } collection) + { + // An array of identifiers is a reference the grammar reaches only as a declared jsonb array (Elements). + model.Collections.Add(new IdentifierCollection(type, property.Name, collection.Kind, IsJsonb(property))); + } + else if (KindOf(property) is { } kind) + { + // A part of a composite key is in entity_id and in every changes path, joined with the other parts, + // where no declaration and no whole-identifier match reaches it. + if (key.Count > 1 && key.Contains(property)) + { + offenders.Add($"Person reference in an entity's composite key, outside the path grammar: {type.Name}.{property.Name}"); + continue; + } + + yield return new PersonReference(model.Module, type, property.Name, kind, property == ownKey); + } + else if (property != ownKey) + { + Classify(model, property, type.Name + "." + property.Name); + } + } + + foreach (var navigation in Containments(entity)) + { + foreach (var reference in Contained(model, type, navigation, navigation.Name, depth: 1, offenders)) + { + yield return reference; + } + } + } + } + + /// A key's one property, or none when the key is composite: only a whole single-column key is an own key. + private static IReadOnlyProperty? OwnKey(IReadOnlyList key) => key.Count == 1 ? key[0] : null; + + /// A plain : an identifier no type names, which only its declaration or an allowance classifies. + private static bool IsIdentifier(IReadOnlyProperty property) => + (Nullable.GetUnderlyingType(property.ClrType) ?? property.ClrType) == typeof(Guid); + + /// + /// Records a property that is neither a person reference nor its holder's own key when it is an identifier: a plain + /// by its path, a strongly typed identifier by its type, each to be classified by an allowance. + /// + private static void Classify(ModuleModel model, IReadOnlyProperty property, string path) + { + if (IsIdentifier(property)) + { + model.Identifiers.Add(path); + } + else if (TypedIdentifierOf(property) is { } type) + { + model.TypedIdentifiers.Add((type, path)); + } + } + + /// + /// A strongly typed identifier over a that no person kind names: any type can hold a person, so + /// each is classified by . + /// + private static Type? TypedIdentifierOf(IReadOnlyProperty property) + { + var type = Nullable.GetUnderlyingType(property.ClrType) ?? property.ClrType; + return type != typeof(UserId) && type != typeof(IdentityDomain.MembershipId) + && type.GetInterfaces().Contains(typeof(IStronglyTypedId)) ? type : null; + } + + /// + /// An enumerable of person or plain identifiers (, Identity's MembershipId, ), + /// whatever its collection type or column, with the person kind its element type names, if any. + /// + private static (UserReferenceKind? Kind, bool Found)? CollectionKindOf(IReadOnlyProperty property) + { + if (property.ClrType == typeof(string)) + { + return null; + } + + var element = (property.ClrType.IsArray ? property.ClrType.GetElementType() : null) + ?? property.ClrType.GetInterfaces().Append(property.ClrType) + .Where(contract => contract.IsGenericType && contract.GetGenericTypeDefinition() == typeof(IEnumerable<>)) + .Select(contract => contract.GetGenericArguments()[0]).FirstOrDefault(); + element = element is null ? null : Nullable.GetUnderlyingType(element) ?? element; + return element == typeof(UserId) ? (UserReferenceKind.User, true) + : element == typeof(IdentityDomain.MembershipId) ? (UserReferenceKind.Membership, true) + : element == typeof(Guid) ? (null, true) + : null; + } + + private static bool IsJsonb(IReadOnlyProperty property) => + string.Equals(property.GetColumnType(), "jsonb", StringComparison.OrdinalIgnoreCase); + + private static IEnumerable Contained(ModuleModel model, Type owner, IReadOnlyNavigation navigation, string path, + int depth, List offenders) + { + var member = navigation.TargetEntityType; + + // The member's own key, as the capture computes it: its key without the foreign key to the owner. A collection's + // members are keyed by it as JSON object keys and as segments of each changes path, which no declaration reaches. + var local = (member.FindPrimaryKey()?.Properties ?? []).Where(property => !navigation.ForeignKey.Properties.Contains(property)) + .ToList(); + var ownKey = OwnKey(local); + var shape = depth == 1 && navigation.IsCollection ? "/*/" : "/"; + foreach (var property in member.GetProperties().Where(property => !navigation.ForeignKey.Properties.Contains(property))) + { + if (CollectionKindOf(property) is not null) + { + offenders.Add($"Identifier collection outside the path grammar: {owner.Name}.{path}/{property.Name}"); + continue; + } + + if (KindOf(property) is not { } kind) + { + if (property != ownKey) + { + Classify(model, property, owner.Name + "." + path + shape + property.Name); + } + + continue; + } + + if (navigation.IsCollection && local.Contains(property)) + { + offenders.Add($"Person reference in a contained member's key, outside the path grammar: {owner.Name}.{path}/{property.Name}"); + } + else if (depth == 1 && navigation.IsCollection) + { + yield return new PersonReference(model.Module, owner, UserReferencePath.Member(navigation.Name, property.Name).ToString(), + kind, IsKey: false); + } + else + { + offenders.Add($"Person reference outside the path grammar: {owner.Name}.{path}/{property.Name}"); + } + } + + // Bounded as the capture bounds containment; a well-formed model ends at a root long before. + if (depth < 8) + { + foreach (var inner in Containments(member)) + { + foreach (var reference in Contained(model, owner, inner, path + "/" + inner.Name, depth + 1, offenders)) + { + yield return reference; + } + } + } + } + + /// The capture's containment rule (ADR-0044 Amendment 6 § 4), read from the model. + private static IEnumerable Containments(IReadOnlyEntityType entity) => + entity.GetNavigations().Where(navigation => !navigation.IsOnDependent && IsContained(navigation)); + + private static bool IsContained(IReadOnlyNavigation navigation) + { + var target = navigation.TargetEntityType; + if (target.ClrType.GetInterfaces().Any(contract => + contract.IsGenericType && contract.GetGenericTypeDefinition() == typeof(IAggregateRoot<>))) + { + return false; + } + + var reaching = target.GetForeignKeys().Where(foreignKey => + foreignKey.PrincipalToDependent is not null && foreignKey.PrincipalEntityType.ClrType != target.ClrType).ToList(); + return reaching.Count == 1 && reaching[0] == navigation.ForeignKey; + } + + /// What a mapped property holds: a person by its type, a Membership by its identifier type, + /// or either as a plain named for it. + private static UserReferenceKind? KindOf(IReadOnlyProperty property) + { + var type = Nullable.GetUnderlyingType(property.ClrType) ?? property.ClrType; + if (type == typeof(UserId)) + { + return UserReferenceKind.User; + } + + if (type == typeof(IdentityDomain.MembershipId)) + { + return UserReferenceKind.Membership; + } + + if (type == typeof(Guid)) + { + if (property.Name.EndsWith("UserId", StringComparison.Ordinal)) + { + return UserReferenceKind.User; + } + + if (property.Name.EndsWith("MembershipId", StringComparison.Ordinal)) + { + return UserReferenceKind.Membership; + } + } + + return null; + } + + /// Whether an Elements declaration names a mapped jsonb string property of its entity. + private static bool IsJsonArrayDeclaration(UserReferenceDeclaration declaration, IReadOnlyDictionary models) => + declaration.Path.Shape == UserReferenceShape.Elements + && models.Values.Select(model => model.Model.FindEntityType(declaration.EntityType)).FirstOrDefault(entity => entity is not null) + ?.FindProperty(declaration.Path.Property) is { } property + && (property.ClrType == typeof(string) || CollectionKindOf(property) is not null) + && IsJsonb(property); + + private static string? ModuleOf(Assembly assembly) + { + const string prefix = "LearnStack.Modules."; + var name = assembly.GetName().Name!; + return name.StartsWith(prefix, StringComparison.Ordinal) ? name[prefix.Length..name.IndexOf('.', prefix.Length)] : null; + } + + private static IModel PlantedModel() + { + using var context = new PlantedContext(); + return context.GetService().Model; + } + + private sealed record RegisteredLocator(string? Module, IUserReferenceLocator Instance); + + private sealed record ModuleModel(string Module, IModel Model, IReadOnlyCollection Audited) + { + /// The plain paths the census found that no type classifies, filled as it walks. + public HashSet Identifiers { get; } = new(StringComparer.Ordinal); + + /// The strongly typed identifiers the census found, by type and path, filled as it walks. + public HashSet<(Type Type, string Path)> TypedIdentifiers { get; } = []; + + /// The audited entities' collections of identifiers, filled as the census walks. + public HashSet Collections { get; } = []; + } + + /// A collection of identifiers on an audited entity, with the person kind its element names and its column. + private sealed record IdentifierCollection(Type Entity, string Property, UserReferenceKind? Kind, bool Jsonb); + + private sealed record PersonReference(string Module, Type Entity, string Path, UserReferenceKind Kind, bool IsKey); +} + +/// +/// A synthetic audited aggregate: a typed, an untyped and a contained person reference, one the grammar cannot reach, a +/// plain no name classifies, a contained collection keyed by a person, a uuid[] and a +/// jsonb collection of identifiers, and an identifier type no allowance names. +/// +internal sealed class PlantedAggregate +{ + public Guid Id { get; set; } + public UserId Owner { get; set; } + public Guid DelegateMembershipId { get; set; } + public Guid ReviewedBy { get; set; } + public List Members { get; } = []; + public PlantedLead? Lead { get; set; } + public List Seats { get; } = []; + public List Watchers { get; set; } = []; + public List Followers { get; set; } = []; + public PlantedPersonId Instructor { get; set; } +} + +/// A strongly typed identifier over a person that no person kind names. +internal readonly record struct PlantedPersonId(Guid Value) : IStronglyTypedId +{ + public bool IsInitialized() => true; +} + +/// A contained member keyed by a person: its key is the JSON object key and a changes path segment. +internal sealed class PlantedSeat +{ + public Guid PlantedAggregateId { get; set; } + public UserId Holder { get; set; } + public int Row { get; set; } +} + +/// A synthetic audited aggregate whose composite key holds a person: no part of it is the entity's own key. +internal sealed class PlantedGrant +{ + public Guid ScopeId { get; set; } + public UserId Holder { get; set; } +} + +internal sealed class PlantedMember +{ + public Guid Id { get; set; } + public Guid PlantedAggregateId { get; set; } + public UserId Reviewer { get; set; } +} + +internal sealed class PlantedLead +{ + public Guid Id { get; set; } + public Guid PlantedAggregateId { get; set; } + public UserId Approver { get; set; } +} + +/// +/// Declares the planted references: wrongly a kind, a path the model does not hold, another module's entity, the person +/// part of a composite key and a retained reference that is not the entity's key; rightly a jsonb array of identifiers. +/// +internal sealed class PlantedLocator : IUserReferenceLocator +{ + public IReadOnlyCollection Redactable { get; } = + [ + new(typeof(PlantedAggregate), UserReferencePath.Of(nameof(PlantedAggregate.Owner)), UserReferenceKind.Membership), + new(typeof(PlantedAggregate), UserReferencePath.Of("Retired"), UserReferenceKind.User), + new(typeof(IdentityDomain.Membership), UserReferencePath.Of("Planted"), UserReferenceKind.User), + new(typeof(PlantedGrant), UserReferencePath.Of(nameof(PlantedGrant.Holder)), UserReferenceKind.User), + new(typeof(PlantedAggregate), UserReferencePath.Elements(nameof(PlantedAggregate.Followers)), UserReferenceKind.User), + ]; + + public IReadOnlyCollection Retained { get; } = + [ + new(typeof(PlantedAggregate), UserReferencePath.Of(nameof(PlantedAggregate.DelegateMembershipId)), + RetainedReferenceKind.AuditEntityReference, "Planted: a reference that is not the row's entity_id."), + ]; +} + +internal sealed class PlantedContext : DbContext +{ + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => + optionsBuilder.UseNpgsql("Host=model-only;Database=model-only;Username=model-only"); + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + modelBuilder.Entity(aggregate => + { + aggregate.Property(entity => entity.Owner).HasConversion(id => id.Value, value => UserId.From(value)); + aggregate.HasMany(entity => entity.Members).WithOne().HasForeignKey(member => member.PlantedAggregateId); + aggregate.HasOne(entity => entity.Lead).WithOne().HasForeignKey(lead => lead.PlantedAggregateId); + aggregate.HasMany(entity => entity.Seats).WithOne().HasForeignKey(seat => seat.PlantedAggregateId); + aggregate.Property(entity => entity.Followers).HasColumnType("jsonb") + .HasConversion(ids => PlantedJson.Write(ids), json => PlantedJson.Read(json)); + aggregate.Property(entity => entity.Instructor).HasConversion(id => id.Value, value => new PlantedPersonId(value)); + }); + modelBuilder.Entity(seat => + { + seat.Property(member => member.Holder).HasConversion(id => id.Value, value => UserId.From(value)); + seat.HasKey(member => new { member.PlantedAggregateId, member.Holder }); + }); + modelBuilder.Entity(grant => + { + grant.Property(entity => entity.Holder).HasConversion(id => id.Value, value => UserId.From(value)); + grant.HasKey(entity => new { entity.ScopeId, entity.Holder }); + }); + modelBuilder.Entity().Property(member => member.Reviewer).HasConversion(id => id.Value, value => UserId.From(value)); + modelBuilder.Entity().Property(lead => lead.Approver).HasConversion(id => id.Value, value => UserId.From(value)); + } +} + +/// The planted jsonb array's conversion: identifiers as an array of strings, as the capture renders them. +internal static class PlantedJson +{ + public static string Write(List ids) => System.Text.Json.JsonSerializer.Serialize(ids.Select(id => id.Value)); + + public static List Read(string json) => + [.. System.Text.Json.JsonSerializer.Deserialize>(json)!.Select(UserId.From)]; +} 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 000000000..6fc7dd88a --- /dev/null +++ b/backend/tests/LearnStack.Tests.Contract/OpenApiContractTests.DataRequests.cs @@ -0,0 +1,244 @@ +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/erasures", "post", "CreateOwnDataErasure", DataRequestShape.Create, "DataErasureAcceptedResponse", "EmptyAdministrationInput"), + new("/api/v1/identity/me/data-requests/closures", "post", "CreateOwnAccountClosure", DataRequestShape.Create, "AccountClosureAcceptedResponse", "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/erasures", "post", "CreateDataErasureForSubject", DataRequestShape.Create, "DataErasureAcceptedResponse", "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"), + ]; + + // 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, cancellation and revocation, If-Match only on cancellation and + // revocation, 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/erasures", "post", "CreateRetainedDataErasure", DataRequestShape.Create, "DataErasureAcceptedResponse", "EmptyAdministrationInput"), + new("/api/v1/identity/data-request-entry/closures", "post", "CreateRetainedAccountClosure", DataRequestShape.Create, "AccountClosureAcceptedResponse", "EmptyAdministrationInput"), + new("/api/v1/identity/data-request-entry/cancellations", "post", "CancelRetainedDataRequest", DataRequestShape.Mutation, "AdministrationVersionReceipt", "RetainedDataRequestTargetInput"), + new("/api/v1/identity/data-request-entry/revocations", "post", "RevokeRetainedDataExport", 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); + // A revocation's precondition is its artifact's version; every other mutation's is the request's. + if (contract.Shape == DataRequestShape.Mutation + && (operation["parameters"]!.AsArray().FirstOrDefault(parameter => parameter!["name"]!.GetValue() == "If-Match")?["description"]?.GetValue() ?? "") + .Contains("ARTIFACT", StringComparison.Ordinal) != contract.Id.StartsWith("Revoke", StringComparison.Ordinal)) + errors.Add("retained-data-request-if-match-version:" + 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", "DataErasureAcceptedResponse", "AccountClosureAcceptedResponse", "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); + // A revocation's precondition is its artifact's version; every other mutation's is the request's. + if (contract.Shape == DataRequestShape.Mutation + && (operation["parameters"]!.AsArray().FirstOrDefault(parameter => parameter!["name"]!.GetValue() == "If-Match")?["description"]?.GetValue() ?? "") + .Contains("ARTIFACT", StringComparison.Ordinal) != contract.Id.StartsWith("Revoke", StringComparison.Ordinal)) + errors.Add("data-request-if-match-version:" + 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); + // ADR-0107 § 7: the person alone files a closure; its accepted resource is a scheduled closure and nothing else, and + // the administrator's surface has no closure route. + if (document["components"]?["schemas"]?["AccountClosureAcceptedResponse"]?["properties"] is not JsonObject closure + || closure["kind"]?["enum"] is not JsonArray { Count: 1 } kind || kind[0]?.GetValue() != "closure" + || closure["status"]?["enum"] is not JsonArray { Count: 1 } scheduled || scheduled[0]?.GetValue() != "scheduled" + || document["paths"]?.AsObject().Any(path => path.Key.StartsWith("/api/v1/identity/data-requests", StringComparison.Ordinal) + && path.Key.Contains("closure", StringComparison.Ordinal)) != false) + errors.Add("data-request-closure"); + // 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 widened = clean.DeepClone(); + widened["components"]!["schemas"]!["AccountClosureAcceptedResponse"]!["properties"]!["kind"]!["enum"]!.AsArray().Add("erasure"); + DataRequestContractErrors(widened).Should().Contain("data-request-closure"); + + var administered = clean.DeepClone(); + administered["paths"]!.AsObject().Add("/api/v1/identity/data-requests/closures", + clean["paths"]!["/api/v1/identity/me/data-requests/closures"]!.DeepClone()); + DataRequestContractErrors(administered).Should().Contain("data-request-closure"); + + 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 dad13899c..82eb6265c 100644 --- a/backend/tests/LearnStack.Tests.Contract/OpenApiContractTests.cs +++ b/backend/tests/LearnStack.Tests.Contract/OpenApiContractTests.cs @@ -182,12 +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)))) 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) { @@ -370,7 +372,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).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 f5e751a94..280b3e1ef 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,31 @@ 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), "CreateErasure", "CreateOwnDataErasure", "POST", "identity/me/data-requests/erasures", typeof(CreateOwnDataErasureCommand), "identity.data_request.create_own_erasure", Protected: ProtectedAdministrationOperation.CreateOwnDataErasure), + new(typeof(OwnDataRequestsController), "CreateClosure", "CreateOwnAccountClosure", "POST", "identity/me/data-requests/closures", typeof(CreateOwnAccountClosureCommand), "identity.data_request.create_own_closure", Protected: ProtectedAdministrationOperation.CreateOwnAccountClosure), + 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), "CreateErasure", "CreateDataErasureForSubject", "POST", "identity/data-requests/erasures", typeof(CreateDataErasureForSubjectCommand), "identity.data_request.create_erasure", Protected: ProtectedAdministrationOperation.CreateDataErasureForSubject), + 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), + // 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), "CreateErasure", "CreateRetainedDataErasure", "POST", "identity/data-request-entry/erasures", typeof(CreateRetainedDataErasureCommand), "identity.data_request.create_retained_erasure", Protected: ProtectedAdministrationOperation.CreateRetainedDataErasure), + new(typeof(DataRequestEntryController), "CreateClosure", "CreateRetainedAccountClosure", "POST", "identity/data-request-entry/closures", typeof(CreateRetainedAccountClosureCommand), "identity.data_request.create_retained_closure", Protected: ProtectedAdministrationOperation.CreateRetainedAccountClosure), + new(typeof(DataRequestEntryController), "Cancel", "CancelRetainedDataRequest", "POST", "identity/data-request-entry/cancellations", typeof(CancelRetainedDataRequestCommand), "identity.data_request.cancel_retained", Protected: ProtectedAdministrationOperation.CancelRetainedDataRequest), + new(typeof(DataRequestEntryController), "RevokeExport", "RevokeRetainedDataExport", "POST", "identity/data-request-entry/revocations", typeof(RevokeRetainedDataExportCommand), "identity.data_request.revoke_retained_export", Protected: ProtectedAdministrationOperation.RevokeRetainedDataExport), + 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] @@ -161,10 +187,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(96, ExpectedActions.Length); + Assert.Equal(37, 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(96, 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 +327,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(37, protectedActions.Length); foreach (var expected in protectedActions) { var original = Assert.Single(endpoints, endpoint => endpoint.Metadata.GetMetadata()?.EndpointName == expected.Name); @@ -330,7 +356,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(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 8f4cd553a..2974ee735 100644 --- a/backend/tests/LearnStack.Tests.Integration/AuthenticatedHttpSurfaceRuntimeTests.Metadata.cs +++ b/backend/tests/LearnStack.Tests.Integration/AuthenticatedHttpSurfaceRuntimeTests.Metadata.cs @@ -51,7 +51,11 @@ 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 + or ProtectedAdministrationOperation.CreateRetainedDataExport or ProtectedAdministrationOperation.CreateOwnDataErasure + or ProtectedAdministrationOperation.CreateDataErasureForSubject or ProtectedAdministrationOperation.CreateRetainedDataErasure + or ProtectedAdministrationOperation.CreateOwnAccountClosure or ProtectedAdministrationOperation.CreateRetainedAccountClosure ? 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 5631e04ab..55a010482 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,32 @@ 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/erasures", "POST", typeof(OwnDataRequestsController), "CreateErasure", typeof(CreateOwnDataErasureCommand), typeof(DataErasureAcceptedResponse), "identity.data_request.create_own_erasure", ProtectedAdministrationOperation.CreateOwnDataErasure), + new("identity/me/data-requests/closures", "POST", typeof(OwnDataRequestsController), "CreateClosure", typeof(CreateOwnAccountClosureCommand), typeof(AccountClosureAcceptedResponse), "identity.data_request.create_own_closure", ProtectedAdministrationOperation.CreateOwnAccountClosure), + 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/erasures", "POST", typeof(DataRequestsController), "CreateErasure", typeof(CreateDataErasureForSubjectCommand), typeof(DataErasureAcceptedResponse), "identity.data_request.create_erasure", ProtectedAdministrationOperation.CreateDataErasureForSubject), + 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), + // 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/erasures", "POST", typeof(DataRequestEntryController), "CreateErasure", typeof(CreateRetainedDataErasureCommand), typeof(DataErasureAcceptedResponse), "identity.data_request.create_retained_erasure", ProtectedAdministrationOperation.CreateRetainedDataErasure), + new("identity/data-request-entry/closures", "POST", typeof(DataRequestEntryController), "CreateClosure", typeof(CreateRetainedAccountClosureCommand), typeof(AccountClosureAcceptedResponse), "identity.data_request.create_retained_closure", ProtectedAdministrationOperation.CreateRetainedAccountClosure), + 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/revocations", "POST", typeof(DataRequestEntryController), "RevokeExport", typeof(RevokeRetainedDataExportCommand), typeof(AdministrationVersionReceipt), "identity.data_request.revoke_retained_export", ProtectedAdministrationOperation.RevokeRetainedDataExport), + 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. @@ -131,7 +158,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), typeof(DataRequestEntryController)]; private const string CensusTarget = "018f4d40-0000-7000-8000-000000000011"; private static SurfaceAction Approved(ControllerActionDescriptor action) => ApprovedActions.Single(expected => @@ -315,7 +343,7 @@ private static void AssertEndpointAuthorization(ControllerActionDescriptor actio private static void AssertActionInventory(IEnumerable actions) { var actual = actions.ToArray(); - actual.Should().HaveCount(72); + actual.Should().HaveCount(96); 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"); @@ -433,6 +461,24 @@ 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), + "CreateErasure" => new CreateRetainedDataErasureCommand(organization), + "CreateClosure" => new CreateRetainedAccountClosureCommand(organization), + "Cancel" => new CancelRetainedDataRequestCommand(organization, Guid.Parse(CensusTarget), 7), + "RevokeExport" => new RevokeRetainedDataExportCommand(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 @@ -451,7 +497,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 +512,12 @@ 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 or ProtectedAdministrationOperation.CreateRetainedDataExport + or ProtectedAdministrationOperation.CreateOwnDataErasure or ProtectedAdministrationOperation.CreateDataErasureForSubject + or ProtectedAdministrationOperation.CreateRetainedDataErasure or ProtectedAdministrationOperation.CreateOwnAccountClosure + or ProtectedAdministrationOperation.CreateRetainedAccountClosure)) + 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 +623,15 @@ 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 or ProtectedAdministrationOperation.CreateRetainedDataExport + or ProtectedAdministrationOperation.CreateOwnDataErasure or ProtectedAdministrationOperation.CreateRetainedDataErasure + or ProtectedAdministrationOperation.CreateOwnAccountClosure or ProtectedAdministrationOperation.CreateRetainedAccountClosure => "{}", + ProtectedAdministrationOperation.CancelRetainedDataRequest or ProtectedAdministrationOperation.RevokeRetainedDataExport => + "{\"requestId\":\"" + CensusTarget + "\"}", + ProtectedAdministrationOperation.CreateDataExportForSubject or ProtectedAdministrationOperation.CreateDataErasureForSubject => + "{\"membershipId\":\"" + CensusTarget + "\"}", _ => throw new InvalidOperationException("Unclassified protected census input"), }; @@ -584,8 +647,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(96); + ApprovedActions.Count(expected => expected.Protected is not null).Should().Be(37); 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/BackgroundJobProductionManifestTests.cs b/backend/tests/LearnStack.Tests.Integration/BackgroundJobProductionManifestTests.cs index 6019ffcd2..164d17da1 100644 --- a/backend/tests/LearnStack.Tests.Integration/BackgroundJobProductionManifestTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/BackgroundJobProductionManifestTests.cs @@ -179,13 +179,27 @@ 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", + // ADR-0107 § 2, § 5: the tenant-side erasure, once per scope group. + "identity.data_erasure_tenant.v1", "identity.data_erasure_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), + (typeof(LearnStack.Modules.Identity.Application.DataRequests.RunTenantDataErasureCommand), BackgroundJobScope.TenantWide), + (typeof(LearnStack.Modules.Identity.Application.DataRequests.RunOrganizationDataErasureCommand), BackgroundJobScope.Organization), }; var actualDefinitions = definitions.DefinitionKeys.ToArray(); var actualRequests = definitions.All.Where(item => item.Classification == BackgroundJobRequestClassification.Ordinary) @@ -239,6 +253,31 @@ private static void AssertRoutes(IServiceProvider services) "identity/invitation-entry/inspections|POST|" + typeof(InvitationEntryController).FullName + ".Inspect", "identity/invitation-entry/acceptances|POST|" + typeof(InvitationEntryController).FullName + ".Accept", "identity/invitation-entry/results|POST|" + typeof(InvitationEntryController).FullName + ".Result", + // P03-10 subject data requests: own, administrator and retained-entry routes; none is a job operator route. + "identity/me/data-requests/exports|POST|" + typeof(OwnDataRequestsController).FullName + ".Create", + "identity/me/data-requests/erasures|POST|" + typeof(OwnDataRequestsController).FullName + ".CreateErasure", + "identity/me/data-requests/closures|POST|" + typeof(OwnDataRequestsController).FullName + ".CreateClosure", + "identity/me/data-requests|GET|" + typeof(OwnDataRequestsController).FullName + ".List", + "identity/me/data-requests/{id}|GET|" + typeof(OwnDataRequestsController).FullName + ".Get", + "identity/me/data-requests/{id}/cancellations|POST|" + typeof(OwnDataRequestsController).FullName + ".Cancel", + "identity/me/data-requests/{id}/artifact/revocations|POST|" + typeof(OwnDataRequestsController).FullName + ".Revoke", + "identity/me/data-requests/{id}/artifact/tickets|POST|" + typeof(OwnDataExportTicketsController).FullName + ".MintTicket", + "identity/me/data-requests/{id}/artifact/chunks|POST|" + typeof(OwnDataExportChunksController).FullName + ".ReadChunk", + "identity/data-requests/exports|POST|" + typeof(DataRequestsController).FullName + ".Create", + "identity/data-requests/erasures|POST|" + typeof(DataRequestsController).FullName + ".CreateErasure", + "identity/data-requests|GET|" + typeof(DataRequestsController).FullName + ".List", + "identity/data-requests/{id}|GET|" + typeof(DataRequestsController).FullName + ".Get", + "identity/data-requests/{id}/cancellations|POST|" + typeof(DataRequestsController).FullName + ".Cancel", + "identity/data-requests/{id}/artifact/revocations|POST|" + typeof(DataRequestsController).FullName + ".Revoke", + "identity/data-request-entry/scopes|GET|" + typeof(DataRequestEntryController).FullName + ".Scopes", + "identity/data-request-entry/requests|GET|" + typeof(DataRequestEntryController).FullName + ".Requests", + "identity/data-request-entry/exports|POST|" + typeof(DataRequestEntryController).FullName + ".CreateExport", + "identity/data-request-entry/erasures|POST|" + typeof(DataRequestEntryController).FullName + ".CreateErasure", + "identity/data-request-entry/closures|POST|" + typeof(DataRequestEntryController).FullName + ".CreateClosure", + "identity/data-request-entry/cancellations|POST|" + typeof(DataRequestEntryController).FullName + ".Cancel", + "identity/data-request-entry/revocations|POST|" + typeof(DataRequestEntryController).FullName + ".RevokeExport", + "identity/data-request-entry/tickets|POST|" + typeof(DataRequestEntryController).FullName + ".MintTicket", + "identity/data-request-entry/chunks|POST|" + typeof(DataRequestEntryController).FullName + ".ReadChunk", // ADR-0099 federation administration: one controller, eleven routes. "identity/federation|GET|" + typeof(FederationController).FullName + ".Get", "identity/federation/configuration|PUT|" + typeof(FederationController).FullName + ".Configure", diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureAdministratorParityTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureAdministratorParityTests.cs new file mode 100644 index 000000000..d633450f2 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureAdministratorParityTests.cs @@ -0,0 +1,221 @@ +using System.Reflection; +using FluentAssertions; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.DataRequests; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The closure's last-administrator read on the platform connection against the administrator predicate the deferred +/// complete-graph guard enforces, over the same fixtures (ADR-0107 § 7). The guard is asked by the only question it +/// answers: a Membership write in the tenant commits only while an eligible tenant-wide administrator remains. So, with +/// exactly two candidate people in tenant B, revoking the subject's Memberships passes the guard exactly when the read says +/// somebody else is eligible, and revoking the other's passes exactly when it says the subject is. +/// +/// +/// The application role's read of the same predicate (DataRequestStore) cannot see another person's User status; +/// it agrees with the platform read in every fixture but the one whose other administrator's User is Closing, which is the +/// one condition the platform read adds. +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed class AccountClosureAdministratorParityTests(SchemaFixture schema) +{ + private static readonly Guid Tenant = SchemaFixture.TenantB; + + public enum Fixture + { + ActiveAdministrator, + SuspendedAdministrator, + RevokedAdministrator, + ClosingAdministrator, + OrganizationAdministrator, + TenantWideLearner, + KernelGrantMissing, + SubjectIsALearner, + } + + [Theory] + [InlineData(Fixture.ActiveAdministrator, true, true)] + [InlineData(Fixture.SuspendedAdministrator, true, false)] + [InlineData(Fixture.RevokedAdministrator, true, false)] + [InlineData(Fixture.ClosingAdministrator, true, false)] + [InlineData(Fixture.OrganizationAdministrator, true, false)] + [InlineData(Fixture.TenantWideLearner, true, false)] + [InlineData(Fixture.KernelGrantMissing, false, false)] + [InlineData(Fixture.SubjectIsALearner, false, true)] + public async Task The_platform_read_answers_as_the_complete_graph_guard_for_every_administrator_state( + Fixture fixture, bool subjectEligible, bool otherEligible) + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var (subject, other) = await ArrangeAsync(kit, fixture); + + var platform = await PlatformStandingAsync(kit, subject); + platform.Should().Be((subjectEligible, otherEligible), "the platform read over " + fixture); + + (await RevocationCommitsAsync(kit, subject)).Should().Be(otherEligible, + "the guard lets the subject go exactly when somebody else is eligible: " + fixture); + if (fixture != Fixture.RevokedAdministrator) + { + (await RevocationCommitsAsync(kit, other)).Should().Be(subjectEligible, + "the guard lets the other go exactly when the subject is eligible: " + fixture); + } + + var application = await ApplicationStandingAsync(kit, subject); + application.Should().Be(fixture == Fixture.ClosingAdministrator ? (true, true) : platform, + "the application role's read differs only where it cannot see a User's status"); + } + + /// The subject and the one other candidate of tenant B, in the fixture's state. + private static async Task<(Guid Subject, Guid Other)> ArrangeAsync(AccountClosureBeginKit kit, Fixture fixture) + { + if (fixture == Fixture.SubjectIsALearner) + { + // Tenant B's seeded people: its administrator and a branch learner. + return (PersonB, AdminB); + } + + var other = await kit.PersonAsync(); + var membership = fixture switch + { + Fixture.OrganizationAdministrator => await kit.MemberAsync(Tenant, SchemaFixture.OrgB1, other, BuiltInRoleKey.OrgAdmin), + Fixture.TenantWideLearner => await kit.MemberAsync(Tenant, null, other, BuiltInRoleKey.Learner), + _ => await kit.MemberAsync(Tenant, null, other, BuiltInRoleKey.TenantAdmin), + }; + switch (fixture) + { + case Fixture.SuspendedAdministrator: + await using (var app = await DataExportTestKit.OpenAppAsync(kit.Database.AppConnectionString)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, transaction, Tenant); + await LockAsync(app, transaction, Tenant, other, exclusive: true); + await ExecuteAsync(app, transaction, "UPDATE public.memberships SET status='Suspended' WHERE id=@id", ("id", membership)); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await transaction.CommitAsync(); + } + + break; + case Fixture.RevokedAdministrator: + await AccountClosureBeginTests.RevokeAsync(kit, Tenant, null, other, membership); + break; + case Fixture.ClosingAdministrator: + // The closure's own writer: the platform session under the person's and the tenant's fences. + await using (var platform = await AccountClosureBeginKit.OpenAsync(kit.Database.PlatformConnectionString)) + await using (var transaction = await platform.BeginTransactionAsync()) + { + await ExecuteAsync(platform, transaction, "SELECT pg_catalog.pg_advisory_xact_lock(@key)", ("key", AccountClosureBeginKit.UserKey(other))); + await ExecuteAsync(platform, transaction, "SELECT pg_catalog.pg_advisory_xact_lock(@key)", ("key", AccountClosureBeginKit.TenantKey(Tenant))); + await ExecuteAsync(platform, transaction, "UPDATE public.users SET status='Closing' WHERE id=@user", ("user", other)); + await transaction.CommitAsync(); + } + + break; + case Fixture.KernelGrantMissing: + // No product path reaches it, because the guard refuses the grant's removal; a superuser fixture does. + await kit.SqlAsync($""" + SET session_replication_role = replica; + DELETE FROM public.role_permission_grants WHERE tenant_id = '{Tenant}' + AND role_id = '{RoleId(Tenant, BuiltInRoleKey.TenantAdmin, PermissionScope.Tenant)}' + AND permission_key = '{IdentityFoundationManifest.RoleAdmin}'; + """); + break; + } + + return (AdminB, other); + } + + private static async Task<(bool Subject, bool Other)> PlatformStandingAsync(AccountClosureBeginKit kit, Guid subject) + { + await using var platform = await AccountClosureBeginKit.OpenAsync(kit.Database.PlatformConnectionString); + await using var command = new NpgsqlCommand(AccountClosureOperatorOperations.AdministratorStandingSql, platform); + command.Parameters.AddWithValue("subject", subject); + command.Parameters.AddWithValue("tenants", new[] { Tenant }); + await using var reader = await command.ExecuteReaderAsync(); + if (!await reader.ReadAsync()) + { + return (false, false); + } + + reader.GetGuid(0).Should().Be(Tenant); + var standing = (reader.GetBoolean(1), reader.GetBoolean(2)); + (await reader.ReadAsync()).Should().BeFalse("one row per tenant"); + return standing; + } + + private static async Task<(bool Subject, bool Other)> ApplicationStandingAsync(AccountClosureBeginKit kit, Guid subject) + { + var sql = (string)typeof(DataRequestStore).GetField("AdministratorStanding", BindingFlags.Static | BindingFlags.NonPublic)! + .GetValue(null)!; + await using var app = await DataExportTestKit.OpenAppAsync(kit.Database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, Tenant); + await using var command = new NpgsqlCommand(sql, app, transaction); + command.Parameters.AddWithValue("tenant", Tenant); + command.Parameters.AddWithValue("subject", subject); + await using var reader = await command.ExecuteReaderAsync(); + (await reader.ReadAsync()).Should().BeTrue(); + return (reader.GetBoolean(0), reader.GetBoolean(1)); + } + + /// + /// Whether revoking every live Membership the person holds in tenant B commits past the complete-graph guard, which runs + /// at once here; the probe always rolls back. + /// + private static async Task RevocationCommitsAsync(AccountClosureBeginKit kit, Guid person) + { + var live = new List<(Guid Membership, Guid? Organization)>(); + foreach (var organization in new Guid?[] { null, SchemaFixture.OrgB1 }) + foreach (var membership in await LiveMembershipsAsync(kit, person, organization)) + live.Add((membership, organization)); + live.Should().NotBeEmpty("the probe revokes something"); + + await using var app = await DataExportTestKit.OpenAppAsync(kit.Database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await LockAsync(app, transaction, Tenant, person, exclusive: true); + try + { + foreach (var (membership, organization) in live) + { + await ScopeAsync(app, transaction, Tenant, organization); + await ExecuteAsync(app, transaction, """ + UPDATE public.memberships SET status='Revoked', deleted_at=clock_timestamp(), deleted_by=@system, + updated_at=clock_timestamp(), updated_by=@system, row_version=row_version+1 + WHERE id=@member + """, ("member", membership), ("system", UserId.SystemActor.Value)); + } + + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + return true; + } + catch (PostgresException refusal) when (refusal.SqlState == "P0303") + { + return false; + } + finally + { + await transaction.RollbackAsync(); + } + } + + private static async Task> LiveMembershipsAsync(AccountClosureBeginKit kit, Guid person, Guid? organization) + { + await using var platform = await AccountClosureBeginKit.OpenAsync(kit.Database.PlatformConnectionString); + await using var command = new NpgsqlCommand(""" + SELECT id FROM public.memberships WHERE tenant_id=@tenant AND user_id=@user + AND organization_id IS NOT DISTINCT FROM @organization AND status <> 'Revoked' + """, platform); + command.Parameters.AddWithValue("tenant", Tenant); + command.Parameters.AddWithValue("user", person); + command.Parameters.Add(new NpgsqlParameter("organization", NpgsqlTypes.NpgsqlDbType.Uuid) { Value = (object?)organization ?? DBNull.Value }); + await using var reader = await command.ExecuteReaderAsync(); + var ids = new List(); + while (await reader.ReadAsync()) ids.Add(reader.GetGuid(0)); + return ids; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureBeginKit.cs b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureBeginKit.cs new file mode 100644 index 000000000..ab5385067 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureBeginKit.cs @@ -0,0 +1,439 @@ +using System.Globalization; +using FluentAssertions; +using LearnStack.Api.Composition; +using LearnStack.Infrastructure.Audit; +using LearnStack.Infrastructure.MultiTenancy; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.Modules.Identity.Infrastructure.DataRequests; +using LearnStack.Modules.Tenancy.Application.Audit; +using LearnStack.Modules.Tenancy.Infrastructure.Persistence; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using LearnStack.Tests.Fixtures; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; +using static LearnStack.Tests.Integration.Database.DataRequestSchemaSeed; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// A disposable seeded database for the closure's Begin, the real platform scope with the real audit store over it, and the +/// fixture writers a closure needs: fresh persons, Memberships under the canonical fences, closure requests due or still in +/// their window. Fixture rows are written by the application role exactly as the product writes them, and only what no +/// product path can write yet (a backdated window, a suspended tenant) by the owner or the superuser. +/// +internal sealed class AccountClosureBeginKit : IAsyncDisposable +{ + private readonly PostgresFixture _postgres; + private readonly NpgsqlDataSource _platform; + private readonly NpgsqlDataSource _app; + private readonly NpgsqlUnitOfWork _unused; + + private AccountClosureBeginKit(PostgresFixture postgres, DisposableSchemaDatabase database) + { + _postgres = postgres; + Database = database; + _platform = LearnStack.Api.Composition.PersistenceCompositionExtensions.BuildPlatformDataSource(database.PlatformConnectionString); + _app = ApplicationDataSource.Build(database.AppConnectionString); + // The Tenancy reader is constructed as production constructs it; its platform form never touches this unit. + _unused = new NpgsqlUnitOfWork(_app, NullLogger.Instance); + } + + internal DisposableSchemaDatabase Database { get; } + + internal static async Task CreateAsync(PostgresFixture postgres) => + new(postgres, await DataExportTestKit.CreateSeededDatabaseAsync(postgres)); + + internal static PlatformAdmission Admission(string? ticket = null) => + TestPlatformAdmissions.Admission( + PlatformOperations.ClosureBegin, ticket, correlationId: "00-closure-begin-" + Guid.NewGuid().ToString("N")); + + internal static long UserKey(Guid user) => IdentityAdvisoryLockKey.ForUser(UserId.From(user)); + + internal static long TenantKey(Guid tenant) => IdentityAdvisoryLockKey.ForTenant(TenantId.From(tenant)); + + /// The scope as production builds it, with the real audit store. + internal PlatformAdminScope Scope() => new( + new PrivilegedDataSource(() => _platform), new AuditCatalog([new TenancyAuditCatalogSource()]), AuditServices(), + new SystemClock(), new SystemGuidFactory(), NullLogger.Instance); + + internal AccountClosureOperatorOperations Owner( + IClosureFanOut? fanOut = null, IDataRequestHoldSource? holds = null, IPlatformAdminScope? scope = null, + IIdentityProviderAccountRemoval? removal = null, Microsoft.Extensions.Logging.ILogger? logger = null) => new( + scope ?? Scope(), new ClosureGroupLifecycleReader(new IdentityScopeLifecycleReader(_unused)), holds ?? new NoHoldSource(), + [fanOut ?? new RecordingFanOut()], removal ?? new RecordingAccountRemoval(), + logger ?? NullLogger.Instance); + + /// A fresh Active person with a creation row, as the product binds one. + internal async Task PersonAsync() + { + var person = Guid.CreateVersion7(); + await InsertUserAsync(Database.AppConnectionString, person); + return person; + } + + /// One Membership with one Role, written by the application role under the person's and the tenant's fences. + internal async Task MemberAsync(Guid tenant, Guid? organization, Guid person, BuiltInRoleKey role) + { + var member = Guid.CreateVersion7(); + await using var app = await DataExportTestKit.OpenAppAsync(Database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant, organization); + await LockAsync(app, transaction, tenant, person, exclusive: role == BuiltInRoleKey.TenantAdmin); + await InsertMemberAsync(app, transaction, tenant, organization, member, person, + RoleId(tenant, role, organization is null ? PermissionScope.Tenant : PermissionScope.Organization)); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await transaction.CommitAsync(); + return member; + } + + /// + /// A closure the person files in the group, its snapshot every Membership they hold there; a due one is backdated past + /// its 24 hours by the owner with the one guard paused, as a closure filed a day ago looks. + /// + internal async Task ClosureAsync(Guid tenant, Guid? organization, Guid person, bool due = true) + { + var id = Guid.CreateVersion7(); + var memberships = await MembershipsAsync(tenant, organization, person); + await using (var app = await DataExportTestKit.OpenAppAsync(Database.AppConnectionString)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, tenant, organization, person); + await InsertRequestAsync(app, transaction, id, tenant, organization, person, [.. memberships], "closure"); + await transaction.CommitAsync(); + } + + if (due) + { + await BackdateAsync(id, tenant, organization); + } + + return id; + } + + internal async Task BackdateAsync(Guid request, Guid tenant, Guid? organization) + { + await using var owner = await 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, 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 ExecuteAsync(owner, transaction, "ALTER TABLE public.data_subject_requests ENABLE TRIGGER tg_data_subject_requests_mutation_guard"); + await transaction.CommitAsync(); + } + + /// A request of another kind or status for the person, written with the guards paused. + internal async Task RequestRowAsync(Guid tenant, Guid person, string kind, string status) + { + var id = Guid.CreateVersion7(); + var membership = (await MembershipsAsync(tenant, null, person))[0]; + var window = kind != "export"; + await SqlAsync($""" + SET session_replication_role = replica; + INSERT INTO data_subject_requests (id, tenant_id, organization_id, kind, origin, subject_user_id, requester_user_id, + status, membership_snapshot, execute_at, completed_at, created_at, created_by, updated_at, updated_by, row_version) + SELECT '{id}', '{tenant}', NULL, '{kind}', 'self', '{person}', '{person}', '{status}', '["{membership}"]'::jsonb, + {(window ? "at + interval '24 hours'" : "NULL")}, {(status == "completed" ? "now()" : "NULL")}, at, '{person}', + {(status is "scheduled" or "requested" ? "NULL" : "now()")}, + {(status is "scheduled" or "requested" ? "NULL" : $"'{UserId.SystemActor.Value}'")}, + {(status is "scheduled" or "requested" ? 0 : 2)} + FROM (SELECT now() - interval '2 days' AS at) AS created + """); + return id; + } + + internal async Task> MembershipsAsync(Guid tenant, Guid? organization, Guid person) + { + await using var platform = await OpenAsync(Database.PlatformConnectionString); + await using var command = new NpgsqlCommand(""" + SELECT id FROM public.memberships + WHERE tenant_id=@tenant AND organization_id IS NOT DISTINCT FROM @organization AND user_id=@user ORDER BY id + """, platform); + command.Parameters.AddWithValue("tenant", tenant); + command.Parameters.Add(new NpgsqlParameter("organization", NpgsqlTypes.NpgsqlDbType.Uuid) { Value = (object?)organization ?? DBNull.Value }); + command.Parameters.AddWithValue("user", person); + await using var reader = await command.ExecuteReaderAsync(); + var ids = new List(); + while (await reader.ReadAsync()) ids.Add(reader.GetGuid(0)); + return ids; + } + + /// Sets a tenant's status, as an operator's lifecycle act would, with no trigger to stop a fixture. + internal Task TenantStatusAsync(Guid tenant, string status) => + SqlAsync($"SET session_replication_role = replica; UPDATE public.tenants SET status = '{status}' WHERE id = '{tenant}'"); + + internal Task OrganizationStatusAsync(Guid tenant, Guid organization, string status) => + SqlAsync($"SET session_replication_role = replica; UPDATE public.organizations SET status = '{status}' WHERE tenant_id = '{tenant}' AND id = '{organization}'"); + + internal Task SqlAsync(string sql) => _postgres.ExecuteAsSuperuserAsync(sql, RebindProofSupport.DatabaseOf(Database.MigrationConnectionString)); + + internal sealed record UserRow(string Status, long Version, bool SubjectPresent); + + /// The User as the migration owner reads it: the platform role is not granted its version. + internal async Task UserAsync(Guid user) + { + await using var owner = await OpenAsync(Database.MigrationConnectionString); + await using var command = new NpgsqlCommand( + "SELECT status, row_version, provider_subject IS NOT NULL FROM public.users WHERE id=@user", owner); + command.Parameters.AddWithValue("user", user); + await using var reader = await command.ExecuteReaderAsync(); + (await reader.ReadAsync()).Should().BeTrue(); + return new UserRow(reader.GetString(0), reader.GetInt64(1), reader.GetBoolean(2)); + } + + internal sealed record RequestRow(string Status, string? LastRefusal, long Version); + + internal async Task RequestAsync(Guid id) + { + await using var platform = await OpenAsync(Database.PlatformConnectionString); + await using var command = new NpgsqlCommand( + "SELECT status, last_refusal, row_version FROM public.data_subject_requests WHERE id=@id", platform); + command.Parameters.AddWithValue("id", id); + await using var reader = await command.ExecuteReaderAsync(); + (await reader.ReadAsync()).Should().BeTrue(); + return new RequestRow(reader.GetString(0), reader.IsDBNull(1) ? null : reader.GetString(1), reader.GetInt64(2)); + } + + internal sealed record AuditRow( + Guid Tenant, string Module, string Operation, string? Reason, Guid? Actor, string? EntityType, string? EntityId, + string Before, string After, string Metadata); + + internal async Task> AuditAsync(string correlation) + { + await using var platform = await OpenAsync(Database.PlatformConnectionString); + await using var command = new NpgsqlCommand(""" + SELECT tenant_id, module, operation, reason, actor_user_id, entity_type, entity_id, before_state::text, + after_state::text, metadata::text + FROM audit_log WHERE correlation_id = @c ORDER BY timestamp, id + """, platform); + command.Parameters.AddWithValue("c", correlation); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await reader.ReadAsync()) + { + rows.Add(new AuditRow( + reader.GetGuid(0), reader.GetString(1), reader.GetString(2), reader.IsDBNull(3) ? null : reader.GetString(3), + reader.IsDBNull(4) ? null : reader.GetGuid(4), reader.IsDBNull(5) ? null : reader.GetString(5), + reader.IsDBNull(6) ? null : reader.GetString(6), reader.IsDBNull(7) ? string.Empty : reader.GetString(7), + reader.IsDBNull(8) ? string.Empty : reader.GetString(8), reader.IsDBNull(9) ? string.Empty : reader.GetString(9))); + } + + return rows; + } + + /// The Begin result rows written for a request, by any operator. + internal async Task ResultRowsAsync(Guid request) + { + await using var platform = await OpenAsync(Database.PlatformConnectionString); + await using var command = new NpgsqlCommand( + "SELECT count(*) FROM audit_log WHERE operation = 'platform.closure.begin' AND entity_id = @id", platform); + command.Parameters.AddWithValue("id", request.ToString("D", CultureInfo.InvariantCulture)); + return (long)(await command.ExecuteScalarAsync())!; + } + + /// + /// The advisory keys held, granted, by the other platform-role backends of this database, with their mode: what a Begin + /// holds while a gate keeps it open. The observer's own backend is left out. + /// + internal async Task> PlatformAdvisoryLocksAsync() + { + await using var observer = await OpenAsync(Database.PlatformConnectionString); + await using var command = new NpgsqlCommand(""" + SELECT ((l.classid::bigint << 32) | l.objid::bigint), l.mode + FROM pg_catalog.pg_locks AS l JOIN pg_catalog.pg_stat_activity AS a ON a.pid = l.pid + WHERE l.locktype = 'advisory' AND l.granted AND l.objsubid = 1 AND a.datname = current_database() + AND a.usename = 'learnstack_platform' AND l.pid <> pg_backend_pid() + ORDER BY 1 + """, observer); + await using var reader = await command.ExecuteReaderAsync(); + var held = new List<(long, string)>(); + while (await reader.ReadAsync()) held.Add((reader.GetInt64(0), reader.GetString(1))); + return held; + } + + /// Waits, from pg_locks, until a backend of the given role in this database waits on a lock. + internal async Task WaitUntilALockIsAwaitedAsync(string role, Task contender, string because) + { + await using var observer = await OpenAsync(Database.PlatformConnectionString); + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(30); + while (true) + { + contender.IsCompleted.Should().BeFalse(because); + await using var command = new NpgsqlCommand( + "SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_locks l JOIN pg_catalog.pg_stat_activity a ON a.pid = l.pid " + + "WHERE a.datname = current_database() AND a.usename = @role AND NOT l.granted)", observer); + command.Parameters.AddWithValue("role", role); + if ((bool)(await command.ExecuteScalarAsync())!) return; + DateTime.UtcNow.Should().BeBefore(deadline, because); + await Task.Delay(TimeSpan.FromMilliseconds(20)); + } + } + + internal static async Task OpenAsync(string connectionString) => + (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); + + /// Every module's reference locator, as the production composition registers them. + internal static IReadOnlyList Locators() + { + var services = new ServiceCollection(); + services.AddIdentityContextualFoundation(); + services.AddDataExportCustody(new Microsoft.Extensions.Configuration.ConfigurationBuilder().Build()); + using var provider = services.BuildServiceProvider(); + return [.. provider.GetServices()]; + } + + public async ValueTask DisposeAsync() + { + await _unused.DisposeAsync(); + await _app.DisposeAsync(); + await _platform.DisposeAsync(); + await Database.DisposeAsync(); + } + + /// The audit store and the real redaction executor over the production locators, as the scope resolves them. + private static IServiceScopeFactory AuditServices() => new ServiceCollection() + .AddSingleton(new AuditRedactionExecutor(Locators())) + .AddMetrics() + .AddLogging() + .AddScoped() + .AddSingleton() + .AddSingleton(new AuditCatalog([new TenancyAuditCatalogSource()])) + .AddSingleton(StaticTenantContextAccessor.Unresolved) + .AddScoped() + .AddSingleton(new Lazy(() => throw new InvalidOperationException("The scope's rows are written on its own connection."))) + .AddScoped() + .BuildServiceProvider() + .GetRequiredService(); +} + +/// +/// The identity provider's stand-in: it records each subject it is asked to delete, may run a probe first (which sees the +/// database while the act is between its two transactions), and answers what a test sets, removed by default, or throws. +/// Its preflight accepts every subject unless a test says otherwise, and records what it was asked. +/// +internal sealed class RecordingAccountRemoval : IIdentityProviderAccountRemoval +{ + public List Subjects { get; } = []; + + public List Preflights { get; } = []; + + public Func Accepts { get; set; } = _ => true; + + public bool CanRemove(string providerSubject) + { + Preflights.Add(providerSubject); + return Accepts(providerSubject); + } + + public Func Answer { get; set; } = _ => AccountRemovalOutcome.Removed; + + public Func? Probe { get; set; } + + public Exception? Failure { get; set; } + + public async Task RemoveAsync(string providerSubject, CancellationToken cancellationToken = default) + { + Subjects.Add(providerSubject); + if (Probe is { } probe) await probe(); + if (Failure is { } failure) throw failure; + return Answer(Subjects.Count); + } +} + +/// +/// The fan-out's stand-in: it records each call, answers each group with the outcome a test sets (started by default), or +/// throws, and may run a probe first, which sees the database as the fan-out would. +/// +internal sealed class RecordingFanOut : IClosureFanOut +{ + public List<(PlatformOperatorWitness Operator, string? Ticket, ClosureFanOutRequest Request)> Calls { get; } = []; + + public Func Outcome { get; set; } = _ => ClosureGroupOutcome.Started; + + public Exception? Failure { get; set; } + + public Func? Probe { get; set; } + + public async Task> FanOutAsync( + PlatformOperatorWitness operatorWitness, string? ticket, ClosureFanOutRequest request, CancellationToken cancellationToken = default) + { + Calls.Add((operatorWitness, ticket, request)); + if (Probe is { } probe) await probe(); + if (Failure is { } failure) throw failure; + return [.. request.Groups.Select(group => new ClosureGroupReport(group, Outcome(group)))]; + } +} + +/// +/// The hold seam's stand-in: it reports a hold or none, records each query, and may hold the act open at the call, when +/// the Begin holds every fence and its request lock and has written nothing. +/// +internal sealed class GatedHolds(bool hold = false, bool gate = false) : IDataRequestHoldSource +{ + public List Queries { get; } = []; + + public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public async Task HasHoldAsync(DataRequestHoldQuery query, CancellationToken cancellationToken) + { + Queries.Add(query); + if (gate && Queries.Count == 1) + { + Entered.SetResult(); + await Release.Task; + } + + return hold; + } +} + +/// The real scope with a handle whose commit is never sent and whose answer is a timeout, as a lost reply. +internal sealed class LostCommitScope(IPlatformAdminScope inner) : IPlatformAdminScope +{ + public async Task EnterAsync( + PlatformAdmission admission, CancellationToken cancellationToken = default, + [System.Runtime.CompilerServices.CallerMemberName] string? callerMember = null, + [System.Runtime.CompilerServices.CallerFilePath] string? callerFile = null, + [System.Runtime.CompilerServices.CallerLineNumber] int callerLine = 0) => + new Handle(await inner.EnterAsync(admission, cancellationToken, callerMember, callerFile, callerLine)); + + private sealed class Handle(IPlatformAdminScopeHandle real) : IPlatformAdminScopeHandle + { + public Task ExecuteAsync(string sql, IReadOnlyList? parameters = null, CancellationToken cancellationToken = default) => + real.ExecuteAsync(sql, parameters, cancellationToken); + + public Task> QueryAsync( + string sql, IReadOnlyList? parameters, Func map, + CancellationToken cancellationToken = default) => real.QueryAsync(sql, parameters, map, cancellationToken); + + public Task WriteIntentAsync(PlatformResult intent, CancellationToken cancellationToken = default) => + real.WriteIntentAsync(intent, cancellationToken); + + public Task RedactAuditAsync(AuditRedactionPlan plan, CancellationToken cancellationToken = default) => + real.RedactAuditAsync(plan, cancellationToken); + + public Task WriteResultAsync(PlatformResult result, CancellationToken cancellationToken = default) => + real.WriteResultAsync(result, cancellationToken); + + public Task CommitAsync(CancellationToken cancellationToken = default) => + Task.FromException(new TimeoutException("forced lost commit")); + + public ValueTask DisposeAsync() => real.DisposeAsync(); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureBeginTests.Bounds.cs b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureBeginTests.Bounds.cs new file mode 100644 index 000000000..31c26b421 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureBeginTests.Bounds.cs @@ -0,0 +1,183 @@ +using FluentAssertions; +using LearnStack.Infrastructure.MultiTenancy; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Platform; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// What a closure could never finish is refused by Begin while the person is still Active (ADR-0107 § 7: Closing cannot +/// stick): a person past the closure's bounds (), counted over every participant group served +/// or not and every Membership of any status, and a person whose identity-provider account the port could never delete. +/// Each refusal changes nothing: no refusal code on the request, no User move, no fan-out, and the scope's entry row is the +/// only record. +/// +public sealed partial class AccountClosureBeginTests +{ + /// + /// One group past the bound is refused, served or not (the extra groups are archived branches, which Finalize still + /// fences and redacts); exactly the bound begins and hands every served group to the fan-out in one call. + /// + [Fact] + public async Task A_person_in_more_participant_groups_than_one_closure_is_admitted_for_is_refused_while_still_Active() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var branches = await BranchesAsync(kit, TenantA, ClosureLimits.MaximumParticipantGroups, archived: true); + var past = await PersonInGroupsAsync(kit, branches); + var at = await PersonInGroupsAsync(kit, branches[..^1]); + var removal = new RecordingAccountRemoval(); + var fanOut = new RecordingFanOut(); + + await RefusedTooLargeAsync(kit, past, kit.Owner(fanOut, removal: removal), "one group past the bound"); + fanOut.Calls.Should().BeEmpty("a refused Begin fans nothing out"); + + await ActivateAsync(kit, TenantA, branches); + var begun = await kit.Owner(fanOut, removal: removal).BeginAsync(AccountClosureBeginKit.Admission(), at.Closure); + + begun.Outcome.Should().Be(ClosureBeginOutcome.Begun, "exactly the bound is admitted"); + begun.Groups.Should().Be(new ClosureBeginTally(ClosureLimits.MaximumParticipantGroups, ClosureLimits.MaximumParticipantGroups, 0, 0, 0, 0)); + fanOut.Calls.Should().ContainSingle().Which.Request.Groups.Should().HaveCount(ClosureLimits.MaximumParticipantGroups, + "the fan-out is handed every served group at the bound it accepts"); + (await kit.UserAsync(at.Person)).Status.Should().Be("Closing"); + } + + /// + /// One Membership past the tenant bound, here Revoked tombstones of one group, is refused although the person is in + /// two groups only: a group's fan-out snapshot and a tenant's redaction pass both stop at that bound. Exactly the bound + /// begins. + /// + [Fact] + public async Task A_person_with_more_Memberships_in_one_tenant_than_a_pass_redacts_is_refused_while_still_Active() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var past = await PersonWithTombstonesAsync(kit, ClosureLimits.MaximumTenantMemberships); + var at = await PersonWithTombstonesAsync(kit, ClosureLimits.MaximumTenantMemberships - 1); + var fanOut = new RecordingFanOut(); + + await RefusedTooLargeAsync(kit, past, kit.Owner(fanOut), "one Membership past the tenant bound"); + fanOut.Calls.Should().BeEmpty(); + + var begun = await kit.Owner(fanOut).BeginAsync(AccountClosureBeginKit.Admission(), at.Closure); + + begun.Outcome.Should().Be(ClosureBeginOutcome.Begun, "exactly the tenant bound is admitted"); + begun.Groups!.Served.Should().Be(2); + (await kit.UserAsync(at.Person)).Status.Should().Be("Closing"); + } + + /// + /// A port that could never delete the account (not configured, or refusing the person's subject before any call) refuses + /// the Begin before any fence or write, asked with the raw subject the first read returned and nothing else; once the + /// port accepts, the same closure begins. + /// + [Fact] + public async Task A_closure_whose_account_the_provider_could_never_delete_is_refused_while_still_Active() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + var closure = await kit.ClosureAsync(TenantA, null, person); + var user = await kit.UserAsync(person); + var request = await kit.RequestAsync(closure); + var removal = new RecordingAccountRemoval { Accepts = _ => false }; + var holds = new GatedHolds(); + var fanOut = new RecordingFanOut(); + var admission = AccountClosureBeginKit.Admission(); + + var refused = await kit.Owner(fanOut, holds, removal: removal).BeginAsync(admission, closure); + + refused.Should().Be(new ClosureBeginResult(ClosureBeginOutcome.RefusedProvider, "scheduled")); + removal.Preflights.Should().Equal(["fixture-subject-" + person.ToString("N")], "the port is asked about the raw subject once"); + removal.Subjects.Should().BeEmpty("the preflight deletes nothing"); + holds.Queries.Should().BeEmpty("nothing is judged for a closure that could never finish"); + (await kit.RequestAsync(closure)).Should().Be(request, "no refusal code is recorded: it is not the person's to act on"); + (await kit.UserAsync(person)).Should().Be(user); + fanOut.Calls.Should().BeEmpty(); + (await kit.AuditAsync(admission.Operator.CorrelationId!)).Should().ContainSingle() + .Which.Operation.Should().Be(PlatformAdminScope.EnterOperation, "the refusal writes nothing beyond the entry row"); + + removal.Accepts = _ => true; + (await kit.Owner(fanOut, holds, removal: removal).BeginAsync(AccountClosureBeginKit.Admission(), closure)).Outcome + .Should().Be(ClosureBeginOutcome.Begun, "a Begin after the port is repaired is judged afresh"); + } + + /// A refusal for the closure's size: nothing on the request, the User or the trail but the entry row. + private static async Task RefusedTooLargeAsync( + AccountClosureBeginKit kit, (Guid Person, Guid Closure) past, LearnStack.Modules.Identity.Infrastructure.DataRequests.AccountClosureOperatorOperations owner, + string because) + { + var user = await kit.UserAsync(past.Person); + var request = await kit.RequestAsync(past.Closure); + var admission = AccountClosureBeginKit.Admission(); + + var refused = await owner.BeginAsync(admission, past.Closure); + + refused.Should().Be(new ClosureBeginResult(ClosureBeginOutcome.RefusedTooLarge, "scheduled"), because); + (await kit.RequestAsync(past.Closure)).Should().Be(request, "no refusal code is recorded and the closure stays scheduled"); + (await kit.UserAsync(past.Person)).Should().Be(user, "the person is never moved to a Closing no step could finish"); + (await kit.AuditAsync(admission.Operator.CorrelationId!)).Should().ContainSingle() + .Which.Operation.Should().Be(PlatformAdminScope.EnterOperation, "the refusal writes nothing beyond the entry row"); + (await kit.PlatformAdvisoryLocksAsync()).Should().BeEmpty("the refusal's transaction ended with its scope"); + } + + /// Organizations of a tenant, written by the superuser with the guards paused, as a large franchise has them. + private static async Task BranchesAsync(AccountClosureBeginKit kit, Guid tenant, int count, bool archived) + { + var branches = Enumerable.Range(0, count).Select(_ => Guid.CreateVersion7()).ToArray(); + await kit.SqlAsync($""" + SET session_replication_role = replica; + INSERT INTO public.organizations(id,tenant_id,slug,display_name,status,created_at,created_by,row_version) + SELECT branch, '{tenant}', 'bound-' || replace(branch::text, '-', ''), 'Bound', '{(archived ? "Archived" : "Active")}', + clock_timestamp(), '{UserId.SystemActor.Value}', 0 + FROM unnest(ARRAY[{string.Join(',', branches.Select(branch => $"'{branch}'::uuid"))}]) AS branch; + """); + return branches; + } + + private static Task ActivateAsync(AccountClosureBeginKit kit, Guid tenant, Guid[] branches) => kit.SqlAsync($""" + SET session_replication_role = replica; + UPDATE public.organizations SET status = 'Active' + WHERE tenant_id = '{tenant}' AND id = ANY(ARRAY[{string.Join(',', branches.Select(branch => $"'{branch}'::uuid"))}]); + """); + + /// + /// A person with a learner Membership in tenant A's tenant-wide group, a due closure filed there, and one Membership in + /// each branch, written by the superuser with the guards paused: no product path admits that many groups for a test. + /// + private static async Task<(Guid Person, Guid Closure)> PersonInGroupsAsync(AccountClosureBeginKit kit, Guid[] branches) + { + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + var closure = await kit.ClosureAsync(TenantA, null, person); + await kit.SqlAsync($""" + SET session_replication_role = replica; + INSERT INTO public.memberships(id,tenant_id,organization_id,user_id,status,created_at,created_by) + SELECT uuidv7(), '{TenantA}', branch, '{person}', 'Active', clock_timestamp(), '{UserId.SystemActor.Value}' + FROM unnest(ARRAY[{string.Join(',', branches.Select(branch => $"'{branch}'::uuid"))}]) AS branch; + """); + return (person, closure); + } + + /// + /// A person in two tenant-wide groups, tenant A's (where the due closure is filed) and tenant B's, whose tenant B group + /// also holds Revoked tombstones of earlier admissions, written by the superuser with the guards paused. + /// + private static async Task<(Guid Person, Guid Closure)> PersonWithTombstonesAsync(AccountClosureBeginKit kit, int tombstones) + { + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + await kit.MemberAsync(TenantB, null, person, BuiltInRoleKey.Learner); + var closure = await kit.ClosureAsync(TenantA, null, person); + await kit.SqlAsync($""" + SET session_replication_role = replica; + INSERT INTO public.memberships(id,tenant_id,organization_id,user_id,status,created_at,created_by,deleted_at,deleted_by) + SELECT uuidv7(), '{TenantB}', NULL, '{person}', 'Revoked', clock_timestamp(), '{UserId.SystemActor.Value}', + clock_timestamp(), '{UserId.SystemActor.Value}' + FROM generate_series(1, {tombstones}); + """); + return (person, closure); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureBeginTests.Concurrency.cs b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureBeginTests.Concurrency.cs new file mode 100644 index 000000000..dc6bfb188 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureBeginTests.Concurrency.cs @@ -0,0 +1,188 @@ +using System.Diagnostics; +using FluentAssertions; +using LearnStack.Infrastructure.MultiTenancy; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Platform; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class AccountClosureBeginTests +{ + /// + /// A Membership admission and a revocation for the person race a Begin held at its judgment: both wait on the person's + /// User fence, the Begin commits Closing, then the admission is refused by the database's own Active check and the + /// revocation proceeds. No wait is unbounded and nothing deadlocks. + /// + [Fact] + public async Task A_Membership_write_that_waits_for_a_Begin_meets_a_Closing_person_and_an_admission_is_refused() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + var branch = await kit.MemberAsync(TenantA, SchemaFixture.OrgA1, person, BuiltInRoleKey.Learner); + var closure = await kit.ClosureAsync(TenantA, null, person); + var holds = new GatedHolds(gate: true); + var begin = kit.Owner(holds: holds).BeginAsync(AccountClosureBeginKit.Admission(), closure); + await using var admitting = await DataExportTestKit.OpenAppAsync(kit.Database.AppConnectionString); + await using var revoking = await DataExportTestKit.OpenAppAsync(kit.Database.AppConnectionString); + await using var admission = await admitting.BeginTransactionAsync(); + await using var revocation = await revoking.BeginTransactionAsync(); + Task admitted, revoked; + var watch = Stopwatch.StartNew(); + try + { + await holds.Entered.Task.WaitAsync(TimeSpan.FromSeconds(30)); + await ScopeAsync(admitting, admission, TenantA, SchemaFixture.OrgA2); + admitted = LockAsync(admitting, admission, TenantA, person, exclusive: false); + await kit.WaitUntilALockIsAwaitedAsync("learnstack_app", admitted, "the admission waits on the person's User fence"); + await ScopeAsync(revoking, revocation, TenantA, SchemaFixture.OrgA1); + revoked = LockAsync(revoking, revocation, TenantA, person, exclusive: true); + await WaitUntilBackendsAwaitLocksAsync(kit, "learnstack_app", 2, [admitted, revoked], + "the admission and the revocation wait on the same fence, each on its own backend"); + } + finally + { + holds.Release.TrySetResult(); + } + + (await begin).Outcome.Should().Be(ClosureBeginOutcome.Begun); + await admitted; + var insert = () => InsertMemberAsync(admitting, admission, TenantA, SchemaFixture.OrgA2, Guid.CreateVersion7(), person, + RoleId(TenantA, BuiltInRoleKey.Learner, PermissionScope.Organization)); + var refusal = (await insert.Should().ThrowAsync()).Which; + (refusal.SqlState, refusal.MessageText).Should().Be(("P0302", "identity membership target is unavailable"), + "a Closing person is admitted to nothing"); + await admission.RollbackAsync(); + + await revoked; + await ExecuteAsync(revoking, revocation, """ + UPDATE public.memberships SET status='Revoked', deleted_at=clock_timestamp(), deleted_by=@system, + updated_at=clock_timestamp(), updated_by=@system, row_version=row_version+1 + WHERE id=@member + """, ("member", branch), ("system", UserId.SystemActor.Value)); + await ExecuteAsync(revoking, revocation, "SET CONSTRAINTS ALL IMMEDIATE"); + await revocation.CommitAsync(); + watch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(60), "every wait was bounded and nothing deadlocked"); + (await kit.UserAsync(person)).Status.Should().Be("Closing"); + } + + /// + /// A Membership the person is being admitted to in a new tenant holds the person's User fence when the Begin starts: + /// the Begin waits for it, then reads the participants under the fence, finds the new tenant, fences it too and fans it + /// out. A Begin that read its participants before the fence would leave the new tenant unfenced, and the database would + /// refuse the User's move. + /// + [Fact] + public async Task A_Begin_that_waits_for_an_admission_reads_the_participants_under_the_fence_and_fences_the_new_tenant() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + var closure = await kit.ClosureAsync(TenantA, null, person); + await using var app = await DataExportTestKit.OpenAppAsync(kit.Database.AppConnectionString); + await using var admission = await app.BeginTransactionAsync(); + await ScopeAsync(app, admission, TenantB, null); + await LockAsync(app, admission, TenantB, person, exclusive: false); + await InsertMemberAsync(app, admission, TenantB, null, Guid.CreateVersion7(), person, + RoleId(TenantB, BuiltInRoleKey.Learner, PermissionScope.Tenant)); + await ExecuteAsync(app, admission, "SET CONSTRAINTS ALL IMMEDIATE"); + var fanOut = new RecordingFanOut(); + + var begin = kit.Owner(fanOut).BeginAsync(AccountClosureBeginKit.Admission(), closure); + await kit.WaitUntilALockIsAwaitedAsync("learnstack_platform", begin, "the Begin waits on the person's User fence"); + await admission.CommitAsync(); + + var result = await begin; + result.Outcome.Should().Be(ClosureBeginOutcome.Begun); + result.Groups!.Served.Should().Be(2, "the tenant the person was admitted to while the Begin waited is a participant"); + fanOut.Calls.Single().Request.Groups.Should().Contain(new ClosureParticipantGroup(TenantId.From(TenantB), null)); + } + + /// + /// A tenant key another act holds past the three-second bound fails the Begin as the retryable unavailable, with + /// nothing changed and only the entry row; once the key is free, a repeat begins. + /// + [Fact] + public async Task A_fence_held_past_its_bound_is_the_retryable_unavailable_and_changes_nothing() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + var closure = await kit.ClosureAsync(TenantA, null, person); + var request = await kit.RequestAsync(closure); + var fanOut = new RecordingFanOut(); + await using var app = await DataExportTestKit.OpenAppAsync(kit.Database.AppConnectionString); + await using (var holder = await app.BeginTransactionAsync()) + { + // An ordinary tenant writer holds the tenant key shared; the Begin needs it exclusively. + await ScopeAsync(app, holder, TenantA, null); + await LockAsync(app, holder, TenantA, null, exclusive: false); + var admission = AccountClosureBeginKit.Admission(); + var watch = Stopwatch.StartNew(); + + var act = () => kit.Owner(fanOut).BeginAsync(admission, closure); + + var failure = (await act.Should().ThrowAsync()).Which; + watch.Elapsed.Should().BeGreaterThanOrEqualTo(TimeSpan.FromSeconds(2.5)).And.BeLessThan(TimeSpan.FromSeconds(15), + "the wait is bounded by the transaction's three-second lock timeout"); + failure.CommitOutcomeUnknown.Should().BeFalse(); + failure.InnerException.Should().BeOfType().Which.SqlState.Should().Be("55P03"); + (await kit.AuditAsync(admission.Operator.CorrelationId!)).Should().ContainSingle() + .Which.Operation.Should().Be(PlatformAdminScope.EnterOperation); + await holder.RollbackAsync(); + } + + (await kit.RequestAsync(closure)).Should().Be(request); + (await kit.UserAsync(person)).Status.Should().Be("Active"); + fanOut.Calls.Should().BeEmpty(); + (await kit.Owner(fanOut).BeginAsync(AccountClosureBeginKit.Admission(), closure)).Outcome.Should().Be(ClosureBeginOutcome.Begun); + } + + /// + /// A commit whose answer is lost is the unknown outcome and fans nothing out; the repeat finds the closure as it is. A + /// fan-out that fails a group, or throws, leaves the committed Begin standing and answers it incomplete. + /// + [Fact] + public async Task A_lost_commit_is_the_unknown_outcome_and_a_failed_fan_out_leaves_the_Begin_committed_and_incomplete() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + await kit.MemberAsync(TenantA, SchemaFixture.OrgA1, person, BuiltInRoleKey.Learner); + var closure = await kit.ClosureAsync(TenantA, null, person); + var fanOut = new RecordingFanOut(); + + var lost = () => kit.Owner(fanOut, scope: new LostCommitScope(kit.Scope())).BeginAsync(AccountClosureBeginKit.Admission(), closure); + + var failure = (await lost.Should().ThrowAsync()).Which; + failure.CommitOutcomeUnknown.Should().BeTrue("the commit was sent, so the act may have landed"); + failure.InnerException.Should().BeOfType(); + fanOut.Calls.Should().BeEmpty("a Begin whose commit is unknown fans nothing out"); + (await kit.RequestAsync(closure)).Status.Should().Be("scheduled", "this commit never reached the database"); + + var branch = new ClosureParticipantGroup(TenantId.From(TenantA), OrganizationId.From(SchemaFixture.OrgA1)); + fanOut.Outcome = group => group == branch ? ClosureGroupOutcome.Failed : ClosureGroupOutcome.Started; + var partial = await kit.Owner(fanOut).BeginAsync(AccountClosureBeginKit.Admission(), closure); + + partial.Should().Be(new ClosureBeginResult(ClosureBeginOutcome.Begun, "fulfilling", Groups: new ClosureBeginTally(2, 1, 0, 0, 1, 0))); + partial.Groups!.Complete.Should().BeFalse("a failed group is owed a repeat"); + (await kit.RequestAsync(closure)).Status.Should().Be("fulfilling", "the Begin committed before the fan-out"); + (await kit.UserAsync(person)).Status.Should().Be("Closing"); + + fanOut.Failure = new InvalidOperationException("forced fan-out defect"); + var thrown = await kit.Owner(fanOut).BeginAsync(AccountClosureBeginKit.Admission(), closure); + thrown.Should().Be(new ClosureBeginResult(ClosureBeginOutcome.Resumed, "fulfilling", Groups: new ClosureBeginTally(2, 0, 0, 0, 2, 0)), + "a fan-out that throws reports every group failed, and the closure stands"); + + fanOut.Failure = null; + fanOut.Outcome = group => group == branch ? ClosureGroupOutcome.Waiting : ClosureGroupOutcome.Adopted; + var waiting = await kit.Owner(fanOut).BeginAsync(AccountClosureBeginKit.Admission(), closure); + waiting.Groups.Should().Be(new ClosureBeginTally(2, 0, 1, 1, 0, 0)); + waiting.Groups!.Complete.Should().BeFalse("a waiting group is owed a repeat"); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureBeginTests.Coverage.cs b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureBeginTests.Coverage.cs new file mode 100644 index 000000000..42a47f76c --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureBeginTests.Coverage.cs @@ -0,0 +1,362 @@ +using FluentAssertions; +using LearnStack.Infrastructure.MultiTenancy; +using LearnStack.Modules.Identity.Infrastructure.DataRequests; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Platform; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The Begin's branches the first suites left unreached: what the act finds after its fences were granted (a closure +/// cancelled, a second operator's Begin, a person closed while it waited), a fulfilling closure whose person is not +/// Closing, the order of the judgment with two refusals standing, a commit that landed and whose answer was lost, and every +/// way the fan-out's answer can be malformed or end. +/// +public sealed partial class AccountClosureBeginTests +{ + /// + /// Waits, from pg_locks, until at least distinct backends of the role in this database wait + /// on a lock, while none of the contenders has finished: a wait observed in the server, never a pause of the test. + /// + private static async Task WaitUntilBackendsAwaitLocksAsync( + AccountClosureBeginKit kit, string role, int count, Task[] contenders, string because) + { + await using var observer = await AccountClosureBeginKit.OpenAsync(kit.Database.PlatformConnectionString); + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(30); + while (true) + { + contenders.Should().OnlyContain(contender => !contender.IsCompleted, because); + await using var command = new Npgsql.NpgsqlCommand( + "SELECT count(DISTINCT l.pid) FROM pg_catalog.pg_locks l JOIN pg_catalog.pg_stat_activity a ON a.pid = l.pid " + + "WHERE a.datname = current_database() AND a.usename = @role AND NOT l.granted", observer); + command.Parameters.AddWithValue("role", role); + if ((long)(await command.ExecuteScalarAsync())! >= count) return; + DateTime.UtcNow.Should().BeBefore(deadline, because); + await Task.Delay(TimeSpan.FromMilliseconds(20)); + } + } + + // Built from the fixture's constants: static fields of the other parts of this class may not be assigned yet. + private static readonly ClosureParticipantGroup WideA = new(TenantId.From(SchemaFixture.TenantA), null); + private static readonly ClosureParticipantGroup BranchA1 = new(TenantId.From(SchemaFixture.TenantA), OrganizationId.From(SchemaFixture.OrgA1)); + + /// + /// The request is read before the fences and again, locked, under them: a closure the person cancelled while the act + /// waited for the person's User fence is not begun. Nothing moves, nothing is fanned out, and the entry row is the only + /// record. + /// + [Fact] + public async Task A_closure_the_person_cancelled_while_the_Begin_waited_for_the_fences_is_not_begun() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + var closure = await kit.ClosureAsync(TenantA, null, person); + var userBefore = await kit.UserAsync(person); + var requestBefore = await kit.RequestAsync(closure); + var fanOut = new RecordingFanOut(); + var admission = AccountClosureBeginKit.Admission(); + await using var app = await DataExportTestKit.OpenAppAsync(kit.Database.AppConnectionString); + await using var cancelling = await app.BeginTransactionAsync(); + await DataRequestSchemaSeed.FenceAsync(app, cancelling, TenantA, null, person); + + var begin = kit.Owner(fanOut).BeginAsync(admission, closure); + await kit.WaitUntilALockIsAwaitedAsync("learnstack_platform", begin, "the Begin waits for the person's User fence"); + await DataRequestSchemaSeed.StepAsync(app, cancelling, closure, "status='cancelled'"); + await cancelling.CommitAsync(); + + (await begin).Should().Be(new ClosureBeginResult(ClosureBeginOutcome.NotBeginnable, "cancelled")); + (await kit.RequestAsync(closure)).Should().Be(requestBefore with { Status = "cancelled", Version = requestBefore.Version + 1 }, + "only the person's cancellation wrote the request"); + (await kit.UserAsync(person)).Should().Be(userBefore, "a closure that cannot begin never moves the person"); + fanOut.Calls.Should().BeEmpty(); + (await kit.AuditAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should() + .Equal([PlatformAdminScope.EnterOperation], "a refusal that changes nothing ends by disposal"); + (await kit.ResultRowsAsync(closure)).Should().Be(0); + } + + /// + /// Two operators begin the same closure. The second waits for the first's fences; when the first commits, the second + /// reads the closure fulfilling, writes nothing, and only fans out again. The request is stepped once, the User moved + /// once, and one result row exists. + /// + [Fact] + public async Task A_second_operator_s_Begin_that_waited_for_the_first_resumes_without_a_write() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + var closure = await kit.ClosureAsync(TenantA, null, person); + var userBefore = await kit.UserAsync(person); + var requestBefore = await kit.RequestAsync(closure); + var holds = new GatedHolds(gate: true); + var firstFanOut = new RecordingFanOut(); + var secondFanOut = new RecordingFanOut { Outcome = _ => ClosureGroupOutcome.Adopted }; + var secondAdmission = AccountClosureBeginKit.Admission("INC-702"); + + var first = kit.Owner(firstFanOut, holds).BeginAsync(AccountClosureBeginKit.Admission("INC-701"), closure); + Task? second = null; + try + { + await holds.Entered.Task.WaitAsync(TimeSpan.FromSeconds(30)); + second = kit.Owner(secondFanOut).BeginAsync(secondAdmission, closure); + await kit.WaitUntilALockIsAwaitedAsync("learnstack_platform", second, "the second Begin waits for the first's fences"); + } + finally + { + holds.Release.TrySetResult(); + } + + (await first).Outcome.Should().Be(ClosureBeginOutcome.Begun); + (await second!).Should().Be(new ClosureBeginResult( + ClosureBeginOutcome.Resumed, "fulfilling", Groups: new ClosureBeginTally(1, 0, 1, 0, 0, 0)), + "the closure began while the second waited, so it is not judged or written again"); + (await kit.RequestAsync(closure)).Should().Be(requestBefore with { Status = "fulfilling", Version = requestBefore.Version + 1 }); + (await kit.UserAsync(person)).Should().Be(userBefore with { Status = "Closing", Version = userBefore.Version + 1 }); + (await kit.ResultRowsAsync(closure)).Should().Be(1, "only the Begin that wrote has a result row"); + (await kit.AuditAsync(secondAdmission.Operator.CorrelationId!)).Select(row => row.Operation).Should() + .Equal([PlatformAdminScope.EnterOperation]); + secondFanOut.Calls.Should().ContainSingle().Which.Request.Groups.Should().Equal(WideA); + } + + /// + /// A person another closure's Finalize closed while this Begin waited for the fences is not admitted: the act reads the + /// status again under the fences and ends with nothing written, the closure still scheduled. + /// + [Fact] + public async Task A_person_closed_while_the_Begin_waited_for_the_fences_is_not_admitted() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + await kit.MemberAsync(TenantA, SchemaFixture.OrgA1, person, BuiltInRoleKey.Learner); + var first = await kit.ClosureAsync(TenantA, null, person); + var second = await kit.ClosureAsync(TenantA, SchemaFixture.OrgA1, person); + var fanOut = new RecordingFanOut(); + (await kit.Owner(fanOut).BeginAsync(AccountClosureBeginKit.Admission(), first)).Outcome.Should().Be(ClosureBeginOutcome.Begun); + var requestBefore = await kit.RequestAsync(second); + var admission = AccountClosureBeginKit.Admission(); + await using var platform = await AccountClosureBeginKit.OpenAsync(kit.Database.PlatformConnectionString); + await using var closing = await platform.BeginTransactionAsync(); + await IdentityMembershipFixture.ExecuteAsync(platform, closing, "SELECT pg_catalog.pg_advisory_xact_lock(@key)", + ("key", AccountClosureBeginKit.UserKey(person))); + await IdentityMembershipFixture.ExecuteAsync(platform, closing, "SELECT pg_catalog.pg_advisory_xact_lock(@key)", + ("key", AccountClosureBeginKit.TenantKey(TenantA))); + + var begin = kit.Owner(fanOut).BeginAsync(admission, second); + await kit.WaitUntilALockIsAwaitedAsync("learnstack_platform", begin, "the Begin waits for the person's User fence"); + await IdentityMembershipFixture.ExecuteAsync(platform, closing, + "UPDATE public.users SET status='Closed', provider_subject=NULL WHERE id=@user", ("user", person)); + await closing.CommitAsync(); + + (await begin).Should().Be(new ClosureBeginResult(ClosureBeginOutcome.SubjectNotAdmitted, "scheduled")); + (await kit.RequestAsync(second)).Should().Be(requestBefore, "the closure of a Closed person stays scheduled and untouched"); + (await kit.UserAsync(person)).Status.Should().Be("Closed"); + fanOut.Calls.Should().ContainSingle("only the first closure's Begin fanned out"); + (await kit.AuditAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should() + .Equal([PlatformAdminScope.EnterOperation]); + } + + /// + /// A closure already fulfilling whose person is not Closing is a state no admitted path writes: the act is abandoned + /// with a plain failure that does not name the person, nothing is fanned out and nothing is written. + /// + [Fact] + public async Task A_fulfilling_closure_whose_person_is_not_Closing_is_a_defect_and_changes_nothing() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + var closure = await kit.RequestRowAsync(TenantA, person, "closure", "fulfilling"); + var requestBefore = await kit.RequestAsync(closure); + var fanOut = new RecordingFanOut(); + var admission = AccountClosureBeginKit.Admission(); + + var act = () => kit.Owner(fanOut).BeginAsync(admission, closure); + + var failure = (await act.Should().ThrowAsync()).Which; + failure.Message.Should().Contain("not Closing").And.NotContain(person.ToString("D")); + fanOut.Calls.Should().BeEmpty("a defect fans nothing out"); + (await kit.RequestAsync(closure)).Should().Be(requestBefore); + (await kit.UserAsync(person)).Status.Should().Be("Active"); + (await kit.AuditAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should() + .Equal([PlatformAdminScope.EnterOperation]); + } + + /// + /// The judgment's order is the ADR's: the window, then the hold, then the last administrator, and the first refusal + /// stands. Each case here has every refusal below the expected one standing as well, so a swapped order answers + /// differently. + /// + [Fact] + public async Task The_judgment_answers_the_window_before_the_hold_before_the_last_administrator() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var administrator = await kit.PersonAsync(); + await kit.MemberAsync(TenantB, null, administrator, BuiltInRoleKey.Learner); + await kit.MemberAsync(TenantA, null, administrator, BuiltInRoleKey.TenantAdmin); + // The seeded administrator of tenant A leaves, so the person is the only eligible one: the third refusal stands always. + await RevokeAsync(kit, TenantA, null, IdentityMembershipFixture.AdminA, IdentityMembershipFixture.AdminMembershipA); + var due = await kit.ClosureAsync(TenantB, null, administrator); + var inWindow = await kit.ClosureAsync(TenantA, null, administrator, due: false); + var fanOut = new RecordingFanOut(); + + // Due, held and the last administrator: the hold answers. + var held = new GatedHolds(hold: true); + (await kit.Owner(fanOut, held).BeginAsync(AccountClosureBeginKit.Admission(), due)) + .Should().Be(new ClosureBeginResult(ClosureBeginOutcome.RefusedHold, "scheduled", "blocked_hold")); + held.Queries.Should().ContainSingle(); + + // In its window and the last administrator: the window answers, the hold source is never asked. + var quiet = new GatedHolds(); + (await kit.Owner(fanOut, quiet).BeginAsync(AccountClosureBeginKit.Admission(), inWindow)) + .Should().Be(new ClosureBeginResult(ClosureBeginOutcome.RefusedWindow, "scheduled", "blocked_window")); + quiet.Queries.Should().BeEmpty("the window is judged before the hold source is asked"); + + // In its window, held and the last administrator: the window still answers. + var everything = new GatedHolds(hold: true); + (await kit.Owner(fanOut, everything).BeginAsync(AccountClosureBeginKit.Admission(), inWindow)) + .Should().Be(new ClosureBeginResult(ClosureBeginOutcome.RefusedWindow, "scheduled", "blocked_window")); + everything.Queries.Should().BeEmpty(); + + (await kit.RequestAsync(due)).LastRefusal.Should().Be("blocked_hold"); + (await kit.RequestAsync(inWindow)).LastRefusal.Should().Be("blocked_window"); + (await kit.UserAsync(administrator)).Status.Should().Be("Active"); + fanOut.Calls.Should().BeEmpty(); + } + + /// + /// A commit that landed and whose answer was lost is the unknown outcome all the same: nothing is fanned out, the closure + /// is fulfilling and its person Closing as the commit left them, and the repeat finds that and resumes. + /// + [Fact] + public async Task A_commit_that_landed_and_whose_answer_was_lost_is_the_unknown_outcome_and_a_repeat_resumes() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + var closure = await kit.ClosureAsync(TenantA, null, person); + var fanOut = new RecordingFanOut(); + var landed = new TappedScope(kit.Scope()) { AfterCommit = () => Task.FromException(new TimeoutException("forced lost answer after the commit landed")) }; + + var lost = () => kit.Owner(fanOut, scope: landed).BeginAsync(AccountClosureBeginKit.Admission(), closure); + + var failure = (await lost.Should().ThrowAsync()).Which; + failure.CommitOutcomeUnknown.Should().BeTrue("the commit was sent, so the act may have landed, and here it did"); + failure.InnerException.Should().BeOfType(); + fanOut.Calls.Should().BeEmpty("a Begin whose commit is unknown fans nothing out"); + (await kit.RequestAsync(closure)).Status.Should().Be("fulfilling", "this commit reached the database"); + (await kit.UserAsync(person)).Status.Should().Be("Closing"); + + fanOut.Outcome = _ => ClosureGroupOutcome.Adopted; + var repeat = await kit.Owner(fanOut).BeginAsync(AccountClosureBeginKit.Admission(), closure); + + repeat.Should().Be(new ClosureBeginResult(ClosureBeginOutcome.Resumed, "fulfilling", Groups: new ClosureBeginTally(1, 0, 1, 0, 0, 0))); + (await kit.ResultRowsAsync(closure)).Should().Be(1, "the repeat wrote nothing"); + } + + /// + /// A fan-out that answers badly is counted by what it reported, never by what it claimed: a group nobody handed over, + /// a second report of a group, an element that is null and an outcome outside the closed set change no served group's + /// count, and a group not reported as started, adopted or waiting is failed. + /// + [Fact] + public async Task A_malformed_fan_out_answer_is_counted_only_for_the_served_groups_and_the_first_report_of_a_group_stands() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + await kit.MemberAsync(TenantA, SchemaFixture.OrgA1, person, BuiltInRoleKey.Learner); + var closure = await kit.ClosureAsync(TenantA, null, person); + var notHandedOver = new ClosureParticipantGroup(TenantId.From(SchemaFixture.TenantB), null); + var logs = new CapturingLogger(); + var fanOut = new ScriptedFanOut((_, _) => Task.FromResult?>(new ClosureGroupReport[] + { + new(WideA, ClosureGroupOutcome.Started), + new(WideA, ClosureGroupOutcome.Failed), + null!, + new(BranchA1, (ClosureGroupOutcome)99), + new(notHandedOver, ClosureGroupOutcome.Started), + })); + + var result = await kit.Owner(fanOut, logger: logs).BeginAsync(AccountClosureBeginKit.Admission(), closure); + + result.Groups.Should().Be(new ClosureBeginTally(Served: 2, Started: 1, Adopted: 0, Waiting: 0, Failed: 1, Unserved: 0), + "the first report of the tenant-wide group stands, the undefined outcome and the unrequested group count for nothing"); + result.Groups!.Complete.Should().BeFalse(); + fanOut.Calls.Should().ContainSingle().Which.Groups.Should().BeEquivalentTo([WideA, BranchA1]); + logs.Lines.Should().BeEmpty("a malformed answer is not an exception"); + (await kit.UserAsync(person)).Status.Should().Be("Closing", "the committed Begin stands"); + } + + /// A fan-out that answers no list at all fails every served group and is not an exception. + [Fact] + public async Task A_fan_out_that_answers_no_list_fails_every_served_group_without_a_log_line() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + var closure = await kit.ClosureAsync(TenantA, null, person); + var logs = new CapturingLogger(); + var fanOut = new ScriptedFanOut((_, _) => Task.FromResult?>(null)); + + var result = await kit.Owner(fanOut, logger: logs).BeginAsync(AccountClosureBeginKit.Admission(), closure); + + result.Groups.Should().Be(new ClosureBeginTally(1, 0, 0, 0, 1, 0)); + logs.Lines.Should().BeEmpty(); + } + + /// + /// A fan-out that throws, and a cancellation that is not the caller's, fail every served group, log the closed + /// fan-out failure once and never name the person; the committed Begin stands and a repeat retries. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task A_fan_out_that_throws_is_logged_once_by_its_closed_event_and_fails_every_served_group(bool cancellation) + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + var closure = await kit.ClosureAsync(TenantA, null, person); + var logs = new CapturingLogger(); + var fanOut = new ScriptedFanOut((_, _) => cancellation + ? Task.FromException?>(new OperationCanceledException("a timeout of the fan-out's own")) + : Task.FromException?>(new InvalidOperationException("forced fan-out defect"))); + + var result = await kit.Owner(fanOut, logger: logs).BeginAsync(AccountClosureBeginKit.Admission(), closure); + + result.Should().Be(new ClosureBeginResult(ClosureBeginOutcome.Begun, "fulfilling", Groups: new ClosureBeginTally(1, 0, 0, 0, 1, 0))); + logs.Lines.Should().ContainSingle().Which.Should().StartWith("7120 Error ").And.NotContain(person.ToString("D")); + } + + /// + /// The operator's own cancellation during the fan-out is theirs to see: it propagates, the log carries no fan-out failure, + /// and the Begin that committed before it stands. + /// + [Fact] + public async Task The_operator_s_cancellation_during_the_fan_out_propagates_and_the_committed_Begin_stands() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + var closure = await kit.ClosureAsync(TenantA, null, person); + var logs = new CapturingLogger(); + using var operatorLeaves = new CancellationTokenSource(); + var fanOut = new ScriptedFanOut((_, token) => + { + operatorLeaves.Cancel(); + token.ThrowIfCancellationRequested(); + return Task.FromResult?>([]); + }); + + var act = () => kit.Owner(fanOut, logger: logs).BeginAsync(AccountClosureBeginKit.Admission(), closure, operatorLeaves.Token); + + await act.Should().ThrowAsync(); + logs.Lines.Should().BeEmpty("the operator's cancellation is not a fan-out failure"); + (await kit.RequestAsync(closure)).Status.Should().Be("fulfilling", "the Begin committed before the fan-out"); + (await kit.UserAsync(person)).Status.Should().Be("Closing"); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureBeginTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureBeginTests.cs new file mode 100644 index 000000000..ba0fd5175 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureBeginTests.cs @@ -0,0 +1,333 @@ +using System.Text.Json; +using FluentAssertions; +using LearnStack.Infrastructure.MultiTenancy; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Platform; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The closure's Begin owner (ADR-0107 § 7) against a real database, the real platform scope, the real audit store, the real +/// Tenancy lifecycle read and the request guard's and the users trigger's closure arms. The fan-out and the hold +/// source are recording stand-ins: the fan-out's own act is proven by its own suite, and a hold source has no production +/// implementation yet. Every statement under test runs as learnstack_platform through the scope. +/// +/// +/// Each test runs in its own disposable copy of the seeded schema and closes fresh persons, because a User a closure moved +/// never returns to Active. +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed partial class AccountClosureBeginTests(SchemaFixture schema) +{ + private static readonly Guid TenantA = SchemaFixture.TenantA; + private static readonly Guid TenantB = SchemaFixture.TenantB; + + /// + /// A person in two tenants and four groups: tenant A's tenant-wide group and two branches, one of them archived, and + /// tenant B's tenant-wide group in a suspended tenant. One transaction fences, judges and moves the User and the request + /// and writes the sentinel result row; only then, with the fences released, the two served groups are fanned out. + /// + [Fact] + public async Task A_Begin_moves_the_person_and_the_request_records_it_under_the_sentinel_and_then_fans_out_the_served_groups() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + await kit.MemberAsync(TenantA, SchemaFixture.OrgA1, person, BuiltInRoleKey.Learner); + await kit.MemberAsync(TenantA, SchemaFixture.OrgA2, person, BuiltInRoleKey.Learner); + await kit.MemberAsync(TenantB, null, person, BuiltInRoleKey.Learner); + var closure = await kit.ClosureAsync(TenantA, null, person); + await kit.OrganizationStatusAsync(TenantA, SchemaFixture.OrgA2, "Archived"); + await kit.TenantStatusAsync(TenantB, "Suspended"); + var userBefore = await kit.UserAsync(person); + var requestBefore = await kit.RequestAsync(closure); + var fanOut = new RecordingFanOut(); + fanOut.Probe = async () => + { + // What the fan-out meets: the Begin committed and its fences ended with it. + (await kit.UserAsync(person)).Status.Should().Be("Closing", "the fan-out runs after the Begin committed"); + (await kit.RequestAsync(closure)).Status.Should().Be("fulfilling"); + (await kit.PlatformAdvisoryLocksAsync()).Should().BeEmpty("no platform connection still holds a fence"); + }; + var admission = AccountClosureBeginKit.Admission("INC-701"); + + var result = await kit.Owner(fanOut).BeginAsync(admission, closure); + + result.Outcome.Should().Be(ClosureBeginOutcome.Begun); + result.Status.Should().Be("fulfilling"); + result.Groups.Should().Be(new ClosureBeginTally(Served: 2, Started: 2, Adopted: 0, Waiting: 0, Failed: 0, Unserved: 2)); + result.Groups!.Complete.Should().BeTrue(); + + var call = fanOut.Calls.Should().ContainSingle().Which; + call.Request.SubjectUserId.Value.Should().Be(person); + call.Request.Groups.Should().BeEquivalentTo(new[] + { + new ClosureParticipantGroup(TenantId.From(TenantA), null), + new ClosureParticipantGroup(TenantId.From(TenantA), OrganizationId.From(SchemaFixture.OrgA1)), + }, "an archived branch and a suspended tenant are unserved and are not fanned out"); + call.Operator.Should().BeSameAs(admission.Operator, "each group's act is admitted for the same operator"); + call.Ticket.Should().Be("INC-701"); + + var user = await kit.UserAsync(person); + user.Should().Be(userBefore with { Status = "Closing", Version = userBefore.Version + 1 }, + "Active to Closing keeps the raw subject until Finalize"); + (await kit.RequestAsync(closure)).Should().Be(requestBefore with { Status = "fulfilling", Version = requestBefore.Version + 1 }); + + var rows = await kit.AuditAsync(admission.Operator.CorrelationId!); + rows.Should().HaveCount(2, "the scope's entry row and one result row"); + var entry = rows.Single(row => row.Operation == PlatformAdminScope.EnterOperation); + (entry.Tenant, entry.Reason).Should().Be((TenantId.PlatformSentinel.Value, "closure_begin")); + var recorded = rows.Single(row => row.Operation == "platform.closure.begin"); + (recorded.Tenant, recorded.Module, recorded.Reason, recorded.Actor, recorded.EntityType, recorded.EntityId).Should().Be( + (TenantId.PlatformSentinel.Value, "platform", "closure_begin", (Guid?)null, "DataSubjectRequest", closure.ToString("D"))); + recorded.Metadata.Should().Contain("INC-701", "a sentinel row no tenant reads carries the ticket"); + SameJson(recorded.Before, """{"status":"scheduled","account":"active"}"""); + SameJson(recorded.After, """{"status":"fulfilling","account":"closing","served_groups":2,"unserved_groups":2}"""); + foreach (var row in rows) + { + (row.Before + row.After).Should().NotContain(person.ToString("D"), "no state names the person"); + } + } + + /// + /// While a Begin is held at its judgment, its backend holds the person's User key and the key of every participant + /// tenant, the Revoked tombstone's tenant included, exclusively and as nothing else; they end with its commit. + /// + [Fact] + public async Task The_fences_are_the_User_key_and_every_participant_tenant_key_held_exclusively_until_the_commit() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, SchemaFixture.OrgA1, person, BuiltInRoleKey.Learner); + var tombstone = await kit.MemberAsync(TenantB, null, person, BuiltInRoleKey.Learner); + await RevokeAsync(kit, TenantB, null, person, tombstone); + var closure = await kit.ClosureAsync(TenantA, SchemaFixture.OrgA1, person); + var holds = new GatedHolds(gate: true); + + var begin = kit.Owner(holds: holds).BeginAsync(AccountClosureBeginKit.Admission(), closure); + try + { + await holds.Entered.Task.WaitAsync(TimeSpan.FromSeconds(30)); + (await kit.PlatformAdvisoryLocksAsync()).Should().BeEquivalentTo(new[] + { + (AccountClosureBeginKit.UserKey(person), "ExclusiveLock"), + (AccountClosureBeginKit.TenantKey(TenantA), "ExclusiveLock"), + (AccountClosureBeginKit.TenantKey(TenantB), "ExclusiveLock"), + }, "the User key and both participant tenants' keys, the tombstone's tenant included, and nothing else"); + } + finally + { + holds.Release.TrySetResult(); + } + + (await begin).Outcome.Should().Be(ClosureBeginOutcome.Begun); + (await kit.PlatformAdvisoryLocksAsync()).Should().BeEmpty("transaction-scoped keys end at the commit"); + holds.Queries.Should().ContainSingle().Which.Should().Match(query => + query.Kind == DataRequestKind.Closure && query.SubjectUserId == UserId.From(person) + && query.Group.TenantId == TenantId.From(TenantA) && query.Group.OrganizationId == OrganizationId.From(SchemaFixture.OrgA1)); + } + + /// + /// A closure in its window is refused blocked_window by the database clock: the code is recorded on the request + /// with a result row, and the User is untouched. Refused again for the same reason, nothing changes and no second row is + /// written; refused for a hold, the code is replaced with a row of its own. + /// + [Fact] + public async Task A_refusal_is_recorded_on_the_request_once_per_code_and_changes_nothing_else() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + var closure = await kit.ClosureAsync(TenantA, null, person, due: false); + var user = await kit.UserAsync(person); + var fanOut = new RecordingFanOut(); + var request = await kit.RequestAsync(closure); + + var first = AccountClosureBeginKit.Admission("INC-702"); + var window = await kit.Owner(fanOut).BeginAsync(first, closure); + + window.Should().Be(new ClosureBeginResult(ClosureBeginOutcome.RefusedWindow, "scheduled", "blocked_window")); + (await kit.RequestAsync(closure)).Should().Be(request with { LastRefusal = "blocked_window", Version = request.Version + 1 }); + var recorded = (await kit.AuditAsync(first.Operator.CorrelationId!)).Single(row => row.Operation == "platform.closure.begin"); + (recorded.Tenant, recorded.EntityId).Should().Be((TenantId.PlatformSentinel.Value, closure.ToString("D"))); + SameJson(recorded.Before, """{"status":"scheduled","last_refusal":null}"""); + SameJson(recorded.After, """{"status":"scheduled","last_refusal":"blocked_window"}"""); + + var repeat = AccountClosureBeginKit.Admission(); + (await kit.Owner(fanOut).BeginAsync(repeat, closure)).Outcome.Should().Be(ClosureBeginOutcome.RefusedWindow); + (await kit.RequestAsync(closure)).Version.Should().Be(request.Version + 1, "the standing code is not recorded again"); + (await kit.AuditAsync(repeat.Operator.CorrelationId!)).Should().ContainSingle() + .Which.Operation.Should().Be(PlatformAdminScope.EnterOperation, "a refusal that changes nothing ends by disposal"); + + await kit.BackdateAsync(closure, TenantA, null); + var held = new GatedHolds(hold: true); + (await kit.Owner(fanOut, held).BeginAsync(AccountClosureBeginKit.Admission(), closure)) + .Should().Be(new ClosureBeginResult(ClosureBeginOutcome.RefusedHold, "scheduled", "blocked_hold")); + (await kit.RequestAsync(closure)).Should().Be(request with { LastRefusal = "blocked_hold", Version = request.Version + 2 }); + (await kit.ResultRowsAsync(closure)).Should().Be(2, "each recorded refusal has its own row"); + + (await kit.UserAsync(person)).Should().Be(user, "a refusal never moves the User"); + fanOut.Calls.Should().BeEmpty("a refused Begin fans nothing out"); + } + + /// + /// The person is the sole eligible administrator of tenant A and a learner of tenant B, which has its own + /// administrator: refused blocked_last_administrator. Tenant A suspended, it does not allow ordinary work and is + /// not judged, so the same Begin succeeds with tenant A unserved. + /// + [Fact] + public async Task The_sole_administrator_of_an_operable_tenant_is_refused_and_a_tenant_that_allows_no_work_is_not_judged() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var administrator = await kit.PersonAsync(); + await kit.MemberAsync(TenantB, null, administrator, BuiltInRoleKey.Learner); + await kit.MemberAsync(TenantA, null, administrator, BuiltInRoleKey.TenantAdmin); + // The seeded administrator of tenant A leaves, so the person is its only eligible one. + await RevokeAsync(kit, TenantA, null, IdentityMembershipFixture.AdminA, IdentityMembershipFixture.AdminMembershipA); + var closure = await kit.ClosureAsync(TenantB, null, administrator); + var fanOut = new RecordingFanOut(); + + (await kit.Owner(fanOut).BeginAsync(AccountClosureBeginKit.Admission(), closure)) + .Should().Be(new ClosureBeginResult(ClosureBeginOutcome.RefusedLastAdministrator, "scheduled", "blocked_last_administrator")); + (await kit.RequestAsync(closure)).LastRefusal.Should().Be("blocked_last_administrator"); + (await kit.UserAsync(administrator)).Status.Should().Be("Active"); + + await kit.TenantStatusAsync(TenantA, "Suspended"); + var begun = await kit.Owner(fanOut).BeginAsync(AccountClosureBeginKit.Admission(), closure); + + begun.Outcome.Should().Be(ClosureBeginOutcome.Begun, "a suspended tenant has no ordinary work to protect"); + begun.Groups.Should().Be(new ClosureBeginTally(1, 1, 0, 0, 0, 1)); + fanOut.Calls.Should().ContainSingle().Which.Request.Groups.Should().Equal(new ClosureParticipantGroup(TenantId.From(TenantB), null)); + (await kit.UserAsync(administrator)).Status.Should().Be("Closing"); + } + + /// + /// A repeat on a closure that began fences nothing, judges nothing and writes nothing but its entry row, and fans out + /// again; a second closure of the same Closing person begins with the User left as it is. + /// + [Fact] + public async Task A_repeat_resumes_without_a_write_and_a_second_closure_of_a_closing_person_begins_without_moving_the_User() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + await kit.MemberAsync(TenantA, SchemaFixture.OrgA1, person, BuiltInRoleKey.Learner); + var closure = await kit.ClosureAsync(TenantA, null, person); + var second = await kit.ClosureAsync(TenantA, SchemaFixture.OrgA1, person); + var fanOut = new RecordingFanOut(); + (await kit.Owner(fanOut).BeginAsync(AccountClosureBeginKit.Admission(), closure)).Outcome.Should().Be(ClosureBeginOutcome.Begun); + var user = await kit.UserAsync(person); + var request = await kit.RequestAsync(closure); + + var repeat = AccountClosureBeginKit.Admission(); + fanOut.Outcome = _ => ClosureGroupOutcome.Adopted; + var resumed = await kit.Owner(fanOut, new GatedHolds(hold: true)).BeginAsync(repeat, closure); + + resumed.Should().Be(new ClosureBeginResult( + ClosureBeginOutcome.Resumed, "fulfilling", Groups: new ClosureBeginTally(2, 0, 2, 0, 0, 0)), + "a closure that began is not judged again, so a hold that appears later does not stop its fan-out"); + (await kit.RequestAsync(closure)).Should().Be(request); + (await kit.UserAsync(person)).Should().Be(user); + (await kit.AuditAsync(repeat.Operator.CorrelationId!)).Should().ContainSingle() + .Which.Operation.Should().Be(PlatformAdminScope.EnterOperation, "a resume writes nothing, so its entry row is its record"); + fanOut.Calls.Should().HaveCount(2).And.OnlyContain(call => call.Request.Groups.Count == 2); + + var joined = AccountClosureBeginKit.Admission(); + fanOut.Outcome = _ => ClosureGroupOutcome.Adopted; + (await kit.Owner(fanOut).BeginAsync(joined, second)).Should().Be(new ClosureBeginResult( + ClosureBeginOutcome.Resumed, "fulfilling", Groups: new ClosureBeginTally(2, 0, 2, 0, 0, 0))); + (await kit.RequestAsync(second)).Status.Should().Be("fulfilling"); + (await kit.UserAsync(person)).Should().Be(user, "the User is already Closing for the first closure"); + var row = (await kit.AuditAsync(joined.Operator.CorrelationId!)).Single(entry => entry.Operation == "platform.closure.begin"); + JsonDocument.Parse(row.Before).RootElement.GetProperty("account").GetString().Should().Be("closing"); + } + + /// + /// What cannot begin is refused and changes nothing: a missing request, an export and an erasure, a completed and a + /// cancelled closure, and a closure whose person is already Closed. + /// + [Fact] + public async Task What_cannot_begin_is_refused_with_its_reason_and_only_the_entry_row_records_it() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + var fanOut = new RecordingFanOut(); + var owner = kit.Owner(fanOut); + var cases = new List<(Guid Request, ClosureBeginOutcome Outcome, string? Status)> + { + (Guid.CreateVersion7(), ClosureBeginOutcome.NotFound, null), + (await kit.RequestRowAsync(TenantA, person, "export", "completed"), ClosureBeginOutcome.NotClosure, "completed"), + (await kit.RequestRowAsync(TenantA, person, "erasure", "scheduled"), ClosureBeginOutcome.NotClosure, "scheduled"), + (await kit.RequestRowAsync(TenantA, person, "closure", "completed"), ClosureBeginOutcome.NotBeginnable, "completed"), + (await kit.RequestRowAsync(TenantA, person, "closure", "cancelled"), ClosureBeginOutcome.NotBeginnable, "cancelled"), + }; + + foreach (var (request, outcome, status) in cases) + { + var admission = AccountClosureBeginKit.Admission(); + var result = await owner.BeginAsync(admission, request); + + (result.Outcome, result.Status).Should().Be((outcome, status), outcome.ToString()); + (await kit.AuditAsync(admission.Operator.CorrelationId!)).Should().ContainSingle(outcome.ToString()) + .Which.Operation.Should().Be(PlatformAdminScope.EnterOperation); + } + + (await kit.UserAsync(person)).Status.Should().Be("Active", "nothing above moved the person"); + + // A person Closed by a finished closure: a closure of theirs left scheduled can never begin. + var closed = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, closed, BuiltInRoleKey.Learner); + await kit.MemberAsync(TenantA, SchemaFixture.OrgA1, closed, BuiltInRoleKey.Learner); + var first = await kit.ClosureAsync(TenantA, null, closed); + var left = await kit.ClosureAsync(TenantA, SchemaFixture.OrgA1, closed); + (await owner.BeginAsync(AccountClosureBeginKit.Admission(), first)).Outcome.Should().Be(ClosureBeginOutcome.Begun); + await CloseAsync(kit, closed, TenantA); + var refused = AccountClosureBeginKit.Admission(); + (await owner.BeginAsync(refused, left)).Should().Be(new ClosureBeginResult(ClosureBeginOutcome.SubjectNotAdmitted, "scheduled")); + (await kit.RequestAsync(left)).Status.Should().Be("scheduled"); + (await kit.AuditAsync(refused.Operator.CorrelationId!)).Should().ContainSingle(); + fanOut.Calls.Should().ContainSingle("only the one Begin that committed fanned out"); + } + + /// A stored state equals the expected closed document, whatever the key order jsonb keeps. + private static void SameJson(string actual, string expected) => + System.Text.Json.Nodes.JsonNode.DeepEquals(System.Text.Json.Nodes.JsonNode.Parse(actual), System.Text.Json.Nodes.JsonNode.Parse(expected)) + .Should().BeTrue($"{actual} is {expected}"); + + /// Revokes one Membership as an administrator does, under the person's and the tenant's exclusive fences. + internal static async Task RevokeAsync(AccountClosureBeginKit kit, Guid tenant, Guid? organization, Guid person, Guid membership) + { + await using var app = await DataExportTestKit.OpenAppAsync(kit.Database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await IdentityMembershipFixture.ScopeAsync(app, transaction, tenant, organization); + await IdentityMembershipFixture.LockAsync(app, transaction, tenant, person, exclusive: true); + await IdentityMembershipFixture.ExecuteAsync(app, transaction, """ + UPDATE public.memberships SET status='Revoked', deleted_at=clock_timestamp(), deleted_by=@system, + updated_at=clock_timestamp(), updated_by=@system, row_version=row_version+1 + WHERE id=@member + """, ("member", membership), ("system", UserId.SystemActor.Value)); + await IdentityMembershipFixture.ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await transaction.CommitAsync(); + } + + /// Closing to Closed as Finalize's second transaction does it, on the platform role under every fence. + private static async Task CloseAsync(AccountClosureBeginKit kit, Guid person, params Guid[] tenants) + { + await using var platform = await AccountClosureBeginKit.OpenAsync(kit.Database.PlatformConnectionString); + await using var transaction = await platform.BeginTransactionAsync(); + await IdentityMembershipFixture.ExecuteAsync(platform, transaction, "SELECT pg_catalog.pg_advisory_xact_lock(@key)", + ("key", AccountClosureBeginKit.UserKey(person))); + foreach (var tenant in tenants.OrderBy(AccountClosureBeginKit.TenantKey)) + await IdentityMembershipFixture.ExecuteAsync(platform, transaction, "SELECT pg_catalog.pg_advisory_xact_lock(@key)", + ("key", AccountClosureBeginKit.TenantKey(tenant))); + await IdentityMembershipFixture.ExecuteAsync(platform, transaction, + "UPDATE public.users SET status='Closed', provider_subject=NULL WHERE id=@user", ("user", person)); + await transaction.CommitAsync(); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureCoverageKit.cs b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureCoverageKit.cs new file mode 100644 index 000000000..cc050b730 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureCoverageKit.cs @@ -0,0 +1,173 @@ +using System.Runtime.CompilerServices; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using Npgsql; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The real platform scope with taps, for the closure's coverage cases that need a fault or an observation at one exact +/// statement of the act: the backend the act runs on, a hook before every statement (which may change the world the +/// statement is about to meet), a result row that cannot be written, and a commit whose answer is lost after it landed. +/// Every statement still runs on the real scope, in the real transaction, as learnstack_platform. +/// +internal sealed class TappedScope(IPlatformAdminScope inner) : IPlatformAdminScope +{ + /// Whether the act's own backend is read, once, as the act enters its scope. + public bool RecordBackend { get; init; } + + /// The server process of the connection the act ran on, when is set. + public int? Backend { get; private set; } + + /// Run before each statement or query of the act, with its text. + public Func? BeforeStatement { get; set; } + + /// Replaces the write of a result row: it throws, or never completes before its token does. + public Func? ReplaceWriteResult { get; set; } + + /// Run before a commit is sent, to hold the act where it holds every fence and has written everything. + public Func? BeforeCommit { get; set; } + + /// Run after a commit landed; it throws to lose the answer. + public Func? AfterCommit { get; set; } + + public async Task EnterAsync( + PlatformAdmission admission, CancellationToken cancellationToken = default, + [CallerMemberName] string? callerMember = null, + [CallerFilePath] string? callerFile = null, + [CallerLineNumber] int callerLine = 0) + { + var real = await inner.EnterAsync(admission, cancellationToken, callerMember, callerFile, callerLine); + if (RecordBackend) + { + Backend = (await real.QueryAsync( + "SELECT pg_catalog.pg_backend_pid()", null, reader => reader.GetInt32(0), cancellationToken)).Single(); + } + + return new Handle(real, this); + } + + private sealed class Handle(IPlatformAdminScopeHandle real, TappedScope tap) : IPlatformAdminScopeHandle + { + public async Task ExecuteAsync( + string sql, IReadOnlyList? parameters = null, CancellationToken cancellationToken = default) + { + if (tap.BeforeStatement is { } before) + { + await before(sql); + } + + return await real.ExecuteAsync(sql, parameters, cancellationToken); + } + + public async Task> QueryAsync( + string sql, IReadOnlyList? parameters, Func map, + CancellationToken cancellationToken = default) + { + if (tap.BeforeStatement is { } before) + { + await before(sql); + } + + return await real.QueryAsync(sql, parameters, map, cancellationToken); + } + + public Task WriteIntentAsync(PlatformResult intent, CancellationToken cancellationToken = default) => + real.WriteIntentAsync(intent, cancellationToken); + + public Task RedactAuditAsync(AuditRedactionPlan plan, CancellationToken cancellationToken = default) => + real.RedactAuditAsync(plan, cancellationToken); + + public Task WriteResultAsync(PlatformResult result, CancellationToken cancellationToken = default) => + tap.ReplaceWriteResult is { } replaced ? replaced(result, cancellationToken) : real.WriteResultAsync(result, cancellationToken); + + public async Task CommitAsync(CancellationToken cancellationToken = default) + { + if (tap.BeforeCommit is { } before) + { + await before(); + } + + await real.CommitAsync(cancellationToken); + if (tap.AfterCommit is { } after) + { + await after(); + } + } + + public ValueTask DisposeAsync() => real.DisposeAsync(); + } +} + +/// +/// The fan-out's stand-in that answers whatever a test scripts, including answers a well-behaved fan-out never gives: a +/// null list, a null element, a group nobody handed over, an outcome outside the closed set, the same group twice, a +/// cancellation. It records the groups it was handed. +/// +internal sealed class ScriptedFanOut( + Func?>> script) : IClosureFanOut +{ + public List Calls { get; } = []; + + public async Task> FanOutAsync( + PlatformOperatorWitness operatorWitness, string? ticket, ClosureFanOutRequest request, + CancellationToken cancellationToken = default) + { + Calls.Add(request); + + // The port's contract is a list; a null answer is the defect the owner must still survive. + return (await script(request, cancellationToken))!; + } +} + +/// The audit rows a coverage case plants to make a redaction assertion non-vacuous. +internal static class AccountClosureCanary +{ + /// + /// A row of the tenant whose entity is the Membership and whose after-state names the person, as the Membership's own + /// audit rows do: selected by the Membership's identifier, and its reference to the person redactable. Written as the + /// platform role, which holds the audit log's INSERT. + /// + internal static async Task PlantMembershipRowAsync(string platformConnectionString, Guid tenant, Guid membership, Guid person) + { + var id = Guid.CreateVersion7(); + await using var platform = await AccountClosureBeginKit.OpenAsync(platformConnectionString); + await using var insert = new NpgsqlCommand(""" + 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, correlation_id, after_state) + VALUES (@id, clock_timestamp(), @tenant, NULL, NULL, 'canary', 'canary.membership.row', 'Update', 'Must', 'Membership', + @entity, 'success', @correlation, jsonb_build_object('UserId', @person::text)) + """, platform); + insert.Parameters.AddWithValue("id", id); + insert.Parameters.AddWithValue("tenant", tenant); + insert.Parameters.AddWithValue("entity", membership.ToString("D")); + insert.Parameters.AddWithValue("correlation", "00-" + id.ToString("N") + "-01"); + insert.Parameters.AddWithValue("person", person); + await insert.ExecuteNonQueryAsync(); + return id; + } + + /// + /// A row of the tenant that names only the Membership: an invitation whose result is that Membership, with no actor and no + /// reference to the person. Only a redaction that compares the Membership's identifier selects it. + /// + internal static async Task PlantMembershipReferenceRowAsync(string platformConnectionString, Guid tenant, Guid membership) + { + var id = Guid.CreateVersion7(); + await using var platform = await AccountClosureBeginKit.OpenAsync(platformConnectionString); + await using var insert = new NpgsqlCommand(""" + 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, correlation_id, after_state) + VALUES (@id, clock_timestamp(), @tenant, NULL, NULL, 'canary', 'canary.invitation.row', 'Update', 'Must', 'Invitation', + @entity, 'success', @correlation, jsonb_build_object('ResultMembershipId', @membership::text)) + """, platform); + insert.Parameters.AddWithValue("id", id); + insert.Parameters.AddWithValue("tenant", tenant); + insert.Parameters.AddWithValue("entity", Guid.CreateVersion7().ToString("D")); + insert.Parameters.AddWithValue("correlation", "00-" + id.ToString("N") + "-01"); + insert.Parameters.AddWithValue("membership", membership); + await insert.ExecuteNonQueryAsync(); + return id; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureEndToEndTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureEndToEndTests.cs new file mode 100644 index 000000000..73f79bcfe --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureEndToEndTests.cs @@ -0,0 +1,346 @@ +using System.Text.Json.Nodes; +using FluentAssertions; +using LearnStack.Infrastructure.MultiTenancy; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Platform; +using LearnStack.Tests.Fixtures; +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 § 7 and ADR-0108 § 8 from end to end through the production composition: a person in three served groups of +/// two tenants and one group of a suspended tenant has a filed closure, a Begin fans it out with the real fan-out act, each +/// group's real erasure job erases the person there, and Finalize (after the provider's three stops, each repaired by a +/// repeat) redacts, deletes the account at the stand-in provider and closes the account. Afterwards the person holds no +/// account and no tenant-side data in any served group, no audit payload names them, every request of theirs is complete, +/// and only the tombstone remains; the database refuses them every new admission. +/// +/// +/// The closure is written as the filing writes it, by the application role under the person's fences; the filing routes +/// themselves, live and retained, are DataRequestHttpTests'. That a Closing or Closed binding answers every session +/// with the uniform 401 is TenantExistingBindingAdmissionTests' proof on the same row state this test reaches. +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed class AccountClosureEndToEndTests(SchemaFixture schema) +{ + private const string Ticket = "CHG-107-E2E"; + private static readonly Guid TenantA = SchemaFixture.TenantA; + private static readonly Guid TenantB = SchemaFixture.TenantB; + private static readonly Guid TenantC = Guid.Parse("33333333-3333-7333-8333-333333333333"); + private static readonly ClosureParticipantGroup TenantWideA = new(TenantId.From(TenantA), null); + private static readonly ClosureParticipantGroup BranchA1 = new(TenantId.From(TenantA), OrganizationId.From(SchemaFixture.OrgA1)); + private static readonly ClosureParticipantGroup TenantWideB = new(TenantId.From(TenantB), null); + private static readonly ClosureParticipantGroup Suspended = new(TenantId.From(TenantC), null); + private static readonly ClosureParticipantGroup[] Served = [TenantWideA, BranchA1, TenantWideB]; + + [Fact] + public async Task A_closure_from_Begin_through_each_group_s_erasure_job_to_Finalize_leaves_only_the_tombstone() + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(schema.Postgres); + var person = Guid.CreateVersion7(); + await InsertUserAsync(database.AppConnectionString, person); + var memberships = new Dictionary + { + [TenantWideA] = await MemberAsync(database, TenantWideA, person, RoleId(TenantA, BuiltInRoleKey.Learner, PermissionScope.Tenant)), + [BranchA1] = await MemberAsync(database, BranchA1, person, RoleId(TenantA, BuiltInRoleKey.Learner, PermissionScope.Organization)), + [TenantWideB] = await MemberAsync(database, TenantWideB, person, RoleId(TenantB, BuiltInRoleKey.Learner, PermissionScope.Tenant)), + [Suspended] = await SuspendedTenantMemberAsync(database, person), + }; + var closure = await FileClosureAsync(database, TenantWideA, person, memberships[TenantWideA]); + await DataErasureTestKit.BackdateAsync(database.MigrationConnectionString, TenantA, null, closure); + var second = await FileClosureAsync(database, TenantWideB, person, memberships[TenantWideB]); + // A row of the tenant that is unserved only names the person, so the proof below that Finalize reaches that tenant too + // is not an empty search before and after: only a redaction of every participant tenant, served or not, removes it. + await AccountClosureCanary.PlantMembershipRowAsync(database.PlatformConnectionString, TenantC, memberships[Suspended], person); + (await DataErasureExecutionTests.IdentifiersInPayloadsAsync(database.PlatformConnectionString, TenantC, [person.ToString("D")])) + .Should().NotBeEmpty("the unserved tenant's row names the person before the closure"); + var subject = new GlobalIdentitySubject(Authority.AuthorityId, Authority.Issuer, "fixture-subject-" + person.ToString("N")); + var removal = new RecordingAccountRemoval + { + Answer = call => call switch + { + 1 => AccountRemovalOutcome.Refused, + 2 => AccountRemovalOutcome.Unavailable, + 3 => AccountRemovalOutcome.Uncertain, + _ => AccountRemovalOutcome.Absent, + }, + }; + await using var host = AccountClosureFlow.Host(database, removal); + + // Begin, with the real fan-out: each served group's erasure created in its own transaction, the suspended tenant's not. + var begun = await AccountClosureFlow.BeginAsync(host, closure, Ticket); + begun.Outcome.Should().Be(ClosureBeginOutcome.Begun); + begun.Groups.Should().Be(new ClosureBeginTally(Served: 3, Started: 3, Adopted: 0, Waiting: 0, Failed: 0, Unserved: 1)); + + // Before the jobs ran, no group is ready and Finalize changes nothing. + var early = await AccountClosureFlow.FinalizeAsync(host, AccountClosureFlow.Admission(PlatformOperations.ClosureFinalize, Ticket), closure); + (early.Outcome, early.Groups).Should().Be((ClosureFinalizeOutcome.GroupsPending, new ClosureFinalizeTally(3, 0, 3, 1))); + removal.Subjects.Should().BeEmpty(); + + // Each group's erasure job, run as the job host runs it. + var erasures = new Dictionary(); + foreach (var group in Served) + { + erasures[group] = await AccountClosureFlow.FanOutRequestAsync(database, group, person); + await AccountClosureFlow.RunErasureJobAsync(host, database, group, erasures[group]); + } + + // The provider's three stops: each leaves the person Closing and the closure fulfilling, and a repeat resumes. + foreach (var stop in new[] { ClosureFinalizeOutcome.ProviderRefused, ClosureFinalizeOutcome.ProviderUnavailable, ClosureFinalizeOutcome.ProviderUncertain }) + { + var stopped = await AccountClosureFlow.FinalizeAsync( + host, AccountClosureFlow.Admission(PlatformOperations.ClosureFinalize, Ticket), closure); + (stopped.Outcome, stopped.Status).Should().Be((stop, "fulfilling")); + (await UserAsync(database, person)).Should().Be(("Closing", false)); + } + + var admission = AccountClosureFlow.Admission(PlatformOperations.ClosureFinalize, Ticket); + var finalized = await AccountClosureFlow.FinalizeAsync(host, admission, closure); + + finalized.Outcome.Should().Be(ClosureFinalizeOutcome.Finalized); + finalized.Groups.Should().Be(new ClosureFinalizeTally(3, 3, 0, 1, ErasuresCompleted: 3, ClosuresCompleted: 2)); + finalized.UnservedGroups.Should().Equal(Suspended); + removal.Subjects.Should().Equal(Enumerable.Repeat(subject.Subject, 4), "every attempt passes the raw subject, and nothing else"); + + // The person: Closed, the raw subject gone, the key kept. + (await UserAsync(database, person)).Should().Be(("Closed", true)); + (await SubjectKeyAsync(database, person)).Should().Be(subject.SubjectKey.Hex, "the subject key is the permanent tombstone"); + + // No tenant-side data in a served group: every Membership of the person is the Revoked tombstone with no profile and no + // assignment. The suspended tenant's stays, and is named for Phase 11's offboarding. + foreach (var group in Served) + (await MembershipAsync(database, group, memberships[group])).Should().Be(("Revoked", (string?)null, 0L), group.ToString()); + (await MembershipAsync(database, Suspended, memberships[Suspended])).Should().Be(("Active", "profile-canary", 1L)); + + // Every request of the person is complete: each group's erasure, the closure with its unserved group, the second closure. + foreach (var group in Served) + (await RequestAsync(database, group, erasures[group])).Status.Should().Be("completed", group.ToString()); + foreach (var (group, request) in new[] { (TenantWideA, closure), (TenantWideB, second) }) + { + var completed = await RequestAsync(database, group, request); + completed.Status.Should().Be("completed"); + JsonNode.Parse(completed.Result)!["unserved_group"]!.GetValue().Should().Be(1); + } + + // No audit payload in any participant tenant or the sentinel names the person, a Membership of theirs or their profile. + string[] identifiers = [person.ToString("D"), .. memberships.Where(entry => entry.Key != Suspended).Select(entry => entry.Value.ToString("D")), + "profile-canary"]; + foreach (var tenant in new[] { TenantA, TenantB, TenantC, TenantId.PlatformSentinel.Value }) + { + string.Join(Environment.NewLine, await DataErasureExecutionTests.IdentifiersInPayloadsAsync( + database.PlatformConnectionString, tenant, identifiers)) + .Should().BeEmpty($"no payload of {tenant} names the person after the closure, except own keys"); + } + + // The evidence: under the sentinel, with the ticket, an intent row per attempt that reached the provider and a result + // row saying how each ended, and the final act's closed counts. + var rows = await RowsAsync(database, admission.Operator.CorrelationId!); + rows.Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation, "platform.closure.finalize_attempt", "platform.closure.finalize"); + rows.Should().OnlyContain(row => row.Tenant == TenantId.PlatformSentinel.Value && row.Metadata.Contains(Ticket)); + var recorded = JsonNode.Parse(rows[^1].After)!; + (recorded["outcome"]!.GetValue(), recorded["provider"]!.GetValue(), recorded["groups"]!["unserved"]!.GetValue()) + .Should().Be(("finalized", "absent", 1)); + (await CountAsync(database, "SELECT count(*) FROM public.audit_log WHERE operation = 'platform.closure.finalize_attempt' AND entity_id = @id", + closure)).Should().Be(4, "one intent row per attempt that reached the provider"); + (await CountAsync(database, "SELECT count(*) FROM public.audit_log WHERE operation = 'platform.closure.finalize' AND entity_id = @id", + closure)).Should().Be(4, "each of those attempts recorded how it ended"); + + // The person is refused everywhere: the binding row every session resolves to is Closed, a new Membership and a new + // request are refused by the database, and a repeat of the act finds it done. + (await BindingStatusAsync(database, subject)).Should().Be("Closed"); + await using (var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString)) + { + await using (var transaction = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, transaction, TenantB, SchemaFixture.OrgB1); + await LockAsync(app, transaction, TenantB, person, false); + var admit = () => InsertMemberAsync(app, transaction, TenantB, SchemaFixture.OrgB1, Guid.CreateVersion7(), person, + RoleId(TenantB, BuiltInRoleKey.Learner, PermissionScope.Organization)); + (await admit.Should().ThrowAsync()).Which.SqlState.Should().Be("P0302"); + } + + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, TenantB, null, person); + var file = () => InsertRequestAsync(app, transaction, Guid.CreateVersion7(), TenantB, null, person, + [memberships[TenantWideB]], "erasure"); + (await file.Should().ThrowAsync()).Which.MessageText.Should().Be("Data request subject is not admitted."); + } + } + + var repeat = await AccountClosureFlow.FinalizeAsync(host, AccountClosureFlow.Admission(PlatformOperations.ClosureFinalize, Ticket), closure); + repeat.Outcome.Should().Be(ClosureFinalizeOutcome.AlreadyFinalized); + removal.Subjects.Should().HaveCount(4); + } + + private static async Task MemberAsync(DisposableSchemaDatabase database, ClosureParticipantGroup group, Guid person, Guid role) + { + var member = Guid.CreateVersion7(); + await using var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, group.TenantId.Value, group.OrganizationId?.Value); + // The tenant key exclusively, as a tenant's first Membership needs it. + await LockAsync(app, transaction, group.TenantId.Value, person, true); + await InsertMemberAsync(app, transaction, group.TenantId.Value, group.OrganizationId?.Value, member, person, role); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await transaction.CommitAsync(); + return member; + } + + /// + /// A third tenant the person joined while it was in use, provisioned as the onboarding writes a tenant, its Roles and a + /// Membership; it is suspended afterwards, so its group is unserved. + /// + private async Task SuspendedTenantMemberAsync(DisposableSchemaDatabase database, Guid person) + { + await using (var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString)) + { + await using (var transaction = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, transaction, TenantC); + await ExecuteAsync(app, transaction, """ + INSERT INTO public.tenants(id,slug,display_name,status,created_at,created_by,row_version) + VALUES(@tenant,'closure-unserved','Unserved','Trial',clock_timestamp(),@actor,0) + """, ("tenant", TenantC), ("actor", UserId.SystemActor.Value)); + await transaction.CommitAsync(); + } + + var templates = IdentityFoundationManifest.Version1.Templates.ToArray(); + for (var index = 0; index < templates.Length; index++) + { + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, TenantC); + await LockAsync(app, transaction, TenantC, null, false); + await ExecuteAsync(app, transaction, """ + INSERT INTO public.roles(id,tenant_id,built_in_key,permission_scope,created_at,created_by) + VALUES(@id,@tenant,@key,@scope,clock_timestamp(),@actor) + """, ("id", RoleC(index)), ("tenant", TenantC), ("key", templates[index].BuiltInKey.ToString()), + ("scope", templates[index].Scope.ToString()), ("actor", UserId.SystemActor.Value)); + foreach (var permission in templates[index].Grants) + await ExecuteAsync(app, transaction, """ + INSERT INTO public.role_permission_grants(tenant_id,role_id,permission_scope,permission_key) + VALUES(@tenant,@role,@scope,@key) + """, ("tenant", TenantC), ("role", RoleC(index)), ("scope", permission.Scope.ToString()), ("key", permission.Key)); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await transaction.CommitAsync(); + } + + // A tenant in use has its administrator before anyone else joins. + var administrator = Guid.CreateVersion7(); + await InsertUserAsync(database.AppConnectionString, administrator); + await MemberAsync(database, Suspended, administrator, + RoleC(Array.FindIndex(templates, template => template.BuiltInKey == BuiltInRoleKey.TenantAdmin && template.Scope == PermissionScope.Tenant))); + var learner = Array.FindIndex(templates, template => template.BuiltInKey == BuiltInRoleKey.Learner && template.Scope == PermissionScope.Tenant); + var member = await MemberAsync(database, Suspended, person, RoleC(learner)); + await schema.Postgres.ExecuteAsSuperuserAsync( + $"SET session_replication_role = replica; UPDATE public.tenants SET status = 'Suspended' WHERE id = '{TenantC}'", + RebindProofSupport.DatabaseOf(database.MigrationConnectionString)); + return member; + } + } + + private static Guid RoleC(int index) => Guid.Parse($"01930000-0000-7000-8000-00000000e3{index + 1:00}"); + + /// A closure the person files in the group, as the filing writes it under the person's fences. + private static async Task FileClosureAsync(DisposableSchemaDatabase database, ClosureParticipantGroup group, Guid person, Guid membership) + { + var id = Guid.CreateVersion7(); + await using var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, group.TenantId.Value, group.OrganizationId?.Value, person); + await InsertRequestAsync(app, transaction, id, group.TenantId.Value, group.OrganizationId?.Value, person, [membership], "closure"); + await transaction.CommitAsync(); + return id; + } + + private static async Task<(string Status, bool SubjectRemoved)> UserAsync(DisposableSchemaDatabase database, Guid person) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString); + await using var command = new NpgsqlCommand("SELECT status, provider_subject IS NULL FROM public.users WHERE id = @id", owner); + command.Parameters.AddWithValue("id", person); + await using var row = await command.ExecuteReaderAsync(); + (await row.ReadAsync()).Should().BeTrue(); + return (row.GetString(0), row.GetBoolean(1)); + } + + private static async Task SubjectKeyAsync(DisposableSchemaDatabase database, Guid person) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString); + return await ScalarAsync(owner, null, "SELECT encode(subject_key, 'hex') FROM public.users WHERE id = @id", ("id", person)); + } + + /// The User row the binding store resolves a session's subject to, read as the application role does. + private static async Task BindingStatusAsync(DisposableSchemaDatabase database, GlobalIdentitySubject subject) + { + await using var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await GlobalIdentitySchemaTests.AnnounceAsync(app, transaction, subject); + return await ScalarAsync(app, transaction, + "SELECT status FROM public.users WHERE authority_id = @authority AND subject_key = @key", + ("authority", subject.AuthorityId.Value), ("key", subject.SubjectKey.ToByteArray())); + } + + private static async Task<(string Status, string? DisplayName, long Assignments)> MembershipAsync( + DisposableSchemaDatabase database, ClosureParticipantGroup group, Guid membership) + { + await using var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, group.TenantId.Value, group.OrganizationId?.Value); + await using var command = new NpgsqlCommand(""" + SELECT m.status, p.display_name, + (SELECT count(*) FROM public.membership_role_assignments a WHERE a.tenant_id = m.tenant_id AND a.membership_id = m.id) + FROM public.memberships m JOIN public.membership_profiles p ON p.tenant_id = m.tenant_id AND p.membership_id = m.id + WHERE m.id = @id + """, app, transaction); + command.Parameters.AddWithValue("id", membership); + await using var row = await command.ExecuteReaderAsync(); + (await row.ReadAsync()).Should().BeTrue(); + return (row.GetString(0), row.IsDBNull(1) ? null : row.GetString(1), row.GetInt64(2)); + } + + private sealed record RequestRow(string Status, string Result); + + private static async Task RequestAsync(DisposableSchemaDatabase database, ClosureParticipantGroup group, Guid request) + { + await using var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, group.TenantId.Value, group.OrganizationId?.Value); + await using var command = new NpgsqlCommand("SELECT status, result::text 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 RequestRow(row.GetString(0), row.GetString(1)); + } + + private sealed record OperatorRow(Guid Tenant, string Operation, string After, string Metadata); + + private static async Task> RowsAsync(DisposableSchemaDatabase database, string correlation) + { + await using var platform = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.PlatformConnectionString); + await using var command = new NpgsqlCommand(""" + SELECT tenant_id, operation, COALESCE(after_state::text, ''), metadata::text + FROM public.audit_log WHERE correlation_id = @c ORDER BY "timestamp", id + """, platform); + command.Parameters.AddWithValue("c", correlation); + var rows = new List(); + await using var reader = await command.ExecuteReaderAsync(); + while (await reader.ReadAsync()) + rows.Add(new OperatorRow(reader.GetGuid(0), reader.GetString(1), reader.GetString(2), reader.GetString(3))); + return rows; + } + + private static async Task CountAsync(DisposableSchemaDatabase database, string sql, Guid entity) + { + await using var platform = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.PlatformConnectionString); + return await ScalarAsync(platform, null, sql, ("id", entity.ToString("D"))); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureFinalizeTests.Coverage.cs b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureFinalizeTests.Coverage.cs new file mode 100644 index 000000000..06b99d0e6 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureFinalizeTests.Coverage.cs @@ -0,0 +1,529 @@ +using System.Diagnostics; +using System.Text.Json.Nodes; +using FluentAssertions; +using LearnStack.Infrastructure.MultiTenancy; +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.Modules.Identity.Infrastructure.DataRequests; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Platform; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The Finalize's branches the first suites left unreached, each arranged in the real database through the seams the +/// suite already uses: a participant tenant that holds only an unserved group, the retained counts each request records by +/// value, two operators finalizing one closure, every defect the act names, a result row that cannot be written, a second +/// closure that began, a person with groups of organizations alone, and a Membership revoked after the Begin. +/// +public sealed partial class AccountClosureFinalizeTests +{ + // Built from the fixture's constants: static fields of the other parts of this class may not be assigned yet. + private static readonly ClosureParticipantGroup BranchB1 = new(TenantId.From(SchemaFixture.TenantB), OrganizationId.From(SchemaFixture.OrgB1)); + + /// The audit kinds a report retained, by closed code. + private static Dictionary RetainedCodes(AuditRedactionReport report) => + report.Retained.ToDictionary(entry => DataRequestCodes.RetainedKinds.ToCode(entry.Kind), entry => entry.Count, StringComparer.Ordinal); + + /// + /// A request's recorded result carries exactly the retained audit counts of , by value: the + /// kinds the redaction reported replace whatever the request held, and a non-vacuous report names at least the actor kind. + /// + private static void AssertRetainedCounts(IReadOnlyDictionary recorded, AuditRedactionReport report, string because) + { + var expected = RetainedCodes(report); + expected.Should().ContainKey("audit_actor_reference").WhoseValue.Should().BePositive("the planted rows make the count worth comparing"); + foreach (var (kind, count) in expected) + { + recorded.Should().ContainKey(kind, because).WhoseValue.Should().Be(count, $"{because}: {kind}"); + } + } + + private static void AssertRetainedCounts(JsonObject recorded, AuditRedactionReport report, string because) => + AssertRetainedCounts( + recorded.ToDictionary(entry => entry.Key, entry => entry.Value!.GetValue(), StringComparer.Ordinal), report, because); + + /// The transaction state of one backend of this database, read by its process. + private static async Task BackendStateAsync(AccountClosureBeginKit kit, int backend) + { + await using var observer = await AccountClosureBeginKit.OpenAsync(kit.Database.PlatformConnectionString); + await using var command = new NpgsqlCommand( + "SELECT COALESCE(state, '') FROM pg_catalog.pg_stat_activity WHERE datname = current_database() AND pid = @pid", observer); + command.Parameters.AddWithValue("pid", backend); + return (string)(await command.ExecuteScalarAsync())!; + } + + /// + /// A participant tenant in which the person holds only an unserved group (the tenant stopped allowing ordinary work + /// before the Begin) is redacted like every other participant tenant: its audit rows that name the person lose their + /// address, agent and e-mail, and the tenant's own report is among the redaction's. A redaction that reached only the + /// tenants of served groups, or only the closure's own tenant, leaves that tenant's rows as they were. + /// + [Fact] + public async Task A_tenant_whose_only_group_is_unserved_is_redacted_like_every_other_participant_tenant() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + var member = await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + await kit.MemberAsync(TenantB, null, person, BuiltInRoleKey.Learner); + var closure = await kit.ClosureAsync(TenantA, null, person); + await kit.TenantStatusAsync(TenantB, "Suspended"); + (await kit.Owner().BeginAsync(AccountClosureBeginKit.Admission(), closure)).Groups.Should().Be(new ClosureBeginTally(1, 1, 0, 0, 0, 1)); + var world = new World( + person, "fixture-subject-" + person.ToString("N"), closure, Guid.Empty, + new Dictionary { [TenantWideA] = await FanOutErasureAsync(kit, TenantWideA, person, member, awaiting: true) }, + new Dictionary + { + ["tenant A"] = await PlantAsync(kit, TenantA, person), + ["tenant B (unserved only)"] = await PlantAsync(kit, TenantB, person), + ["sentinel"] = await PlantAsync(kit, TenantId.PlatformSentinel.Value, person), + }); + (await PlantedAsync(kit, world)).Values.Should().OnlyContain(row => row.Address != null, "the planted rows name the person before the act"); + + var result = await kit.Owner().FinalizeAsync(Admission(), closure); + + result.Outcome.Should().Be(ClosureFinalizeOutcome.Finalized); + result.Groups.Should().Be(new ClosureFinalizeTally(Served: 1, Ready: 1, Pending: 0, Unserved: 1, ErasuresCompleted: 1, ClosuresCompleted: 1)); + result.UnservedGroups.Should().Equal(TenantWideB); + result.Redaction!.Tenants.Keys.Should().BeEquivalentTo([TenantId.From(TenantA), TenantId.From(TenantB)]); + result.Redaction.Tenants[TenantId.From(TenantB)].RowsSelected.Should().Be(1, "the tenant's own pass found the row that names the person"); + (await PlantedAsync(kit, world)).Should().ContainKey("tenant B (unserved only)").WhoseValue.Should().Be( + new PlantedRow(null, null, null, person), "the unserved-only tenant's row lost its address, agent and e-mail"); + (await PlantedAsync(kit, world)).Values.Should().OnlyContain(row => row.Address == null && row.Agent == null && row.Email == null); + } + + /// + /// The retained audit counts each completed request records are the redaction's, by value and by tenant: a fan-out + /// erasure records its own tenant's counts and a closure the total of every pass. The tenants hold different numbers of + /// rows that name the person, so the tenant's count, the other tenant's and the total are three different numbers, and + /// none of them is the job's. + /// + [Fact] + public async Task Each_erasure_records_its_own_tenant_s_retained_counts_and_each_closure_the_total_by_value() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await BegunAsync(kit); + await PlantAsync(kit, TenantA, world.Person); + await PlantAsync(kit, TenantA, world.Person); + + var result = await kit.Owner().FinalizeAsync(Admission(), world.Closure); + + result.Outcome.Should().Be(ClosureFinalizeOutcome.Finalized); + var tenantA = RetainedCodes(result.Redaction!.Tenants[TenantId.From(TenantA)]); + var tenantB = RetainedCodes(result.Redaction.Tenants[TenantId.From(TenantB)]); + var total = RetainedCodes(result.Redaction.Total); + tenantA["audit_actor_reference"].Should().Be(3); + tenantB["audit_actor_reference"].Should().Be(1); + total["audit_actor_reference"].Should().BeGreaterThan(tenantA["audit_actor_reference"], "the total sums every pass, the sentinel's included"); + foreach (var group in Served) + { + var recorded = JsonNode.Parse((await RequestStateAsync(kit, group, world.Erasures[group])).Result)!.AsObject(); + AssertRetainedCounts(recorded, result.Redaction.Tenants[group.TenantId], group + " records its own tenant's counts"); + recorded["consent_evidence"]!.GetValue().Should().Be(2, "the tenant side's record is kept"); + recorded["audit_actor_reference"]!.GetValue().Should().NotBe(9, "the job's own count is replaced"); + } + + foreach (var (group, request) in new[] { (TenantWideA, world.Closure), (TenantWideB, world.SecondClosure) }) + { + var recorded = JsonNode.Parse((await RequestStateAsync(kit, group, request)).Result)!.AsObject(); + AssertRetainedCounts(recorded, result.Redaction.Total, "a closure records the total"); + recorded["unserved_group"]!.GetValue().Should().Be(1); + } + + AssertRetainedCounts(result.Retained!, result.Redaction.Total, "the answer carries the closure's recorded counts"); + } + + /// + /// A Finalize that waited for the fences of another's second transaction, which then completed the closure, answers what + /// was recorded and writes nothing: the provider is not asked, the person is not touched again and only the entry row is + /// its record. + /// + [Fact] + public async Task A_Finalize_that_waited_for_the_fences_of_another_that_completed_answers_it_and_writes_nothing() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await BegunAsync(kit); + var atCommit = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var gated = new TappedScope(kit.Scope()) + { + BeforeCommit = async () => + { + atCommit.TrySetResult(); + await release.Task; + }, + }; + var first = new RecordingAccountRemoval(); + var second = new RecordingAccountRemoval(); + var waiting = Admission(); + + var winner = kit.Owner(scope: gated, removal: first).FinalizeAsync(Admission(), world.Closure); + Task? loser = null; + try + { + await atCommit.Task.WaitAsync(TimeSpan.FromSeconds(30)); + loser = kit.Owner(removal: second).FinalizeAsync(waiting, world.Closure); + await kit.WaitUntilALockIsAwaitedAsync("learnstack_platform", loser, "the second Finalize waits for the first's second transaction's fences"); + } + finally + { + release.TrySetResult(); + } + + var completed = await winner; + var answered = await loser!; + + completed.Outcome.Should().Be(ClosureFinalizeOutcome.Finalized); + answered.Should().BeEquivalentTo(new ClosureFinalizeResult(ClosureFinalizeOutcome.AlreadyFinalized, "completed", Retained: completed.Retained)); + second.Subjects.Should().BeEmpty("the second Finalize never reaches the provider"); + first.Subjects.Should().HaveCount(1); + (await kit.AuditAsync(waiting.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal([PlatformAdminScope.EnterOperation]); + } + + /// + /// A closure another operator's Finalize completed while this one called the provider is found completed under the second + /// fences: this attempt records already_finalized with its own redaction, writes no state, and answers the + /// closure's recorded counts. + /// + [Fact] + public async Task A_Finalize_whose_closure_another_operator_completed_during_its_provider_call_records_already_finalized() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await BegunAsync(kit); + var other = new RecordingAccountRemoval(); + ClosureFinalizeResult? inner = null; + var removal = new RecordingAccountRemoval + { + Probe = async () => inner = await kit.Owner(removal: other).FinalizeAsync(Admission(), world.Closure), + }; + var admission = Admission(); + + var result = await kit.Owner(removal: removal).FinalizeAsync(admission, world.Closure); + + inner!.Outcome.Should().Be(ClosureFinalizeOutcome.Finalized); + result.Outcome.Should().Be(ClosureFinalizeOutcome.AlreadyFinalized); + result.Status.Should().Be("completed"); + result.Groups.Should().BeNull("this attempt completed nothing"); + result.Redaction.Should().NotBeNull("this attempt's own redaction committed with its intent row"); + result.Retained.Should().BeEquivalentTo(inner.Retained); + other.Subjects.Should().HaveCount(1); + removal.Subjects.Should().HaveCount(1); + var rows = await kit.AuditAsync(admission.Operator.CorrelationId!); + rows.Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation, Attempt, Result); + var recorded = JsonNode.Parse(rows[^1].After)!; + (recorded["outcome"]!.GetValue(), recorded["provider"]!.GetValue()).Should().Be(("already_finalized", "removed")); + (await kit.UserAsync(world.Person)).Status.Should().Be("Closed"); + } + + /// + /// Anything that changed the closure or its person between the two transactions is a broken invariant, named and logged + /// by its closed name: the provider's account is already gone, nothing of the second transaction committed, and no result + /// row is written. Each disjunct of the second transaction's judgment is driven alone. + /// + [Theory] + [InlineData("version")] + [InlineData("stamp")] + [InlineData("status")] + [InlineData("account")] + [InlineData("group")] + public async Task A_closure_changed_between_the_two_transactions_is_a_defect_after_the_account_is_gone(string change) + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await BegunAsync(kit); + var changed = change switch + { + "version" => $"UPDATE public.data_subject_requests SET row_version = row_version + 1 WHERE id = '{world.Closure}'", + "stamp" => $"UPDATE public.data_subject_requests SET updated_at = updated_at + interval '1 second' WHERE id = '{world.Closure}'", + "status" => $"UPDATE public.data_subject_requests SET status = 'cancelled' WHERE id = '{world.Closure}'", + "account" => $"UPDATE public.users SET status = 'Active' WHERE id = '{world.Person}'", + _ => $""" + INSERT INTO public.memberships(id,tenant_id,organization_id,user_id,status,created_at,created_by,deleted_at,deleted_by) + VALUES('{Guid.CreateVersion7()}','{TenantB}','{SchemaFixture.OrgB1}','{world.Person}','Revoked',clock_timestamp(), + '{UserId.SystemActor.Value}',clock_timestamp(),'{UserId.SystemActor.Value}') + """, + }; + var removal = new RecordingAccountRemoval { Probe = () => kit.SqlAsync("SET session_replication_role = replica; " + changed) }; + var logs = new CapturingLogger(); + var admission = Admission(); + + var act = () => kit.Owner(removal: removal, logger: logs).FinalizeAsync(admission, world.Closure); + + await act.Should().ThrowAsync(); + logs.Lines.Should().ContainSingle().Which.Should().StartWith("7122 Error ").And.Contain("closure_changed_between_transactions") + .And.NotContain(world.Person.ToString("D")).And.NotContain(world.ProviderSubject); + removal.Subjects.Should().Equal([world.ProviderSubject], "the account was deleted before the second transaction judged"); + (await kit.UserAsync(world.Person)).Status.Should().Be(change == "account" ? "Active" : "Closing", "nothing of the second transaction committed"); + foreach (var group in Served) + { + (await RequestStateAsync(kit, group, world.Erasures[group])).Status.Should().Be("awaiting_privileged_step"); + } + + (await kit.RequestAsync(world.Closure)).Status.Should().Be(change == "status" ? "cancelled" : "fulfilling"); + (await kit.AuditAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should() + .Equal([PlatformAdminScope.EnterOperation, Attempt], "the intent row committed with the redaction and no result row was written"); + } + + /// + /// A row another session changed under the second transaction (the User no longer Closing when the act closes it) is a + /// defect by its closed name, and the whole second transaction rolls back: no earlier statement of it, the Closed User + /// included, survives. An awaiting erasure cannot change under it: the transaction locks them first, so one the + /// operator's completion finished meanwhile is accepted as completed (the fences test of this class). + /// + [Theory] + [InlineData("account_not_closed")] + public async Task A_row_changed_under_the_second_transaction_is_a_defect_that_rolls_the_whole_transaction_back(string defect) + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await BegunAsync(kit); + var armed = true; + var scope = new TappedScope(kit.Scope()) + { + BeforeStatement = async sql => + { + if (!armed) + { + return; + } + + if (defect == "account_not_closed" && sql.Contains("SET status = 'Closed'", StringComparison.Ordinal)) + { + armed = false; + await kit.SqlAsync($"SET session_replication_role = replica; UPDATE public.users SET status = 'Active' WHERE id = '{world.Person}'"); + } + }, + }; + var removal = new RecordingAccountRemoval(); + var logs = new CapturingLogger(); + var admission = Admission(); + + var act = () => kit.Owner(removal: removal, scope: scope, logger: logs).FinalizeAsync(admission, world.Closure); + + await act.Should().ThrowAsync(); + armed.Should().BeFalse("the hook found the statement it was set for"); + logs.Lines.Should().ContainSingle().Which.Should().StartWith("7122 Error ").And.Contain(defect).And.NotContain(world.Person.ToString("D")); + removal.Subjects.Should().HaveCount(1); + var user = await kit.UserAsync(world.Person); + (user.Status, user.SubjectPresent).Should().Be(("Active", true), + "the User's move to Closed was rolled back with the rest"); + (await kit.RequestAsync(world.Closure)).Status.Should().Be("fulfilling"); + foreach (var group in Served) + { + (await RequestStateAsync(kit, group, world.Erasures[group])).Status.Should().Be("awaiting_privileged_step"); + } + + (await kit.AuditAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal([PlatformAdminScope.EnterOperation, Attempt]); + } + + /// + /// A person with one more open closure beside the finalized one than the bound is refused after the provider call: the + /// closures are read last, in the second transaction, and the defect rolls the whole of it back. Exactly the bound many + /// others complete with the closure. The world already holds one other (the second closure in its window), so the cases + /// add the bound less one and the bound. + /// + [Theory] + [InlineData(ClosureLimits.MaximumParticipantGroups - 1, true)] + [InlineData(ClosureLimits.MaximumParticipantGroups, false)] + public async Task The_closures_a_person_holds_beyond_the_bound_are_a_defect_that_rolls_the_second_transaction_back(int added, bool finalized) + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await BegunAsync(kit); + var membership = (await kit.MembershipsAsync(TenantB, null, world.Person))[0]; + // Open closures in groups of no organization that exists, written by the owner with the guards paused; the tenant is one + // of the person's participants, so the second transaction holds its fence. + await kit.SqlAsync($""" + SET session_replication_role = replica; + 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) + SELECT uuidv7(), '{TenantB}', uuidv7(), 'closure', 'self', '{world.Person}', '{world.Person}', 'scheduled', + '["{membership}"]'::jsonb, created.at + interval '24 hours', created.at, '{world.Person}', 0 + FROM (SELECT now() - interval '2 days' AS at) AS created, generate_series(1, {added}) AS series + """); + var logs = new CapturingLogger(); + var admission = Admission(); + + var act = () => kit.Owner(logger: logs).FinalizeAsync(admission, world.Closure); + + if (finalized) + { + var result = await act(); + result.Outcome.Should().Be(ClosureFinalizeOutcome.Finalized); + result.Groups!.ClosuresCompleted.Should().Be(ClosureLimits.MaximumParticipantGroups + 1, + "the bound many others and the closure itself complete: the bound itself is not beyond the bound"); + return; + } + + await act.Should().ThrowAsync(); + logs.Lines.Should().ContainSingle().Which.Should().StartWith("7122 Error ").And.Contain("open_closures_beyond_bound"); + (await kit.UserAsync(world.Person)).Status.Should().Be("Closing", "the second transaction rolled back"); + (await kit.RequestAsync(world.Closure)).Status.Should().Be("fulfilling"); + foreach (var group in Served) + { + (await RequestStateAsync(kit, group, world.Erasures[group])).Status.Should().Be("awaiting_privileged_step"); + } + } + + /// + /// A Closing account whose raw provider subject is already gone cannot be removed at the provider: the act is abandoned + /// before anything is redacted or asked, with the closed name logged. + /// + [Fact] + public async Task A_Closing_account_without_a_provider_subject_is_a_defect_before_any_redaction() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await BegunAsync(kit); + await kit.SqlAsync($"SET session_replication_role = replica; UPDATE public.users SET provider_subject = NULL WHERE id = '{world.Person}'"); + var removal = new RecordingAccountRemoval(); + var logs = new CapturingLogger(); + var admission = Admission(); + + var act = () => kit.Owner(removal: removal, logger: logs).FinalizeAsync(admission, world.Closure); + + await act.Should().ThrowAsync(); + logs.Lines.Should().ContainSingle().Which.Should().StartWith("7122 Error ").And.Contain("closing_account_without_provider_subject"); + removal.Subjects.Should().BeEmpty(); + (await PlantedAsync(kit, world)).Values.Should().OnlyContain(row => row.Address != null, "nothing was redacted"); + (await kit.AuditAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal([PlatformAdminScope.EnterOperation]); + } + + /// + /// A result row recording a stop at the provider that cannot be written, because the write fails or outlasts its + /// three-second budget, changes no answer: the act answers the stop it found, the intent row stands alone, the failure is + /// logged critical by the closed outcome, and a repeat finishes. + /// + [Theory] + [InlineData("fails")] + [InlineData("outlasts_the_budget")] + public async Task A_result_row_that_cannot_be_written_leaves_the_answer_unchanged_and_is_logged_critical(string how) + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await BegunAsync(kit); + var removal = new RecordingAccountRemoval { Answer = call => call == 1 ? AccountRemovalOutcome.Refused : AccountRemovalOutcome.Absent }; + var scope = new TappedScope(kit.Scope()) + { + ReplaceWriteResult = how == "fails" + ? (_, _) => Task.FromException(new InvalidOperationException("forced result failure")) + : (_, token) => Task.Delay(Timeout.InfiniteTimeSpan, token), + }; + var logs = new CapturingLogger(); + var admission = Admission(); + var clock = Stopwatch.StartNew(); + + var result = await kit.Owner(removal: removal, scope: scope, logger: logs).FinalizeAsync(admission, world.Closure); + + clock.Stop(); + result.Outcome.Should().Be(ClosureFinalizeOutcome.ProviderRefused, "the answer is what the act found"); + result.Redaction.Should().NotBeNull(); + if (how != "fails") + { + clock.Elapsed.Should().BeGreaterThanOrEqualTo(TimeSpan.FromSeconds(2.5)).And.BeLessThan(TimeSpan.FromSeconds(15), "the write is given three seconds"); + } + + logs.Lines.Should().Contain(line => line.StartsWith("7121 Warning ", StringComparison.Ordinal)) + .And.ContainSingle(line => line.StartsWith("7123 Critical ", StringComparison.Ordinal) && line.Contains("provider_refused", StringComparison.Ordinal)) + .Which.Should().NotContain(world.Person.ToString("D")).And.NotContain(world.ProviderSubject); + (await kit.AuditAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should() + .Equal([PlatformAdminScope.EnterOperation, Attempt], "only the intent row stands"); + (await kit.UserAsync(world.Person)).Status.Should().Be("Closing"); + + (await kit.Owner(removal: removal).FinalizeAsync(Admission(), world.Closure)).Outcome.Should().Be(ClosureFinalizeOutcome.Finalized); + (await kit.UserAsync(world.Person)).Status.Should().Be("Closed"); + } + + /// + /// A second closure of the person that already began (fulfilling) is completed by the first's Finalize from fulfilling, + /// with the closure's retained counts, as one never begun is completed from scheduled. + /// + [Fact] + public async Task A_second_closure_that_began_is_completed_by_the_first_s_Finalize() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await BegunAsync(kit); + await kit.BackdateAsync(world.SecondClosure, TenantB, null); + (await kit.Owner().BeginAsync(AccountClosureBeginKit.Admission(), world.SecondClosure)).Outcome.Should().Be(ClosureBeginOutcome.Resumed); + (await kit.RequestAsync(world.SecondClosure)).Status.Should().Be("fulfilling"); + + var result = await kit.Owner().FinalizeAsync(Admission(), world.Closure); + + result.Outcome.Should().Be(ClosureFinalizeOutcome.Finalized); + result.Groups!.ClosuresCompleted.Should().Be(2); + (await kit.RequestAsync(world.SecondClosure)).Status.Should().Be("completed"); + var recorded = JsonNode.Parse((await RequestStateAsync(kit, TenantWideB, world.SecondClosure)).Result)!.AsObject(); + AssertRetainedCounts(recorded, result.Redaction!.Total, "the begun second closure records the total"); + recorded["unserved_group"]!.GetValue().Should().Be(1); + } + + /// + /// A person whose groups are all organizations (no tenant-wide Membership in either tenant) is finalized through each + /// organization's erasure: the closure is filed in an organization, every group's fan-out erasure is read by its own + /// group, both tenants are redacted and the person is closed. + /// + [Fact] + public async Task A_person_with_groups_of_organizations_alone_is_finalized_through_each_group_s_erasure() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + var memberships = new Dictionary + { + [BranchA1] = await kit.MemberAsync(TenantA, SchemaFixture.OrgA1, person, BuiltInRoleKey.Learner), + [new(TenantId.From(TenantA), OrganizationId.From(SchemaFixture.OrgA2))] = + await kit.MemberAsync(TenantA, SchemaFixture.OrgA2, person, BuiltInRoleKey.Learner), + [BranchB1] = await kit.MemberAsync(TenantB, SchemaFixture.OrgB1, person, BuiltInRoleKey.Learner), + }; + var closure = await kit.ClosureAsync(TenantA, SchemaFixture.OrgA1, person); + (await kit.Owner().BeginAsync(AccountClosureBeginKit.Admission(), closure)).Groups.Should().Be(new ClosureBeginTally(3, 3, 0, 0, 0, 0)); + var erasures = new Dictionary(); + foreach (var (group, member) in memberships) + { + erasures[group] = await FanOutErasureAsync(kit, group, person, member, awaiting: true); + } + + var world = new World(person, "fixture-subject-" + person.ToString("N"), closure, Guid.Empty, erasures, + new Dictionary { ["tenant A"] = await PlantAsync(kit, TenantA, person), ["tenant B"] = await PlantAsync(kit, TenantB, person) }); + + var result = await kit.Owner().FinalizeAsync(Admission(), closure); + + result.Outcome.Should().Be(ClosureFinalizeOutcome.Finalized); + result.Groups.Should().Be(new ClosureFinalizeTally(Served: 3, Ready: 3, Pending: 0, Unserved: 0, ErasuresCompleted: 3, ClosuresCompleted: 1)); + result.UnservedGroups.Should().BeEmpty(); + foreach (var (group, request) in erasures) + { + (await RequestStateAsync(kit, group, request)).Status.Should().Be("completed", group.ToString()); + } + + (await RequestStateAsync(kit, BranchA1, closure)).Status.Should().Be("completed"); + (await PlantedAsync(kit, world)).Values.Should().OnlyContain(row => row.Address == null); + (await kit.UserAsync(person)).Status.Should().Be("Closed"); + } + + /// + /// A Membership revoked after the Begin is still the person's: its group stays a participant and ready, and the + /// redaction compares the rows of the tenant with the revoked Membership too, so a row that names only that Membership + /// (no actor, no reference to the person) is selected and its payload reference is redacted. + /// + [Fact] + public async Task A_Membership_revoked_after_the_Begin_is_still_a_reference_the_redaction_compares() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await BegunAsync(kit); + var membership = (await kit.MembershipsAsync(TenantA, SchemaFixture.OrgA1, world.Person)).Single(); + await AccountClosureBeginTests.RevokeAsync(kit, TenantA, SchemaFixture.OrgA1, world.Person, membership); + await AccountClosureCanary.PlantMembershipReferenceRowAsync(kit.Database.PlatformConnectionString, TenantA, membership); + (await DataErasureExecutionTests.IdentifiersInPayloadsAsync(kit.Database.PlatformConnectionString, TenantA, [membership.ToString("D")])) + .Should().NotBeEmpty("the row names the revoked Membership before the act"); + + var result = await kit.Owner().FinalizeAsync(Admission(), world.Closure); + + result.Outcome.Should().Be(ClosureFinalizeOutcome.Finalized); + result.Groups.Should().Be(new ClosureFinalizeTally(3, 3, 0, 1, ErasuresCompleted: 3, ClosuresCompleted: 2), + "the revoked Membership's group is still a served participant"); + result.Redaction!.Tenants[TenantId.From(TenantA)].RowsSelected.Should().Be(2, + "the planted actor row and the row that names only the revoked Membership"); + (await DataErasureExecutionTests.IdentifiersInPayloadsAsync(kit.Database.PlatformConnectionString, TenantA, [membership.ToString("D")])) + .Should().BeEmpty("the revoked Membership's reference was redacted"); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureFinalizeTests.Fences.cs b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureFinalizeTests.Fences.cs new file mode 100644 index 000000000..5dee95b01 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureFinalizeTests.Fences.cs @@ -0,0 +1,323 @@ +using System.Diagnostics; +using FluentAssertions; +using LearnStack.Infrastructure.MultiTenancy; +using LearnStack.Modules.Identity.Infrastructure.DataRequests; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.Tests.Fixtures; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// Finalize's fences and the states another act or a lifecycle change leaves between its reads: the first transaction holds +/// the person's User fence alone while it redacts, an erasure the operator's erasure completion finishes while the second +/// transaction waits for it is taken as it completed, an unserved group whose fan-out erasure is still open keeps the act +/// waiting, a result row that cannot be written after the provider step is the retryable unavailable, and a participant set +/// past the closure's bounds is a defect named by its closed name. +/// +public sealed partial class AccountClosureFinalizeTests +{ + /// + /// While the first transaction is held at its first redaction, the act holds the person's User key and nothing else, and + /// an identity write in each participant tenant that takes the tenant's key exclusively, as an administrator's write and + /// an erasure job do, commits within its own two-second bound. The act then finishes. + /// + [Fact] + public async Task The_first_transaction_holds_the_User_fence_alone_so_participant_tenants_write_while_it_redacts() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await BegunAsync(kit); + var gated = new GatedRedactionScope(kit.Scope()); + var finalize = kit.Owner(scope: gated).FinalizeAsync(Admission(), world.Closure); + try + { + await gated.Entered.Task.WaitAsync(TimeSpan.FromSeconds(30)); + (await kit.PlatformAdvisoryLocksAsync()).Should().Equal( + [(AccountClosureBeginKit.UserKey(world.Person), "ExclusiveLock")], + "the redaction changes no User and no request, so no participant tenant's key is held while it runs"); + + foreach (var tenant in new[] { TenantA, TenantB }) + { + var clock = Stopwatch.StartNew(); + await AdmitSomeoneElseAsync(kit, tenant).WaitAsync(TimeSpan.FromSeconds(10)); + clock.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(2), "the tenant's key was free while the act redacted"); + } + } + finally + { + gated.Release.TrySetResult(); + } + + (await finalize.WaitAsync(TimeSpan.FromSeconds(60))).Outcome.Should().Be(ClosureFinalizeOutcome.Finalized); + (await kit.UserAsync(world.Person)).Status.Should().Be("Closed"); + } + + /// + /// The operator's erasure completion finishes the person's own erasure while the second transaction waits for its row: + /// the act takes it as it completed, completes only the erasures still awaiting, and finalizes, with no defect logged. + /// + [Fact] + public async Task An_erasure_the_operator_completes_while_the_second_transaction_waits_is_taken_as_it_completed() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await OwnErasureWorldAsync(kit); + var logs = new CapturingLogger(); + NpgsqlConnection? side = null; + NpgsqlTransaction? completing = null; + var removal = new RecordingAccountRemoval + { + Probe = async () => + { + // Between the transactions: Step 2's completion of the person's own erasure, locked and written, not committed. + side = await AccountClosureBeginKit.OpenAsync(kit.Database.PlatformConnectionString); + completing = await side.BeginTransactionAsync(); + await ExecuteAsync(side, completing, """ + UPDATE public.data_subject_requests SET status = 'completed', row_version = row_version + 1 + WHERE id = @id AND status = 'awaiting_privileged_step' + """, ("id", world.OwnErasure)); + }, + }; + try + { + var finalize = kit.Owner(removal: removal, logger: logs).FinalizeAsync(Admission(), world.Closure); + await kit.WaitUntilALockIsAwaitedAsync("learnstack_platform", finalize, + "the second transaction waits for the erasure the operator's completion holds"); + await completing!.CommitAsync(); + + var result = await finalize.WaitAsync(TimeSpan.FromSeconds(30)); + + result.Outcome.Should().Be(ClosureFinalizeOutcome.Finalized); + result.Groups.Should().Be(new ClosureFinalizeTally(2, 2, 0, 0, ErasuresCompleted: 1, ClosuresCompleted: 1), + "the erasure the operator completed is ready and is not completed again"); + } + finally + { + if (completing is not null) await completing.DisposeAsync(); + if (side is not null) await side.DisposeAsync(); + } + + (await RequestStateAsync(kit, TenantWideB, world.OwnErasure)).Status.Should().Be("completed"); + (await RequestStateAsync(kit, TenantWideA, world.FanOut)).Status.Should().Be("completed"); + logs.Lines.Should().NotContain(line => line.StartsWith("7122 ", StringComparison.Ordinal), "an admitted path wrote it, so it is no defect"); + } + + /// + /// A branch archived after its fan-out erasure started is unserved, but its erasure is still open: Finalize refuses as + /// pending and writes nothing, because once the person is Closed nothing completes a fan-out erasure. Once the erasure + /// awaits its privileged step, Finalize completes it with the others. + /// + [Fact] + public async Task An_unserved_group_whose_fan_out_erasure_is_still_open_keeps_the_closure_pending_until_it_awaits() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + var tenantWide = await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + var branch = await kit.MemberAsync(TenantA, SchemaFixture.OrgA1, person, BuiltInRoleKey.Learner); + var closure = await kit.ClosureAsync(TenantA, null, person); + (await kit.Owner().BeginAsync(AccountClosureBeginKit.Admission(), closure)).Outcome.Should().Be(ClosureBeginOutcome.Begun); + var served = await FanOutErasureAsync(kit, TenantWideA, person, tenantWide, awaiting: true); + var running = await FanOutErasureAsync(kit, BranchA1, person, branch, awaiting: false); + await kit.OrganizationStatusAsync(TenantA, SchemaFixture.OrgA1, "Archived"); + var removal = new RecordingAccountRemoval(); + var admission = Admission(); + + var pending = await kit.Owner(removal: removal).FinalizeAsync(admission, closure); + + pending.Outcome.Should().Be(ClosureFinalizeOutcome.GroupsPending); + pending.Groups.Should().Be(new ClosureFinalizeTally(Served: 1, Ready: 1, Pending: 1, Unserved: 1), + "the archived branch is unserved but its fan-out erasure is open, so it is required"); + removal.Subjects.Should().BeEmpty(); + (await kit.AuditAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation); + + // Its job finishes, as it would once the branch's work resumed: written by the owner with the guards paused, because an + // archived branch takes no ordinary write. + await kit.SqlAsync($$""" + SET session_replication_role = replica; + UPDATE public.data_subject_requests SET status = 'awaiting_privileged_step', result = '{"consent_evidence":1}'::jsonb, + row_version = row_version + 2, updated_at = now(), updated_by = '{{UserId.SystemActor.Value}}' + WHERE id = '{{running}}' + """); + + var finalized = await kit.Owner(removal: removal).FinalizeAsync(Admission(), closure); + + finalized.Outcome.Should().Be(ClosureFinalizeOutcome.Finalized); + finalized.Groups.Should().Be(new ClosureFinalizeTally(1, 2, 0, 1, ErasuresCompleted: 2, ClosuresCompleted: 1), + "ready counts the required groups, the unserved one whose erasure awaited included"); + finalized.UnservedGroups.Should().Equal(BranchA1); + (await RequestStateAsync(kit, BranchA1, running)).Status.Should().Be("completed", "no fan-out erasure is stranded"); + (await RequestStateAsync(kit, TenantWideA, served)).Status.Should().Be("completed"); + } + + /// + /// The result row of the second transaction cannot be written after the provider removed the account: the act answers + /// the retryable unavailable, never the audit refusal that says the provider was not asked; the closure's state rolled + /// back with the row, and a repeat finds the account absent and finishes. + /// + [Fact] + public async Task A_result_row_refused_after_the_provider_step_is_the_retryable_unavailable_and_a_repeat_finishes() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await BegunAsync(kit); + var removal = new RecordingAccountRemoval { Answer = call => call == 1 ? AccountRemovalOutcome.Removed : AccountRemovalOutcome.Absent }; + var admission = Admission(); + + var act = () => kit.Owner(removal: removal, scope: new RefusedFinalResultScope(kit.Scope())).FinalizeAsync(admission, world.Closure); + + var failure = (await act.Should().ThrowAsync()).Which; + failure.CommitOutcomeUnknown.Should().BeFalse("the commit was never sent"); + failure.InnerException.Should().BeOfType(); + removal.Subjects.Should().ContainSingle("the account was removed before the row was refused"); + (await kit.UserAsync(world.Person)).Status.Should().Be("Closing", "the second transaction rolled back with its row"); + (await kit.RequestAsync(world.Closure)).Status.Should().Be("fulfilling"); + (await kit.AuditAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal( + PlatformAdminScope.EnterOperation, Attempt); + + var repeat = await kit.Owner(removal: removal).FinalizeAsync(Admission(), world.Closure); + + repeat.Outcome.Should().Be(ClosureFinalizeOutcome.Finalized); + (await kit.UserAsync(world.Person)).Status.Should().Be("Closed"); + } + + /// + /// A participant set past the closure's bounds, which Begin refuses and no admitted path makes once the person is Closing + /// (written here by the superuser with the guards paused, after the Begin), is refused as a defect logged by its closed + /// name alone before anything is redacted or asked: groups past the bound, and a tenant whose Memberships one redaction + /// pass refuses. + /// + [Theory] + [InlineData("participants_beyond_bound")] + [InlineData("redaction_plan_refused")] + public async Task A_participant_set_past_the_bounds_after_the_Begin_is_a_defect_named_without_the_person(string defect) + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await OwnErasureWorldAsync(kit); + var organization = Guid.CreateVersion7(); + await kit.SqlAsync(defect == "participants_beyond_bound" + ? $""" + SET session_replication_role = replica; + INSERT INTO public.organizations(id,tenant_id,slug,display_name,status,created_at,created_by,row_version) + SELECT uuidv7(), '{TenantB}', 'past-' || n, 'Past', 'Archived', clock_timestamp(), '{UserId.SystemActor.Value}', 0 + FROM generate_series(1, {GroupsPastTheBound}) AS n; + INSERT INTO public.memberships(id,tenant_id,organization_id,user_id,status,created_at,created_by) + SELECT uuidv7(), '{TenantB}', o.id, '{world.Person}', 'Active', clock_timestamp(), '{UserId.SystemActor.Value}' + FROM public.organizations AS o WHERE o.tenant_id = '{TenantB}' AND o.slug LIKE 'past-%'; + """ + : $""" + SET session_replication_role = replica; + INSERT INTO public.organizations(id,tenant_id,slug,display_name,status,created_at,created_by,row_version) + VALUES ('{organization}', '{TenantB}', 'past-tombstones', 'Past', 'Archived', clock_timestamp(), '{UserId.SystemActor.Value}', 0); + INSERT INTO public.memberships(id,tenant_id,organization_id,user_id,status,created_at,created_by,deleted_at,deleted_by) + SELECT uuidv7(), '{TenantB}', '{organization}', '{world.Person}', 'Revoked', clock_timestamp(), '{UserId.SystemActor.Value}', + clock_timestamp(), '{UserId.SystemActor.Value}' + FROM generate_series(1, {MembershipsPastTheBound}); + """); + var logs = new CapturingLogger(); + var removal = new RecordingAccountRemoval(); + var admission = Admission(); + + var act = () => kit.Owner(removal: removal, logger: logs).FinalizeAsync(admission, world.Closure); + + await act.Should().ThrowAsync(); + logs.Lines.Should().ContainSingle().Which.Should().StartWith("7122 ").And.Contain(defect).And.NotContain(world.Person.ToString("D")); + removal.Subjects.Should().BeEmpty("the provider is never asked for a closure past its bounds"); + (await kit.AuditAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal( + [PlatformAdminScope.EnterOperation], "nothing was redacted and no intent row was written"); + (await kit.UserAsync(world.Person)).Status.Should().Be("Closing"); + } + + /// + /// Begin's grouped participant read uses the person's Membership index, never a tenant's or a group's, whatever the + /// other people of the person's groups hold. + /// + [Fact] + public async Task Begins_participant_read_counts_the_person_s_Memberships_through_the_person_s_index() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + await kit.SqlAsync($""" + SET session_replication_role = replica; + INSERT INTO public.memberships(id,tenant_id,organization_id,user_id,status,created_at,created_by) + SELECT uuidv7(), '{TenantB}', NULL, uuidv7(), 'Active', clock_timestamp(), '{UserId.SystemActor.Value}' + FROM generate_series(1, 4000); + ANALYZE public.memberships; + """); + await using var platform = await AccountClosureBeginKit.OpenAsync(kit.Database.PlatformConnectionString); + await using var command = new NpgsqlCommand( + "SET enable_seqscan = off; EXPLAIN (FORMAT JSON) " + AccountClosureOperatorOperations.ParticipantsSql, platform); + command.Parameters.AddWithValue("subject", IdentityMembershipFixture.PersonA); + command.Parameters.AddWithValue("limit", GroupsPastTheBound); + + var plan = (await command.ExecuteScalarAsync())!.ToString()!; + + plan.Should().Contain("ix_memberships_user_id").And.NotContain("Seq Scan"); + } + + /// One group past the closure's bound. + private const int GroupsPastTheBound = LearnStack.SharedKernel.DataProtection.ClosureLimits.MaximumParticipantGroups + 1; + + /// One Membership past what one tenant pass of the redaction compares. + private const int MembershipsPastTheBound = LearnStack.SharedKernel.DataProtection.ClosureLimits.MaximumTenantMemberships + 1; + + /// A begun closure whose tenant B group stands on the person's own erasure, which awaits the privileged step. + private sealed record OwnErasureWorld(Guid Person, Guid Closure, Guid FanOut, Guid OwnErasure); + + /// + /// A person in tenant A's and tenant B's tenant-wide groups with their own erasure of tenant B already awaiting the + /// privileged step (the fan-out adopts it as it is), a due closure filed in tenant A, the Begin, and tenant A's fan-out + /// erasure awaiting the privileged step. + /// + private static async Task OwnErasureWorldAsync(AccountClosureBeginKit kit) + { + var person = await kit.PersonAsync(); + var tenantWide = await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + await kit.MemberAsync(TenantB, null, person, BuiltInRoleKey.Learner); + var own = await kit.RequestRowAsync(TenantB, person, "erasure", "awaiting_privileged_step"); + var closure = await kit.ClosureAsync(TenantA, null, person); + (await kit.Owner().BeginAsync(AccountClosureBeginKit.Admission(), closure)).Outcome.Should().Be(ClosureBeginOutcome.Begun); + var fanOut = await FanOutErasureAsync(kit, TenantWideA, person, tenantWide, awaiting: true); + return new OwnErasureWorld(person, closure, fanOut, own); + } + + /// + /// Another person's Membership in the tenant, admitted as an administrator admits one: under that person's User key and + /// the tenant's key exclusively, each wait bounded as the application's own writers bound it. + /// + private static async Task AdmitSomeoneElseAsync(AccountClosureBeginKit kit, Guid tenant) + { + var someone = await kit.PersonAsync(); + await using var app = await DataExportTestKit.OpenAppAsync(kit.Database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant); + await ExecuteAsync(app, transaction, "SET LOCAL lock_timeout = '2s'"); + await LockAsync(app, transaction, tenant, someone, exclusive: true); + await InsertMemberAsync(app, transaction, tenant, null, Guid.CreateVersion7(), someone, + RoleId(tenant, BuiltInRoleKey.Learner, PermissionScope.Tenant)); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await transaction.CommitAsync(); + } + + /// The real scope with a handle that refuses the act's final result row as an unavailable audit store does. + private sealed class RefusedFinalResultScope(IPlatformAdminScope inner) : IPlatformAdminScope + { + public async Task EnterAsync( + PlatformAdmission admission, CancellationToken cancellationToken = default, + [System.Runtime.CompilerServices.CallerMemberName] string? callerMember = null, + [System.Runtime.CompilerServices.CallerFilePath] string? callerFile = null, + [System.Runtime.CompilerServices.CallerLineNumber] int callerLine = 0) => + new Handle(await inner.EnterAsync(admission, cancellationToken, callerMember, callerFile, callerLine)); + + private sealed class Handle(IPlatformAdminScopeHandle real) : ForwardingHandle(real) + { + public override Task WriteResultAsync(PlatformResult result, CancellationToken cancellationToken = default) => + result.AfterState?.Contains("\"finalized\"", StringComparison.Ordinal) == true + ? Task.FromException(new AuditWriteFailedException("forced refusal of the final result row")) + : base.WriteResultAsync(result, cancellationToken); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureFinalizeTests.Races.cs b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureFinalizeTests.Races.cs new file mode 100644 index 000000000..9613b7cc7 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureFinalizeTests.Races.cs @@ -0,0 +1,298 @@ +using System.Diagnostics; +using System.Text.Json.Nodes; +using FluentAssertions; +using LearnStack.Infrastructure.MultiTenancy; +using LearnStack.Modules.Identity.Infrastructure.DataRequests; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The Finalize's concurrency and failure seams: a group made pending between its two transactions, a fence another act +/// holds past the bound, a commit whose answer is lost before and after it landed, a Membership admission racing the first +/// transaction, and the plans of the statements it adds. +/// +public sealed partial class AccountClosureFinalizeTests +{ + /// + /// The second transaction judges again under its own fences: a served group made pending while the provider was being + /// called (here its erasure set back to running by the owner) stops the act after the account's deletion with the + /// person still Closing, records where it stopped, and a repeat once the group is ready finds the account absent and + /// finishes. + /// + [Fact] + public async Task A_group_made_pending_between_the_two_transactions_is_found_again_under_the_second_fences() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await BegunAsync(kit); + var erasure = world.Erasures[TenantWideB]; + var removal = new RecordingAccountRemoval + { + Answer = call => call == 1 ? AccountRemovalOutcome.Removed : AccountRemovalOutcome.Absent, + Probe = () => kit.SqlAsync( + $"SET session_replication_role = replica; UPDATE public.data_subject_requests SET status = 'fulfilling' WHERE id = '{erasure}'"), + }; + var admission = Admission(); + + var stopped = await kit.Owner(removal: removal).FinalizeAsync(admission, world.Closure); + + stopped.Outcome.Should().Be(ClosureFinalizeOutcome.GroupsPending); + stopped.Groups.Should().Be(new ClosureFinalizeTally(Served: 3, Ready: 2, Pending: 1, Unserved: 1)); + (await kit.UserAsync(world.Person)).Should().Match(row => row.Status == "Closing" && row.SubjectPresent, + "nothing of the second transaction committed"); + (await kit.RequestAsync(world.Closure)).Status.Should().Be("fulfilling"); + foreach (var group in new[] { TenantWideA, BranchA1 }) + (await RequestStateAsync(kit, group, world.Erasures[group])).Status.Should().Be("awaiting_privileged_step"); + var rows = await kit.AuditAsync(admission.Operator.CorrelationId!); + rows.Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation, Attempt, Result); + var recorded = JsonNode.Parse(rows[^1].After)!; + (recorded["outcome"]!.GetValue(), recorded["provider"]!.GetValue(), recorded["groups"]!["pending"]!.GetValue()) + .Should().Be(("groups_pending", "removed", 1)); + + removal.Probe = null; + await kit.SqlAsync( + $"SET session_replication_role = replica; UPDATE public.data_subject_requests SET status = 'awaiting_privileged_step' WHERE id = '{erasure}'"); + var finished = await kit.Owner(removal: removal).FinalizeAsync(Admission(), world.Closure); + + finished.Outcome.Should().Be(ClosureFinalizeOutcome.Finalized); + (await kit.UserAsync(world.Person)).Status.Should().Be("Closed"); + removal.Subjects.Should().HaveCount(2); + } + + /// + /// A fence another act holds past the bound answers the retryable unavailable within the bound, with no commit sent. The + /// person's User key is the first transaction's: the provider is never asked and the entry row is the only record. A + /// participant tenant's key is the second transaction's alone: the first redacted and recorded its intent and the + /// provider removed the account, and the second then waited and rolled back, leaving the person Closing. + /// + [Theory] + [InlineData("user")] + [InlineData("tenant")] + public async Task A_fence_held_past_the_bound_is_the_retryable_unavailable_and_changes_nothing(string held) + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await BegunAsync(kit); + var removal = new RecordingAccountRemoval { Answer = call => call == 1 ? AccountRemovalOutcome.Removed : AccountRemovalOutcome.Absent }; + await using var holder = await AccountClosureBeginKit.OpenAsync(kit.Database.PlatformConnectionString); + await using var holding = await holder.BeginTransactionAsync(); + await ExecuteAsync(holder, holding, "SELECT pg_catalog.pg_advisory_xact_lock(@key)", + ("key", held == "user" ? AccountClosureBeginKit.UserKey(world.Person) : AccountClosureBeginKit.TenantKey(TenantB))); + var admission = Admission(); + var clock = Stopwatch.StartNew(); + + var act = () => kit.Owner(removal: removal).FinalizeAsync(admission, world.Closure); + + var failure = (await act.Should().ThrowAsync()).Which; + failure.CommitOutcomeUnknown.Should().BeFalse("no commit was sent"); + clock.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(15), "each key waits at most three seconds"); + var rows = (await kit.AuditAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation); + if (held == "user") + { + removal.Subjects.Should().BeEmpty(); + rows.Should().Equal(PlatformAdminScope.EnterOperation); + } + else + { + removal.Subjects.Should().ContainSingle("the first transaction never waits for a participant tenant's key"); + rows.Should().Equal(PlatformAdminScope.EnterOperation, Attempt); + } + + (await kit.UserAsync(world.Person)).Status.Should().Be("Closing", "nothing of the second transaction committed"); + await holding.RollbackAsync(); + + (await kit.Owner(removal: removal).FinalizeAsync(Admission(), world.Closure)).Outcome.Should().Be(ClosureFinalizeOutcome.Finalized, + "the repeat after the other act let go finishes"); + } + + /// + /// A final commit whose answer is lost is the unknown outcome whether or not it landed: one that was never sent leaves + /// the closure fulfilling and a repeat finishes it; one that landed leaves it completed and a repeat answers + /// already_finalized. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task A_lost_final_commit_is_the_unknown_outcome_and_a_repeat_finds_what_landed(bool landed) + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await BegunAsync(kit); + var removal = new RecordingAccountRemoval { Answer = call => call == 1 ? AccountRemovalOutcome.Removed : AccountRemovalOutcome.Absent }; + IPlatformAdminScope lost = landed ? new LandedLostCommitScope(kit.Scope()) : new LostCommitScope(kit.Scope()); + + var act = () => kit.Owner(removal: removal, scope: lost).FinalizeAsync(Admission(), world.Closure); + + (await act.Should().ThrowAsync()).Which.CommitOutcomeUnknown.Should().BeTrue( + "the final commit was sent, so it may have landed"); + (await kit.UserAsync(world.Person)).Status.Should().Be(landed ? "Closed" : "Closing"); + + var repeat = await kit.Owner(removal: removal).FinalizeAsync(Admission(), world.Closure); + + repeat.Outcome.Should().Be(landed ? ClosureFinalizeOutcome.AlreadyFinalized : ClosureFinalizeOutcome.Finalized); + (await kit.UserAsync(world.Person)).Status.Should().Be("Closed"); + removal.Subjects.Should().HaveCount(landed ? 1 : 2, "a landed finalization asks the provider nothing again"); + } + + /// + /// A Membership admission for the person in a tenant of theirs, started while the first transaction holds the fences, + /// waits for the person's User key, never deadlocks with the act, and once the act's checkpoint released the keys is + /// refused by the database because the person is Closing. The act then finishes with the participants it read. + /// + [Fact] + public async Task A_Membership_admission_racing_the_first_transaction_waits_and_is_refused_by_the_Closing_person() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await BegunAsync(kit); + var gated = new GatedRedactionScope(kit.Scope()); + var finalize = kit.Owner(scope: gated).FinalizeAsync(Admission(), world.Closure); + await gated.Entered.Task.WaitAsync(TimeSpan.FromSeconds(30)); + + await using var app = await DataExportTestKit.OpenAppAsync(kit.Database.AppConnectionString); + await using var admission = await app.BeginTransactionAsync(); + await ScopeAsync(app, admission, TenantB, SchemaFixture.OrgB1); + var waiting = LockAsync(app, admission, TenantB, world.Person, false); + try + { + await kit.WaitUntilALockIsAwaitedAsync("learnstack_app", waiting, "the admission waits for the person's User key"); + } + finally + { + gated.Release.TrySetResult(); + } + + await waiting.WaitAsync(TimeSpan.FromSeconds(30)); + var insert = () => InsertMemberAsync(app, admission, TenantB, SchemaFixture.OrgB1, Guid.CreateVersion7(), world.Person, + RoleId(TenantB, BuiltInRoleKey.Learner, PermissionScope.Tenant)); + var refused = (await insert.Should().ThrowAsync()).Which; + (refused.SqlState, refused.MessageText).Should().Be(("P0302", "identity membership target is unavailable")); + await admission.RollbackAsync(); + + var result = await finalize.WaitAsync(TimeSpan.FromSeconds(30)); + result.Outcome.Should().Be(ClosureFinalizeOutcome.Finalized); + result.Groups!.Served.Should().Be(3, "the refused admission added no group"); + } + + /// + /// The statements Finalize adds read the person's own rows through the person's indexes, never a group's or a tenant's + /// whole history: the readiness read and the open-closure read through the request subject index, the Membership reads + /// through the Membership user index. Thousands of other people's requests and Memberships in the same groups make a + /// scan by group visibly worse than one by person. + /// + [Fact] + public async Task The_Finalize_statements_read_the_person_s_rows_through_the_person_s_indexes() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await BegunAsync(kit); + await kit.SqlAsync($""" + SET session_replication_role = replica; + INSERT INTO public.memberships(id,tenant_id,organization_id,user_id,status,created_at,created_by) + SELECT uuidv7(), '{TenantB}', NULL, uuidv7(), 'Active', clock_timestamp(), '{UserId.SystemActor.Value}' + FROM generate_series(1, 4000); + 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) + SELECT uuidv7(), '{TenantB}', NULL, 'erasure', 'self', member.user_id, member.user_id, 'cancelled', + jsonb_build_array(member.id::text), now(), now() - interval '24 hours', member.user_id, 1 + FROM public.memberships AS member WHERE member.tenant_id = '{TenantB}' AND member.user_id <> '{world.Person}'; + ANALYZE public.memberships; + ANALYZE public.data_subject_requests; + """); + await using var platform = await AccountClosureBeginKit.OpenAsync(kit.Database.PlatformConnectionString); + + async Task Plan(string sql) + { + await using var command = new NpgsqlCommand("SET enable_seqscan = off; EXPLAIN (FORMAT JSON) " + sql, platform); + command.Parameters.AddWithValue("subject", world.Person); + command.Parameters.AddWithValue("began", DateTimeOffset.UtcNow); + command.Parameters.AddWithValue("limit", 1025); + command.Parameters.AddWithValue("id", world.Closure); + return (await command.ExecuteScalarAsync())!.ToString()!; + } + + var readiness = await Plan(AccountClosureOperatorOperations.ReadinessSql); + readiness.Should().Contain("ix_data_subject_requests_subject_user_id").And.Contain("ix_memberships_user_id").And.NotContain("Seq Scan"); + (await Plan(AccountClosureOperatorOperations.MembershipsSql)).Should().Contain("ix_memberships_user_id").And.NotContain("Seq Scan"); + (await Plan(AccountClosureOperatorOperations.OpenClosuresSql)).Should().Contain("ix_data_subject_requests_subject_user_id") + .And.NotContain("Seq Scan"); + } + + /// The real scope with a handle whose final commit lands and whose answer is then lost. + private sealed class LandedLostCommitScope(IPlatformAdminScope inner) : IPlatformAdminScope + { + public async Task EnterAsync( + PlatformAdmission admission, CancellationToken cancellationToken = default, + [System.Runtime.CompilerServices.CallerMemberName] string? callerMember = null, + [System.Runtime.CompilerServices.CallerFilePath] string? callerFile = null, + [System.Runtime.CompilerServices.CallerLineNumber] int callerLine = 0) => + new Handle(await inner.EnterAsync(admission, cancellationToken, callerMember, callerFile, callerLine)); + + private sealed class Handle(IPlatformAdminScopeHandle real) : ForwardingHandle(real) + { + public override async Task CommitAsync(CancellationToken cancellationToken = default) + { + await base.CommitAsync(cancellationToken); + throw new TimeoutException("forced lost answer after the commit landed"); + } + } + } + + /// + /// The real scope with a handle that holds the act at its first redaction, when the first transaction holds every + /// fence and has written nothing, until the test releases it. + /// + private sealed class GatedRedactionScope(IPlatformAdminScope inner) : IPlatformAdminScope + { + public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public async Task EnterAsync( + PlatformAdmission admission, CancellationToken cancellationToken = default, + [System.Runtime.CompilerServices.CallerMemberName] string? callerMember = null, + [System.Runtime.CompilerServices.CallerFilePath] string? callerFile = null, + [System.Runtime.CompilerServices.CallerLineNumber] int callerLine = 0) => + new Handle(await inner.EnterAsync(admission, cancellationToken, callerMember, callerFile, callerLine), this); + + private sealed class Handle(IPlatformAdminScopeHandle real, GatedRedactionScope gate) : ForwardingHandle(real) + { + public override async Task RedactAuditAsync(AuditRedactionPlan plan, CancellationToken cancellationToken = default) + { + if (gate.Entered.TrySetResult()) + { + await gate.Release.Task; + } + + return await base.RedactAuditAsync(plan, cancellationToken); + } + } + } + + private abstract class ForwardingHandle(IPlatformAdminScopeHandle real) : IPlatformAdminScopeHandle + { + public Task ExecuteAsync(string sql, IReadOnlyList? parameters = null, CancellationToken cancellationToken = default) => + real.ExecuteAsync(sql, parameters, cancellationToken); + + public Task> QueryAsync( + string sql, IReadOnlyList? parameters, Func map, + CancellationToken cancellationToken = default) => real.QueryAsync(sql, parameters, map, cancellationToken); + + public Task WriteIntentAsync(PlatformResult intent, CancellationToken cancellationToken = default) => + real.WriteIntentAsync(intent, cancellationToken); + + public virtual Task RedactAuditAsync(AuditRedactionPlan plan, CancellationToken cancellationToken = default) => + real.RedactAuditAsync(plan, cancellationToken); + + public virtual Task WriteResultAsync(PlatformResult result, CancellationToken cancellationToken = default) => + real.WriteResultAsync(result, cancellationToken); + + public virtual Task CommitAsync(CancellationToken cancellationToken = default) => real.CommitAsync(cancellationToken); + + public ValueTask DisposeAsync() => real.DisposeAsync(); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureFinalizeTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureFinalizeTests.cs new file mode 100644 index 000000000..b4b1c1e0f --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureFinalizeTests.cs @@ -0,0 +1,521 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using FluentAssertions; +using LearnStack.Infrastructure.MultiTenancy; +using LearnStack.Modules.Identity.Infrastructure.DataRequests; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Platform; +using LearnStack.Tests.Fixtures; +using Microsoft.Extensions.Logging; +using Npgsql; +using NpgsqlTypes; +using Xunit; +using static LearnStack.Tests.Integration.Database.DataRequestSchemaSeed; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The closure's Finalize owner (ADR-0107 § 7, ADR-0108 § 8) against a real database, the real platform scope with the real +/// audit store and the real redaction executor over the production locators, the real Tenancy lifecycle read, the request +/// guard's closure arms and the users trigger exception. The identity provider is a recording stand-in; each group's +/// fan-out erasure is written as the group's act and its job leave it, by the application role under the canonical fences. +/// Every statement of the act runs as learnstack_platform through the scope. +/// +/// +/// +/// Each test runs in its own disposable copy of the seeded schema and closes a fresh person, because a User a closure moved +/// never returns to Active. The person holds Memberships in tenant A's tenant-wide group and branch A1 and in tenant B's +/// tenant-wide group (three served groups) and in branch A2, which is archived after the person filed (unserved). Their +/// closure was filed in tenant A's tenant-wide group and is due; a second closure, filed in tenant B and still in its +/// window, was never begun. +/// +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed partial class AccountClosureFinalizeTests(SchemaFixture schema) +{ + private const string Attempt = "platform.closure.finalize_attempt"; + private const string Result = "platform.closure.finalize"; + private static readonly Guid TenantA = SchemaFixture.TenantA; + private static readonly Guid TenantB = SchemaFixture.TenantB; + private static readonly ClosureParticipantGroup TenantWideA = new(TenantId.From(TenantA), null); + private static readonly ClosureParticipantGroup BranchA1 = new(TenantId.From(TenantA), OrganizationId.From(SchemaFixture.OrgA1)); + private static readonly ClosureParticipantGroup BranchA2 = new(TenantId.From(TenantA), OrganizationId.From(SchemaFixture.OrgA2)); + private static readonly ClosureParticipantGroup TenantWideB = new(TenantId.From(TenantB), null); + private static readonly ClosureParticipantGroup[] Served = [TenantWideA, BranchA1, TenantWideB]; + + /// + /// The whole act: the first transaction redacts every participant tenant and the sentinel and commits with the intent + /// row; the provider is called with the raw subject between the transactions, while no fence and no transaction is + /// held; the second moves the User to Closed with the raw subject removed, completes every served group's erasure, the + /// closure and the person's never-begun second closure, and commits with the result row. A repeat answers what was + /// recorded and writes nothing but its entry row. No state, log line or answer names the person or the raw subject. + /// + [Fact] + public async Task A_Finalize_redacts_removes_the_account_closes_the_person_and_completes_every_open_request_in_two_transactions() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await BegunAsync(kit); + var removal = new RecordingAccountRemoval(); + var logs = new CapturingLogger(); + var between = new List(); + var scope = new TappedScope(kit.Scope()) { RecordBackend = true }; + removal.Probe = async () => + { + // Between the transactions: the redaction and its intent row committed, nothing else moved, and the platform + // connection holds no fence and no open transaction while the provider call runs. + (await kit.UserAsync(world.Person)).Status.Should().Be("Closing"); + (await kit.RequestAsync(world.Closure)).Status.Should().Be("fulfilling"); + (await kit.PlatformAdvisoryLocksAsync()).Should().BeEmpty("the first transaction's keys ended at its commit"); + between.Add(await BackendStateAsync(kit, scope.Backend!.Value)); + (await PlantedAsync(kit, world)).Values.Should().OnlyContain(row => row.Address == null && row.Agent == null && row.Email == null, + "the redaction committed with the intent row, before the provider call"); + }; + var keyBefore = await SubjectKeyAsync(kit, world.Person); + var admission = Admission("INC-801"); + + var result = await kit.Owner(removal: removal, logger: logs, scope: scope).FinalizeAsync(admission, world.Closure); + + result.Outcome.Should().Be(ClosureFinalizeOutcome.Finalized); + result.Status.Should().Be("completed"); + result.Groups.Should().Be(new ClosureFinalizeTally(Served: 3, Ready: 3, Pending: 0, Unserved: 1, ErasuresCompleted: 3, ClosuresCompleted: 2)); + result.UnservedGroups.Should().Equal(BranchA2); + result.Redaction!.Tenants.Keys.Should().BeEquivalentTo([TenantId.From(TenantA), TenantId.From(TenantB)], + "both tenants hold a served group here (the unserved branch belongs to tenant A, which two served groups name), so this " + + "proves the served tenants; " + nameof(A_tenant_whose_only_group_is_unserved_is_redacted_like_every_other_participant_tenant) + + " proves the tenant whose only group is unserved"); + result.Redaction.Total.Redacted[AuditRedactedColumn.IpAddress].Should().Be(3, "the two planted tenant rows and the sentinel one"); + result.Retained.Should().ContainKey("unserved_group").WhoseValue.Should().Be(1); + removal.Subjects.Should().Equal([world.ProviderSubject], "the raw subject is read once and passed to the port"); + between.Should().Equal(["idle"], "the act's own backend, read by its process, is idle while the provider runs: the transaction " + + "the checkpoint opened is not begun on the server until its first statement"); + + // The person: Closed, the raw subject gone, the key and the creation evidence kept as the tombstone. + var user = await kit.UserAsync(world.Person); + (user.Status, user.SubjectPresent).Should().Be(("Closed", false)); + (await SubjectKeyAsync(kit, world.Person)).Should().Be(keyBefore, "the subject key is the permanent tombstone"); + (await CreationRowsAsync(kit, world.Person)).Should().Be(1, "the creation row stays, redacted, never deleted"); + + // Every served group's erasure completed with its tenant's retained audit kinds; the closure and the second one too. + foreach (var group in Served) + { + var erasure = await RequestStateAsync(kit, group, world.Erasures[group]); + erasure.Status.Should().Be("completed", group.ToString()); + var recorded = JsonNode.Parse(erasure.Result)!.AsObject(); + recorded["consent_evidence"]!.GetValue().Should().Be(2, "the tenant side's record stays as its participants wrote it"); + AssertRetainedCounts(recorded, result.Redaction.Tenants[group.TenantId], $"{group}: the redaction's retained kinds replace the job's"); + recorded["audit_actor_reference"]!.GetValue().Should().NotBe(9, "the job's own count of the kind is replaced, not kept"); + } + + foreach (var (group, closure) in new[] { (TenantWideA, world.Closure), (TenantWideB, world.SecondClosure) }) + { + var completed = await RequestStateAsync(kit, group, closure); + completed.Status.Should().Be("completed", "the never-begun second closure completes with the one finalized"); + var recordedClosure = JsonNode.Parse(completed.Result)!.AsObject(); + recordedClosure["unserved_group"]!.GetValue().Should().Be(1); + AssertRetainedCounts(recordedClosure, result.Redaction.Total, "a closure records the total of every pass"); + } + + // The evidence: the entry, the intent with the summed counts and the result, all under the sentinel with the ticket. + var rows = await kit.AuditAsync(admission.Operator.CorrelationId!); + rows.Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation, Attempt, Result); + rows.Should().OnlyContain(row => row.Tenant == TenantId.PlatformSentinel.Value && row.Actor == null + && row.Reason == "closure_finalize" && row.Metadata.Contains("INC-801")); + var intent = rows.Single(row => row.Operation == Attempt); + JsonNode.DeepEquals(JsonNode.Parse(intent.After), JsonNode.Parse(result.Redaction.ToClosedJson())).Should().BeTrue(intent.After); + var recordedResult = JsonNode.Parse(rows.Single(row => row.Operation == Result).After)!; + recordedResult["outcome"]!.GetValue().Should().Be("finalized"); + recordedResult["account"]!.GetValue().Should().Be("closed"); + recordedResult["provider"]!.GetValue().Should().Be("removed"); + recordedResult["groups"]!["closures_completed"]!.GetValue().Should().Be(2); + foreach (var row in rows) + { + (row.Before + row.After + row.Metadata).Should().NotContain(world.Person.ToString("D")).And.NotContain(world.ProviderSubject) + .And.NotContain(keyBefore, "no row of the act names the person, the raw subject or the key"); + } + + string.Join(' ', JsonSerializer.Serialize(result.Groups), JsonSerializer.Serialize(result.Retained), result.Redaction.ToClosedJson(), + string.Join(',', result.UnservedGroups!.Select(group => group.TenantId.Value + "/" + group.OrganizationId?.Value))) + .Should().NotContain(world.Person.ToString("D")).And.NotContain(world.ProviderSubject, "the answer names no person"); + logs.Lines.Should().NotContain(line => line.Contains(world.Person.ToString("D"), StringComparison.Ordinal) + || line.Contains(world.ProviderSubject, StringComparison.Ordinal) || line.Contains("INC-801", StringComparison.Ordinal)); + + // A repeat finds what landed: it answers the recorded result, asks the provider nothing and writes only its entry row. + var repeat = Admission("INC-802"); + var again = await kit.Owner(removal: removal).FinalizeAsync(repeat, world.Closure); + again.Outcome.Should().Be(ClosureFinalizeOutcome.AlreadyFinalized); + again.Retained.Should().BeEquivalentTo(result.Retained); + AssertRetainedCounts(again.Retained!, result.Redaction.Total, "a repeat answers the closure's recorded counts, by value"); + removal.Subjects.Should().HaveCount(1); + (await kit.AuditAsync(repeat.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation); + } + + /// + /// The provider's three stops and a port that throws: each leaves the person Closing and the closure fulfilling, with + /// the redaction committed under its intent row and a result row saying where the act stopped. A repeat redacts again, + /// which changes no row, writes its own intent row, finds the account absent, which is success, and finalizes. + /// + [Theory] + [InlineData(AccountRemovalOutcome.Refused, ClosureFinalizeOutcome.ProviderRefused, "provider_refused")] + [InlineData(AccountRemovalOutcome.Unavailable, ClosureFinalizeOutcome.ProviderUnavailable, "provider_unavailable")] + [InlineData(AccountRemovalOutcome.Uncertain, ClosureFinalizeOutcome.ProviderUncertain, "provider_uncertain")] + [InlineData((AccountRemovalOutcome)0, ClosureFinalizeOutcome.ProviderUncertain, "provider_uncertain")] + public async Task A_provider_stop_leaves_the_closure_fulfilling_with_its_evidence_and_a_repeat_finishes_it( + AccountRemovalOutcome stop, ClosureFinalizeOutcome expected, string token) + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await BegunAsync(kit); + var removal = new RecordingAccountRemoval { Answer = call => call == 1 ? stop : AccountRemovalOutcome.Absent }; + if (stop == 0) + { + removal.Failure = new HttpRequestException("the transport failed after the deletion may have been sent"); + } + + var logs = new CapturingLogger(); + var first = Admission("INC-811"); + + var stopped = await kit.Owner(removal: removal, logger: logs).FinalizeAsync(first, world.Closure); + + stopped.Outcome.Should().Be(expected); + stopped.Status.Should().Be("fulfilling"); + (await kit.UserAsync(world.Person)).Should().Match(row => row.Status == "Closing" && row.SubjectPresent); + (await kit.RequestAsync(world.Closure)).Status.Should().Be("fulfilling"); + foreach (var group in Served) + (await RequestStateAsync(kit, group, world.Erasures[group])).Status.Should().Be("awaiting_privileged_step"); + var rows = await kit.AuditAsync(first.Operator.CorrelationId!); + rows.Select(row => (row.Operation, row.After.Contains(token, StringComparison.Ordinal))).Should().Equal( + (PlatformAdminScope.EnterOperation, false), (Attempt, false), (Result, true)); + logs.Lines.Should().Contain(line => line.Contains(token, StringComparison.Ordinal)); + logs.Lines.Should().NotContain(line => line.Contains(world.ProviderSubject, StringComparison.Ordinal) + || line.Contains("deletion may have been sent", StringComparison.Ordinal)); + var redacted = await PlantedAsync(kit, world); + redacted.Values.Should().OnlyContain(row => row.Address == null, "the redaction committed before the provider was asked"); + + removal.Failure = null; + var second = Admission("INC-812"); + var finished = await kit.Owner(removal: removal).FinalizeAsync(second, world.Closure); + + finished.Outcome.Should().Be(ClosureFinalizeOutcome.Finalized); + finished.Redaction!.Total.Redacted.Values.Should().AllSatisfy(count => count.Should().Be(0, "a repeat's redaction changes no row")); + (await PlantedAsync(kit, world)).Should().BeEquivalentTo(redacted, "the second run rewrote nothing"); + (await kit.UserAsync(world.Person)).Status.Should().Be("Closed"); + removal.Subjects.Should().Equal([world.ProviderSubject, world.ProviderSubject]); + var repeated = await kit.AuditAsync(second.Operator.CorrelationId!); + repeated.Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation, Attempt, Result); + JsonNode.Parse(repeated[^1].After)!["provider"]!.GetValue().Should().Be("absent", "a missing account is success"); + } + + /// + /// Every served group must be ready, and nothing is written while one is not: a group whose fan-out erasure is still + /// running, a group with no erasure, a group whose newest erasure completed before this closure began (a person admitted + /// again since), and a group whose erasure does not cover a Membership the person holds there. The provider is never + /// asked and the scope's entry row is the only record. + /// + [Theory] + [InlineData("running")] + [InlineData("missing")] + [InlineData("completed_before_begin")] + [InlineData("snapshot_short")] + public async Task A_Finalize_before_every_served_group_is_ready_answers_closed_tallies_and_writes_nothing(string variant) + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await BegunAsync(kit, pendingGroup: TenantWideB, variant: variant); + var removal = new RecordingAccountRemoval(); + var admission = Admission(); + + var result = await kit.Owner(removal: removal).FinalizeAsync(admission, world.Closure); + + result.Outcome.Should().Be(ClosureFinalizeOutcome.GroupsPending, variant); + result.Status.Should().Be("fulfilling"); + result.Groups.Should().Be(new ClosureFinalizeTally(Served: 3, Ready: 2, Pending: 1, Unserved: 1)); + result.UnservedGroups.Should().BeNull("a refusal names no group"); + removal.Subjects.Should().BeEmpty("the provider is asked only once every served group is ready"); + (await kit.AuditAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should().Equal(PlatformAdminScope.EnterOperation); + (await PlantedAsync(kit, world)).Values.Should().OnlyContain(row => row.Address != null, "nothing was redacted"); + (await kit.UserAsync(world.Person)).Status.Should().Be("Closing"); + } + + /// + /// The guard of the stale erasure hazard, from the other side: a person's own erasure that awaited its privileged step when + /// the closure began and was completed by the operator's erasure completion after it stands for its group, and Finalize + /// leaves it as it completed. + /// + [Fact] + public async Task An_erasure_completed_after_the_closure_began_stands_for_its_group() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var world = await BegunAsync(kit, pendingGroup: TenantWideB, variant: "completed_after_begin"); + + var result = await kit.Owner().FinalizeAsync(Admission(), world.Closure); + + result.Outcome.Should().Be(ClosureFinalizeOutcome.Finalized); + result.Groups.Should().Be(new ClosureFinalizeTally(3, 3, 0, 1, ErasuresCompleted: 2, ClosuresCompleted: 2), + "the group's erasure was already completed and is not completed again"); + } + + /// + /// Requests that are not begun closures are refused before any fence, the provider is never asked, and the scope's entry + /// row is the only record: no request, an export, an erasure, a closure never begun and a cancelled one. + /// + [Fact] + public async Task Requests_that_are_not_begun_closures_are_refused_before_any_fence_and_write_nothing() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + var export = await kit.RequestRowAsync(TenantA, person, "export", "requested"); + var erasure = await kit.RequestRowAsync(TenantA, person, "erasure", "awaiting_privileged_step"); + var cancelled = await kit.RequestRowAsync(TenantA, person, "closure", "cancelled"); + var scheduled = await kit.ClosureAsync(TenantA, null, person); + var removal = new RecordingAccountRemoval(); + + foreach (var (request, outcome, status) in new (Guid, ClosureFinalizeOutcome, string?)[] + { + (Guid.CreateVersion7(), ClosureFinalizeOutcome.NotFound, null), + (export, ClosureFinalizeOutcome.NotClosure, "requested"), + (erasure, ClosureFinalizeOutcome.NotClosure, "awaiting_privileged_step"), + (cancelled, ClosureFinalizeOutcome.NotFinalizable, "cancelled"), + (scheduled, ClosureFinalizeOutcome.NotFinalizable, "scheduled"), + }) + { + var admission = Admission(); + var result = await kit.Owner(removal: removal).FinalizeAsync(admission, request); + (result.Outcome, result.Status).Should().Be((outcome, status), outcome.ToString()); + (await kit.AuditAsync(admission.Operator.CorrelationId!)).Select(row => row.Operation).Should() + .Equal([PlatformAdminScope.EnterOperation], "a refusal writes nothing beyond the entry row"); + } + + removal.Subjects.Should().BeEmpty(); + (await kit.UserAsync(person)).Status.Should().Be("Active"); + } + + /// + /// A state no admitted path writes is refused closed and logged by its closed name alone: a closure fulfilling while its + /// person is Active (here forced by the owner with the guards paused). + /// + [Fact] + public async Task A_fulfilling_closure_whose_person_is_not_Closing_is_a_defect_logged_without_the_person() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var person = await kit.PersonAsync(); + await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner); + var closure = await kit.RequestRowAsync(TenantA, person, "closure", "fulfilling"); + var logs = new CapturingLogger(); + var removal = new RecordingAccountRemoval(); + + var act = () => kit.Owner(removal: removal, logger: logs).FinalizeAsync(Admission(), closure); + + await act.Should().ThrowAsync(); + logs.Lines.Should().ContainSingle().Which.Should().Contain("fulfilling_closure_account_not_closing") + .And.NotContain(person.ToString("D")); + removal.Subjects.Should().BeEmpty(); + } + + private static PlatformAdmission Admission(string? ticket = null) => TestPlatformAdmissions.Admission( + PlatformOperations.ClosureFinalize, ticket, correlationId: "00-closure-finalize-" + Guid.NewGuid().ToString("N")); + + /// A begun closure and where its groups stand, and the planted audit rows that name the person. + private sealed record World( + Guid Person, string ProviderSubject, Guid Closure, Guid SecondClosure, Dictionary Erasures, + Dictionary Planted); + + /// + /// The person, their Memberships, the due closure and the second one in its window, the archived branch, the Begin, and + /// each served group's fan-out erasure awaiting the privileged step, unless is left as + /// says. One row in each participant tenant and one in the sentinel name the person as actor. + /// + private static async Task BegunAsync( + AccountClosureBeginKit kit, ClosureParticipantGroup? pendingGroup = null, string variant = "ready") + { + var person = await kit.PersonAsync(); + var memberships = new Dictionary + { + [TenantWideA] = await kit.MemberAsync(TenantA, null, person, BuiltInRoleKey.Learner), + [BranchA1] = await kit.MemberAsync(TenantA, SchemaFixture.OrgA1, person, BuiltInRoleKey.Learner), + [TenantWideB] = await kit.MemberAsync(TenantB, null, person, BuiltInRoleKey.Learner), + [BranchA2] = await kit.MemberAsync(TenantA, SchemaFixture.OrgA2, person, BuiltInRoleKey.Learner), + }; + if (variant == "completed_before_begin") + { + // An erasure of the group that completed before the closure began: the person was admitted to the group again + // afterwards (the fixture's Membership stands for that later one), and the group's fan-out never ran. + await kit.RequestRowAsync(TenantB, person, "erasure", "completed"); + } + + Guid? ownErasure = null; + if (variant == "completed_after_begin") + { + ownErasure = await kit.RequestRowAsync(TenantB, person, "erasure", "awaiting_privileged_step"); + } + + var closure = await kit.ClosureAsync(TenantA, null, person); + var second = await kit.ClosureAsync(TenantB, null, person, due: false); + await kit.OrganizationStatusAsync(TenantA, SchemaFixture.OrgA2, "Archived"); + (await kit.Owner().BeginAsync(AccountClosureBeginKit.Admission(), closure)).Outcome.Should().Be(ClosureBeginOutcome.Begun); + + var erasures = new Dictionary(); + foreach (var group in Served) + { + if (group == pendingGroup && variant is "missing" or "completed_before_begin") + { + continue; + } + + if (group == pendingGroup && variant == "completed_after_begin") + { + var completed = await new DataRequestOperatorOperations(kit.Scope()).CompleteErasureAsync( + TestPlatformAdmissions.Admission(PlatformOperations.ErasureComplete), ownErasure!.Value); + completed.Outcome.Should().Be(ErasureCompletionOutcome.Completed); + erasures[group] = ownErasure.Value; + continue; + } + + erasures[group] = await FanOutErasureAsync(kit, group, person, memberships[group], + awaiting: !(group == pendingGroup && variant == "running")); + if (group == pendingGroup && variant == "snapshot_short") + { + // A Membership of the group the erasure's frozen snapshot does not hold, as an erasure adopted from before a + // re-admission would: written by the owner with the guards paused. + await kit.SqlAsync($""" + SET session_replication_role = replica; + INSERT INTO public.memberships(id,tenant_id,organization_id,user_id,status,created_at,created_by,deleted_at,deleted_by) + VALUES('{Guid.CreateVersion7()}','{TenantB}',NULL,'{person}','Revoked',clock_timestamp(),'{UserId.SystemActor.Value}', + clock_timestamp(),'{UserId.SystemActor.Value}') + """); + } + } + + var planted = new Dictionary + { + ["tenant A"] = await PlantAsync(kit, TenantA, person), + ["tenant B"] = await PlantAsync(kit, TenantB, person), + ["sentinel"] = await PlantAsync(kit, TenantId.PlatformSentinel.Value, person), + }; + return new World(person, "fixture-subject-" + person.ToString("N"), closure, second, erasures, planted); + } + + /// + /// A served group's fan-out erasure as the group's act creates it (born fulfilling by the application role under + /// the person's User fence) and, unless still running, as its job leaves it: awaiting the privileged step with the + /// tenant side's retained record. + /// + private static async Task FanOutErasureAsync( + AccountClosureBeginKit kit, ClosureParticipantGroup group, Guid person, Guid membership, bool awaiting) + { + var id = Guid.CreateVersion7(); + var (tenant, organization) = (group.TenantId.Value, group.OrganizationId?.Value); + await using var app = await DataExportTestKit.OpenAppAsync(kit.Database.AppConnectionString); + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, tenant, organization, person); + await 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) + VALUES(@id,@tenant,@organization,'erasure','closure_fanout',@subject,NULL,'fulfilling',@snapshot::jsonb,NULL,now(),@system) + """, ("id", id), ("tenant", tenant), ("organization", organization), ("subject", person), ("snapshot", Snapshot(membership)), + ("system", UserId.SystemActor.Value)); + await transaction.CommitAsync(); + } + + if (awaiting) + { + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, tenant, organization, null); + await StepAsync(app, transaction, id, "result='{\"consent_evidence\":2,\"audit_actor_reference\":9}'"); + await StepAsync(app, transaction, id, "status='awaiting_privileged_step'"); + await transaction.CommitAsync(); + } + + return id; + } + + /// A row naming the person as its actor, with an address, an agent and an e-mail, as the platform role writes it. + private static async Task PlantAsync(AccountClosureBeginKit kit, Guid tenant, Guid person) + { + var id = Guid.CreateVersion7(); + await using var platform = await AccountClosureBeginKit.OpenAsync(kit.Database.PlatformConnectionString); + await using var command = new NpgsqlCommand(""" + INSERT INTO public.audit_log (id, "timestamp", tenant_id, organization_id, actor_user_id, actor_email, module, operation, + operation_type, operation_class, entity_type, entity_id, outcome, correlation_id, ip_address, user_agent) + VALUES (@id, clock_timestamp(), @tenant, NULL, @actor, 'person@example.test', 'canary', 'canary.closure.row', 'Update', 'Must', + 'Course', @entity, 'success', @correlation, '198.51.100.7'::inet, 'Canary/1.0') + """, platform); + command.Parameters.AddWithValue("id", id); + command.Parameters.AddWithValue("tenant", tenant); + command.Parameters.AddWithValue("actor", person); + command.Parameters.AddWithValue("entity", Guid.CreateVersion7().ToString("D")); + command.Parameters.AddWithValue("correlation", "00-" + id.ToString("N") + "-01"); + await command.ExecuteNonQueryAsync(); + return id; + } + + private sealed record PlantedRow(string? Address, string? Agent, string? Email, Guid? Actor); + + private static async Task> PlantedAsync(AccountClosureBeginKit kit, World world) + { + await using var platform = await AccountClosureBeginKit.OpenAsync(kit.Database.PlatformConnectionString); + var rows = new Dictionary(); + foreach (var (label, id) in world.Planted) + { + await using var command = new NpgsqlCommand( + "SELECT host(ip_address), user_agent, actor_email, actor_user_id FROM public.audit_log WHERE id = @id", platform); + command.Parameters.AddWithValue("id", id); + await using var reader = await command.ExecuteReaderAsync(); + (await reader.ReadAsync()).Should().BeTrue(label); + rows[label] = new PlantedRow(reader.IsDBNull(0) ? null : reader.GetString(0), reader.IsDBNull(1) ? null : reader.GetString(1), + reader.IsDBNull(2) ? null : reader.GetString(2), reader.IsDBNull(3) ? null : reader.GetGuid(3)); + } + + rows.Values.Should().OnlyContain(row => row.Actor == world.Person, "the actor is retained: redaction rewrites six columns only"); + return rows; + } + + private sealed record RequestState(string Status, string Result); + + /// A request in its own group, as the owner reads it. + private static async Task RequestStateAsync(AccountClosureBeginKit kit, ClosureParticipantGroup group, Guid id) + { + await using var owner = await AccountClosureBeginKit.OpenAsync(kit.Database.MigrationConnectionString); + await using var transaction = await owner.BeginTransactionAsync(); + await ScopeAsync(owner, transaction, group.TenantId.Value, group.OrganizationId?.Value); + await using var command = new NpgsqlCommand( + "SELECT status, result::text FROM public.data_subject_requests WHERE id=@id", owner, transaction); + command.Parameters.AddWithValue("id", id); + await using var row = await command.ExecuteReaderAsync(); + (await row.ReadAsync()).Should().BeTrue(); + return new RequestState(row.GetString(0), row.GetString(1)); + } + + private static async Task SubjectKeyAsync(AccountClosureBeginKit kit, Guid person) + { + await using var owner = await AccountClosureBeginKit.OpenAsync(kit.Database.MigrationConnectionString); + return await ScalarAsync(owner, null, "SELECT encode(subject_key, 'hex') FROM public.users WHERE id=@id", ("id", person)); + } + + private static async Task CreationRowsAsync(AccountClosureBeginKit kit, Guid person) + { + await using var platform = await AccountClosureBeginKit.OpenAsync(kit.Database.PlatformConnectionString); + return await ScalarAsync(platform, null, + "SELECT count(*) FROM public.audit_log WHERE operation = 'identity.user.create' AND entity_id = @id", + ("id", person.ToString("D"))); + } +} + +/// A logger that keeps every formatted line and its exception's text, to prove what an act never logs. +internal sealed class CapturingLogger : ILogger +{ + private readonly System.Collections.Concurrent.ConcurrentQueue _lines = new(); + + public IReadOnlyList Lines => [.. _lines]; + + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) => + _lines.Enqueue(eventId.Id + " " + logLevel + " " + formatter(state, exception) + (exception is null ? string.Empty : " " + exception)); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureFlow.cs b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureFlow.cs new file mode 100644 index 000000000..9332b7b2a --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureFlow.cs @@ -0,0 +1,110 @@ +using System.Diagnostics; +using FluentAssertions; +using LearnStack.Application.Jobs; +using LearnStack.Infrastructure.Jobs; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Platform; +using LearnStack.Tests.Fixtures; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Hosting; +using Npgsql; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// A whole closure through the production composition: the API host over a disposable database with the operator's grant +/// held, the real gate, platform scope, audit store, redaction executor, fan-out, operator act executor, erasure job and +/// runtime, and an identity provider stand-in in place of the account-removal adapter. Begin and Finalize are resolved from a +/// request scope with the trace an HTTP request carries, as their route resolves them. +/// +internal static class AccountClosureFlow +{ + internal static WebApplicationFactory Host(DisposableSchemaDatabase database, IIdentityProviderAccountRemoval removal) => + new ConstructionOnlyApiFactory().WithWebHostBuilder(builder => + { + builder.UseEnvironment(Environments.Development); + builder.UseSetting("ConnectionStrings:Default", database.AppConnectionString); + builder.UseSetting("ConnectionStrings:OutboxDispatcher", database.OutboxConnectionString); + builder.UseSetting("ConnectionStrings:PlatformAdmin", database.PlatformConnectionString); + builder.ConfigureTestServices(services => + { + services.RemoveAll(); + services.AddSingleton(new Grants()); + services.RemoveAll(); + services.AddSingleton(removal); + }); + }); + + internal static PlatformAdmission Admission(PlatformOperation operation, string? ticket) => TestPlatformAdmissions.Admission( + operation, ticket, correlationId: "00-closure-flow-" + Guid.NewGuid().ToString("N")); + + internal static async Task BeginAsync(WebApplicationFactory host, Guid closure, string? ticket = null) + { + using var activity = new Activity("closure-flow-begin").Start(); + await using var scope = host.Services.CreateAsyncScope(); + return await scope.ServiceProvider.GetRequiredService().BeginAsync( + Admission(PlatformOperations.ClosureBegin, ticket), closure); + } + + internal static async Task FinalizeAsync(WebApplicationFactory host, PlatformAdmission admission, Guid closure) + { + using var activity = new Activity("closure-flow-finalize").Start(); + await using var scope = host.Services.CreateAsyncScope(); + return await scope.ServiceProvider.GetRequiredService().FinalizeAsync(admission, closure); + } + + /// The group's one fan-out erasure of the person, read under the group's own announcement. + internal static async Task FanOutRequestAsync(DisposableSchemaDatabase database, ClosureParticipantGroup group, Guid person) + { + await using var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, group.TenantId.Value, group.OrganizationId?.Value); + return await ScalarAsync(app, transaction, """ + SELECT id FROM public.data_subject_requests + WHERE subject_user_id = @subject AND tenant_id = @tenant AND organization_id IS NOT DISTINCT FROM @organization::uuid + AND kind = 'erasure' AND origin = 'closure_fanout' + """, ("subject", person), ("tenant", group.TenantId.Value), ("organization", (object?)group.OrganizationId?.Value ?? DBNull.Value)); + } + + /// Runs the group's erasure job for the request through the actual runtime, as the job host would. + internal static async Task RunErasureJobAsync( + WebApplicationFactory host, DisposableSchemaDatabase database, ClosureParticipantGroup group, Guid request) + { + Guid job; + await using (var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, transaction, group.TenantId.Value, group.OrganizationId?.Value); + job = await ScalarAsync(app, transaction, """ + SELECT id FROM public.background_jobs + WHERE tenant_id = @tenant AND organization_id IS NOT DISTINCT FROM @organization::uuid AND definition_key = @definition + AND parameters = @parameters + ORDER BY created_at DESC, id DESC LIMIT 1 + """, ("tenant", group.TenantId.Value), ("organization", (object?)group.OrganizationId?.Value ?? DBNull.Value), + ("definition", group.OrganizationId is null ? "identity.data_erasure_tenant.v1" : "identity.data_erasure_organization.v1"), + ("parameters", DataErasureTestKit.Parameters(request))); + } + + var executor = host.Services.GetRequiredService(); + var start = await executor.ExecuteAsync( + await DataExportTestKit.RoutingClaim.ClaimAsync(database.OutboxConnectionString, BackgroundJobId.From(job)), BackgroundJobTestRun.Create()); + start.Outcome.Should().Be(JobStartExecutionOutcome.Started); + (await executor.ExecuteBusinessAsync(start.Receipt!, start.Receipt!.Run.OpenBoundary(BackgroundJobCheckpointKind.Transactional))) + .Committed(); + } + + /// The operator's grant of the one key every closure act and every fan-out act needs. + private sealed class Grants : IPlatformOperatorGrantSource + { + public ValueTask IsGrantedAsync(string subjectDigest, string permissionKey, CancellationToken cancellationToken = default) => + ValueTask.FromResult(permissionKey == PlatformPermissions.DataRequestWrite.Key + && subjectDigest == TestPlatformAdmissions.Witness().SubjectDigest); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureStorageTests.Arrows.cs b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureStorageTests.Arrows.cs new file mode 100644 index 000000000..69252e1f2 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureStorageTests.Arrows.cs @@ -0,0 +1,400 @@ +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; + +public sealed partial class AccountClosureStorageTests +{ + private const string Begin = "status='fulfilling',row_version=row_version+1"; + private const string Finalize = "status='completed',row_version=row_version+1"; + private const string ImmutableState = "Data request immutable state refused."; + private const string RefusalRecord = "Data request refusal record refused."; + private const string ResultRefused = "Data request result refused."; + private const string Transition = "Data request transition refused."; + private const string Subject = "Data request closure subject refused."; + private const string UserFence = "Data request closure user fence refused."; + private const string TenantFence = "Data request closure tenant fence refused."; + + /// + /// A closure's Begin (scheduled → fulfilling) once its window has passed, with the subject Closing and the + /// subject's User key, the request's tenant key and every participant tenant key held exclusively; and its refusal + /// record (scheduled → scheduled setting a closed code), which needs no witness. Each condition is removed alone, + /// and the platform role takes no other arrow, row INSERT or DELETE. + /// + [Fact] + public async Task A_closure_s_Begin_and_its_refusal_record_take_their_arrows_only_under_their_witnesses() + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(schema.Postgres); + var arranged = await ArrangeAsync(database); + await MoveAsync(database, PersonA, Close, (SchemaFixture.TenantA, Mode.Exclusive), (SchemaFixture.TenantB, Mode.Exclusive)); + static Task Unfenced(NpgsqlConnection connection, NpgsqlTransaction transaction) => Task.CompletedTask; + + // The refusal record, on the closure still in its window. + foreach (var (set, reason) in new[] + { + ("last_refusal='blocked_window'", ImmutableState), + ("last_refusal='blocked_window',row_version=row_version+2", ImmutableState), + ("last_refusal='blocked_everything',row_version=row_version+1", RefusalRecord), + ("last_refusal=NULL,row_version=row_version+1", RefusalRecord), + ("last_refusal='blocked_window',result='{\"audit_actor_reference\":1}',row_version=row_version+1", ResultRefused), + ("last_refusal='blocked_window',completed_at=now(),row_version=row_version+1", "Data request completion refused."), + ("last_refusal='blocked_window',status='cancelled',row_version=row_version+1", RefusalRecord), + ("status='cancelled',row_version=row_version+1", Transition), + // A never-begun closure completes only on Finalize's arm, which refuses a subject not yet Closed. + ("status='completed',row_version=row_version+1", Subject), + }) + { + var refusal = await PlatformRefusedAsync(database, Unfenced, Format(set), ("id", arranged.PendingClosureA1)); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", reason), set); + } + + await PlatformCommitAsync(database, Unfenced, Format("last_refusal='blocked_window',row_version=row_version+1"), + arranged.PendingClosureA1); + var recorded = await RequestStateAsync(database, SchemaFixture.TenantA, SchemaFixture.OrgA1, arranged.PendingClosureA1); + recorded.Should().Be(new RequestState("scheduled", 1, "blocked_window", null, SystemActor, "{}"), + "the record stamps the system actor, steps the version once and leaves the request scheduled"); + foreach (var (set, because) in new[] + { + ("last_refusal='blocked_window',row_version=row_version+1", "recording the standing code again changes nothing"), + ("last_refusal=NULL,row_version=row_version+1", "a code is never cleared; a Begin that succeeds moves the request on"), + }) + { + var refusal = await PlatformRefusedAsync(database, Unfenced, Format(set), ("id", arranged.PendingClosureA1)); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", RefusalRecord), because); + } + + await PlatformCommitAsync(database, Unfenced, Format("last_refusal='blocked_last_administrator',row_version=row_version+1"), + arranged.PendingClosureA1); + (await RequestStateAsync(database, SchemaFixture.TenantA, SchemaFixture.OrgA1, arranged.PendingClosureA1)).Refusal + .Should().Be("blocked_last_administrator", "a later refusal replaces the standing one"); + (await PlatformRefusedAsync(database, Unfenced, Format("last_refusal='blocked_hold',row_version=row_version+1"), ("id", BranchB.Request))) + .MessageText.Should().Be(RefusalRecord, "only a closure carries the platform's refusal record"); + + // Begin: every condition but one, each time. + foreach (var (set, reason) in new[] + { + ("status='fulfilling'", ImmutableState), + (Begin + ",result='{\"audit_actor_reference\":1}'", ResultRefused), + (Begin + ",completed_at=now()", "Data request completion refused."), + (Begin + ",last_refusal='blocked_hold'", RefusalRecord), + }) + { + var refusal = await PlatformRefusedAsync(database, FullFencesOfPersonA, Format(set), ("id", arranged.DueClosureA)); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", reason), set); + } + + (await PlatformRefusedAsync(database, FullFencesOfPersonA, Format(Begin + ",progress='{}'::jsonb"), ("id", arranged.DueClosureA))) + .SqlState.Should().Be("42501", "a column outside the grant never reaches the guard"); + foreach (var (user, tenantA, tenantB, reason, because) in new (Mode, Mode, Mode, string, string)[] + { + (Mode.None, Mode.Exclusive, Mode.Exclusive, UserFence, "without the User key"), + (Mode.Shared, Mode.Exclusive, Mode.Exclusive, UserFence, "with the User key shared"), + (Mode.Exclusive, Mode.None, Mode.Exclusive, TenantFence, "without the request's own tenant key"), + (Mode.Exclusive, Mode.Shared, Mode.Exclusive, TenantFence, "with the request's tenant key shared"), + (Mode.Exclusive, Mode.Exclusive, Mode.None, TenantFence, "without the tombstone tenant's key"), + (Mode.Exclusive, Mode.Exclusive, Mode.Shared, TenantFence, "with the tombstone tenant's key shared"), + }) + { + var refusal = await PlatformRefusedAsync(database, PersonAFences(user, tenantA, tenantB), Format(Begin), ("id", arranged.DueClosureA)); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", reason), because); + } + + (await PlatformRefusedAsync(database, FullFencesOfPersonA, Format(Begin), ("id", arranged.PendingClosureA1))) + .MessageText.Should().Be("Data request closure window refused.", "a closure is begun only once its window has passed"); + (await PlatformRefusedAsync(database, (connection, transaction) => ClosureFencesAsync(connection, transaction, PersonB, Mode.Exclusive, + (SchemaFixture.TenantB, Mode.Exclusive)), Format(Begin), ("id", arranged.DueClosureB))) + .MessageText.Should().Be(Subject, "the User is moved to Closing first, in the same transaction"); + + await PlatformCommitAsync(database, FullFencesOfPersonA, Format(Begin), arranged.DueClosureA); + (await RequestStateAsync(database, SchemaFixture.TenantA, null, arranged.DueClosureA)) + .Should().Be(new RequestState("fulfilling", 1, null, null, SystemActor, "{}")); + + // From fulfilling the platform role takes Finalize alone, and only once the subject is Closed. + foreach (var (set, reason) in new[] + { + (Finalize, Subject), + ("status='cancelled',row_version=row_version+1", Transition), + ("status='scheduled',row_version=row_version+1", Transition), + (Begin, Transition), + }) + { + var refusal = await PlatformRefusedAsync(database, FullFencesOfPersonA, Format(set), ("id", arranged.DueClosureA)); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", reason), set); + } + + // The platform role has no INSERT or DELETE grant; widened in this disposable database, its arm refuses both. + await using (var owner = await OpenAsync(database.MigrationConnectionString)) + await ExecuteAsync(owner, null, "GRANT INSERT, DELETE ON public.data_subject_requests TO learnstack_platform"); + try + { + var delete = await PlatformRefusedAsync(database, FullFencesOfPersonA, "DELETE FROM public.data_subject_requests WHERE id=@id", + ("id", arranged.DueClosureA)); + (delete.SqlState, delete.MessageText).Should().Be(("23514", "Data request mutation refused.")); + var insert = await PlatformRefusedAsync(database, FullFencesOfPersonA, """ + 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,NULL,'erasure','closure_fanout',@subject,NULL,'fulfilling',@snapshot::jsonb,NULL,now(),@system) + """, ("id", Guid.CreateVersion7()), ("tenant", SchemaFixture.TenantA), ("subject", PersonA), + ("snapshot", Snapshot(LearnerMembershipA)), ("system", SystemActor)); + (insert.SqlState, insert.MessageText).Should().Be(("23514", "Data request mutation refused.")); + } + finally + { + await using var owner = await OpenAsync(database.MigrationConnectionString); + await ExecuteAsync(owner, null, "REVOKE INSERT, DELETE ON public.data_subject_requests FROM learnstack_platform"); + } + } + + /// + /// A closure's Finalize (fulfilling → completed, and scheduled → completed for another closure of the + /// subject never begun) once the subject is Closed, under the fences of Begin, with the result changed only in the audit + /// kinds and the unserved groups; and the completion of its fan-out erasures + /// (awaiting_privileged_step → completed) once the subject is Closing or Closed, under the subject's User key and + /// the request's own tenant key, with the result changed only in the audit kinds. The application role takes none of + /// the closure's arrows. + /// + [Fact] + public async Task A_closure_s_Finalize_and_its_fan_out_completions_take_their_arrows_only_under_their_witnesses() + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(schema.Postgres); + var arranged = await ArrangeAsync(database, pendingDue: true); + await MoveAsync(database, PersonA, Close, (SchemaFixture.TenantA, Mode.Exclusive), (SchemaFixture.TenantB, Mode.Exclusive)); + await PlatformCommitAsync(database, FullFencesOfPersonA, Format(Begin), arranged.DueClosureA); + var fanA = await FanOutAsync(database, SchemaFixture.TenantA, null, PersonA, LearnerMembershipA); + var fanB = await FanOutAsync(database, SchemaFixture.TenantB, null, PersonA, arranged.ForeignMembership); + + // The application role's arms are unchanged: none of the closure's arrows is its own. + await using (var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString)) + { + foreach (var (tenant, organization, id, set, because) in new (Guid, Guid?, Guid, string, string)[] + { + (SchemaFixture.TenantA, SchemaFixture.OrgA1, arranged.PendingClosureA1, "status='fulfilling'", "Begin"), + (SchemaFixture.TenantA, null, arranged.DueClosureA, "status='completed',completed_at=now()", "Finalize"), + (SchemaFixture.TenantA, null, fanA, "status='completed',completed_at=now()", "a fan-out's completion"), + }) + { + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, tenant, organization, PersonA); + var refusal = await DataExportTestKit.RefuseAsync(transaction, () => StepAsync(app, transaction, id, set)); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", Transition), because); + } + + // ADR-0106 § 7's application refusal record admits a code on any scheduled request, a closure's included; no + // application path writes one, and the closure's own record is the platform's (flagged for the maintainer). + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, SchemaFixture.TenantA, SchemaFixture.OrgA1, null); + await StepAsync(app, transaction, arranged.PendingClosureA1, "last_refusal='blocked_hold'"); + await transaction.RollbackAsync(); + } + } + + // A fan-out's completion while the subject is Closing, admitted with its two fences and refused without either. + const string Redacted = "result='{\"consent_evidence\":2,\"audit_actor_reference\":4,\"unscoped_audit_rows\":1}'"; + Task FanOutFences(NpgsqlConnection connection, NpgsqlTransaction transaction, Mode user, Mode tenant) => + ClosureFencesAsync(connection, transaction, PersonA, user, (SchemaFixture.TenantA, tenant)); + await PlatformAdmittedAsync(database, (connection, transaction) => FanOutFences(connection, transaction, Mode.Exclusive, Mode.Exclusive), + Format(Finalize + "," + Redacted), fanA); + foreach (var (user, tenant, reason, because) in new (Mode, Mode, string, string)[] + { + (Mode.None, Mode.Exclusive, UserFence, "without the User key"), + (Mode.Shared, Mode.Exclusive, UserFence, "with the User key shared"), + (Mode.Exclusive, Mode.None, TenantFence, "without the request's tenant key"), + (Mode.Exclusive, Mode.Shared, TenantFence, "with the request's tenant key shared"), + }) + { + var refusal = await PlatformRefusedAsync(database, (connection, transaction) => FanOutFences(connection, transaction, user, tenant), + Format(Finalize + "," + Redacted), ("id", fanA)); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", reason), because); + } + + foreach (var (set, reason) in new[] + { + (Finalize + ",result='{\"consent_evidence\":3,\"audit_actor_reference\":4}'", ResultRefused), + (Finalize + ",result='{\"audit_actor_reference\":4}'", ResultRefused), + (Finalize + ",result='{\"consent_evidence\":2,\"audit_actor_reference\":4,\"unserved_group\":1}'", ResultRefused), + (Finalize + ",last_refusal='blocked_hold'", RefusalRecord), + ("status='completed'", ImmutableState), + }) + { + var refusal = await PlatformRefusedAsync(database, FullFencesOfPersonA, Format(set), ("id", fanA)); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", reason), set); + } + + (await PlatformRefusedAsync(database, FullFencesOfPersonA, Format(Finalize), ("id", arranged.DueClosureA))) + .MessageText.Should().Be(Subject, "Finalize completes the closure only once the subject is Closed"); + (await PlatformRefusedAsync(database, FullFencesOfPersonA, Format(Finalize), ("id", arranged.PendingClosureA1))) + .MessageText.Should().Be(Subject, "a never-begun closure of the subject is completed only once the subject is Closed"); + + await MoveAsync(database, PersonA, Closed, (SchemaFixture.TenantA, Mode.Exclusive), (SchemaFixture.TenantB, Mode.Exclusive)); + (await PlatformRefusedAsync(database, FullFencesOfPersonA, Format(Begin), ("id", arranged.PendingClosureA1))) + .MessageText.Should().Be(Subject, "no closure is begun once the subject is Closed"); + + // Finalize: every condition but one, each time, for the closure it finalizes from fulfilling and for another closure + // of the subject never begun, which the same arm completes under the same witnesses (20261123120000). + const string Report = "result='{\"audit_actor_reference\":3,\"unserved_group\":1}'"; + foreach (var completing in new[] { arranged.DueClosureA, arranged.PendingClosureA1 }) + foreach (var (user, tenantA, tenantB, reason, because) in new (Mode, Mode, Mode, string, string)[] + { + (Mode.None, Mode.Exclusive, Mode.Exclusive, UserFence, "without the User key"), + (Mode.Shared, Mode.Exclusive, Mode.Exclusive, UserFence, "with the User key shared"), + (Mode.Exclusive, Mode.None, Mode.Exclusive, TenantFence, "without the request's own tenant key"), + (Mode.Exclusive, Mode.Shared, Mode.Exclusive, TenantFence, "with the request's tenant key shared"), + (Mode.Exclusive, Mode.Exclusive, Mode.None, TenantFence, "without the tombstone tenant's key"), + (Mode.Exclusive, Mode.Exclusive, Mode.Shared, TenantFence, "with the tombstone tenant's key shared"), + }) + { + var refusal = await PlatformRefusedAsync(database, PersonAFences(user, tenantA, tenantB), Format(Finalize + "," + Report), + ("id", completing)); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", reason), because); + } + + foreach (var (set, reason) in new[] + { + (Finalize + ",result='{\"consent_evidence\":1}'", ResultRefused), + (Finalize + ",result='{\"request_receipt\":1,\"unserved_group\":1}'", ResultRefused), + (Finalize + ",last_refusal='blocked_hold'", RefusalRecord), + ("status='completed'," + Report, ImmutableState), + }) + { + var refusal = await PlatformRefusedAsync(database, FullFencesOfPersonA, Format(set), ("id", arranged.DueClosureA)); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", reason), set); + } + + foreach (var (set, reason) in new[] + { + (Finalize + ",result='{\"request_receipt\":1}'", ResultRefused), + (Finalize + ",last_refusal='blocked_window'", RefusalRecord), + ("status='completed'," + Report, ImmutableState), + }) + { + var refusal = await PlatformRefusedAsync(database, FullFencesOfPersonA, Format(set), ("id", arranged.PendingClosureA1)); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", reason), set); + } + + // Finalize's second transaction: every fan-out erasure, the closure and the subject's never-begun closure completed, + // under the fences of Begin, with the completion time the database clock's whatever the statement says. + await using (var platform = await OpenAsync(database.PlatformConnectionString)) + await using (var transaction = await platform.BeginTransactionAsync()) + { + await FullFencesOfPersonA(platform, transaction); + foreach (var fan in new[] { fanA, fanB }) + await ExecuteAsync(platform, transaction, Format(Finalize + "," + Redacted + ",completed_at='2001-01-01T00:00:00Z'"), ("id", fan)); + await ExecuteAsync(platform, transaction, Format(Finalize + "," + Report), ("id", arranged.DueClosureA)); + await ExecuteAsync(platform, transaction, Format(Finalize + "," + Report), ("id", arranged.PendingClosureA1)); + await transaction.CommitAsync(); + } + + var neverBegun = await RequestStateAsync(database, SchemaFixture.TenantA, SchemaFixture.OrgA1, arranged.PendingClosureA1); + neverBegun.Should().Be(new RequestState("completed", 1, null, neverBegun.CompletedAt, SystemActor, + "{\"unserved_group\": 1, \"audit_actor_reference\": 3}"), "a never-begun closure goes from scheduled to completed in one step"); + + var closure = await RequestStateAsync(database, SchemaFixture.TenantA, null, arranged.DueClosureA); + closure.Should().Be(new RequestState("completed", 2, null, closure.CompletedAt, SystemActor, "{\"unserved_group\": 1, \"audit_actor_reference\": 3}")); + closure.CompletedAt.Should().NotBeNull().And.BeCloseTo(DateTime.UtcNow, TimeSpan.FromMinutes(1)); + foreach (var (tenant, fan) in new[] { (SchemaFixture.TenantA, fanA), (SchemaFixture.TenantB, fanB) }) + { + var completed = await RequestStateAsync(database, tenant, null, fan); + completed.Should().Be(new RequestState("completed", 3, null, completed.CompletedAt, SystemActor, + "{\"consent_evidence\": 2, \"unscoped_audit_rows\": 1, \"audit_actor_reference\": 4}")); + completed.CompletedAt.Should().BeCloseTo(DateTime.UtcNow, TimeSpan.FromMinutes(1), "no caller supplies the completion time"); + } + + (await RequestStampedAsync(database, SchemaFixture.TenantA, null, arranged.DueClosureA)).Should().BeTrue( + "the completion time is the update stamp the arm wrote"); + foreach (var id in new[] { arranged.DueClosureA, arranged.PendingClosureA1, fanA }) + { + var refusal = await PlatformRefusedAsync(database, FullFencesOfPersonA, Format(Finalize), ("id", id)); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", Transition), "a completed request is terminal"); + } + } + + /// + /// One fan-out erasure as the closure's pipeline frame writes it: born fulfilling by the application role in the + /// group's own transaction under the subject's User fence, then carried by the application's own arrows to the + /// privileged step with a tenant-side result. + /// + private static async Task FanOutAsync(DisposableSchemaDatabase database, Guid tenant, Guid? organization, Guid subject, Guid membership) + { + var id = Guid.CreateVersion7(); + await using var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString); + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, tenant, organization, subject); + await InsertFanOutAsync(app, transaction, id, tenant, organization, subject, membership); + await transaction.CommitAsync(); + } + + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, tenant, organization, null); + await StepAsync(app, transaction, id, "result='{\"consent_evidence\":2,\"audit_actor_reference\":9}'"); + await StepAsync(app, transaction, id, "status='awaiting_privileged_step'"); + await transaction.CommitAsync(); + } + + return id; + } + + private static string Format(string set) => "UPDATE public.data_subject_requests SET " + set + " WHERE id=@id"; + + /// Runs one request statement on a fresh platform transaction holding and commits it. + private static async Task PlatformCommitAsync(DisposableSchemaDatabase database, Func fences, + string sql, Guid id) + { + await using var platform = await OpenAsync(database.PlatformConnectionString); + await using var transaction = await platform.BeginTransactionAsync(); + await fences(platform, transaction); + (await ExecuteCountAsync(platform, transaction, sql, id)).Should().Be(1, sql); + await transaction.CommitAsync(); + } + + /// Runs one request statement on a fresh platform transaction holding , sees it admitted and rolls back. + private static async Task PlatformAdmittedAsync(DisposableSchemaDatabase database, Func fences, + string sql, Guid id) + { + await using var platform = await OpenAsync(database.PlatformConnectionString); + await using var transaction = await platform.BeginTransactionAsync(); + await fences(platform, transaction); + (await ExecuteCountAsync(platform, transaction, sql, id)).Should().Be(1, sql); + await transaction.RollbackAsync(); + } + + private static async Task ExecuteCountAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, string sql, Guid id) + { + await using var command = new NpgsqlCommand(sql, connection, transaction); + command.Parameters.AddWithValue("id", id); + return await command.ExecuteNonQueryAsync(); + } + + private sealed record RequestState(string Status, long Version, string? Refusal, DateTime? CompletedAt, Guid? UpdatedBy, string Result); + + /// The request row as the owner reads it in its own group, the update stamps included. + private static async Task RequestStateAsync(DisposableSchemaDatabase database, Guid tenant, Guid? organization, Guid id) + { + await using var owner = await OpenAsync(database.MigrationConnectionString); + await using var transaction = await owner.BeginTransactionAsync(); + await ScopeAsync(owner, transaction, tenant, organization); + await using var command = new NpgsqlCommand(""" + SELECT status, row_version, last_refusal, completed_at, updated_by, result::text + FROM public.data_subject_requests WHERE id=@id + """, owner, transaction); + command.Parameters.AddWithValue("id", id); + await using var row = await command.ExecuteReaderAsync(); + (await row.ReadAsync()).Should().BeTrue(); + return new RequestState(row.GetString(0), row.GetInt64(1), row.IsDBNull(2) ? null : row.GetString(2), + row.IsDBNull(3) ? null : row.GetDateTime(3), row.IsDBNull(4) ? null : row.GetGuid(4), row.GetString(5)); + } + + private static async Task RequestStampedAsync(DisposableSchemaDatabase database, Guid tenant, Guid? organization, Guid id) + { + await using var owner = await OpenAsync(database.MigrationConnectionString); + await using var transaction = await owner.BeginTransactionAsync(); + await ScopeAsync(owner, transaction, tenant, organization); + return await ScalarAsync(owner, transaction, + "SELECT completed_at = updated_at FROM public.data_subject_requests WHERE id=@id", ("id", id)); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureStorageTests.Coverage.cs b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureStorageTests.Coverage.cs new file mode 100644 index 000000000..2d7c4b810 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureStorageTests.Coverage.cs @@ -0,0 +1,111 @@ +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; + +public sealed partial class AccountClosureStorageTests +{ + /// + /// The fences are the connection's own: keys that another backend holds, even every key the arrow needs, admit nothing + /// for this backend. For the User move and for a closure's Begin, one backend holds some of the closure's fences and + /// this one holds the rest or none, and the arrow names the missing fence it needs. With the fences held by this + /// backend alone and no other holder, the same statements are admitted. + /// + [Fact] + public async Task A_fence_another_backend_holds_admits_nothing_for_this_one() + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(schema.Postgres); + var arranged = await ArrangeAsync(database); + + // The User move, while the person is Active: what the other backend holds, and what this one takes beside it. + foreach (var (held, own, reason, because) in new (Mode[] Held, Mode[] Own, string Reason, string Because)[] + { + ([Mode.Exclusive, Mode.Exclusive, Mode.Exclusive], [Mode.None, Mode.None, Mode.None], "User closure fence refused.", + "another backend holds every fence and this one none"), + ([Mode.Exclusive, Mode.None, Mode.None], [Mode.None, Mode.Exclusive, Mode.Exclusive], "User closure fence refused.", + "another backend holds the User key and this one both tenant keys"), + ([Mode.Exclusive, Mode.Exclusive, Mode.None], [Mode.None, Mode.None, Mode.Exclusive], "User closure fence refused.", + "another backend holds the User key and one tenant key, this one the other tenant key"), + ([Mode.None, Mode.Exclusive, Mode.Exclusive], [Mode.Exclusive, Mode.None, Mode.None], "User closure tenant fence refused.", + "another backend holds both tenant keys and this one the User key"), + ([Mode.None, Mode.None, Mode.Exclusive], [Mode.Exclusive, Mode.Exclusive, Mode.None], "User closure tenant fence refused.", + "another backend holds the tombstone tenant's key and this one the rest"), + }) + { + await using var holder = await OpenAsync(database.PlatformConnectionString); + await using var holding = await holder.BeginTransactionAsync(); + await PersonAFences(held[0], held[1], held[2])(holder, holding); + (await HeldAdvisoryKeysAsync(database, holder)).Should().Be(held.Count(mode => mode != Mode.None), because); + + var refusal = await PlatformRefusedAsync(database, PersonAFences(own[0], own[1], own[2]), Close, ("user", PersonA)); + + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", reason), because); + } + + (await UserStateAsync(database, PersonA)).Status.Should().Be("Active"); + await MoveAsync(database, PersonA, Close, (SchemaFixture.TenantA, Mode.Exclusive), (SchemaFixture.TenantB, Mode.Exclusive)); + + // A closure's Begin, once the person is Closing: the same, with the arrow's own two fence messages. + foreach (var (held, own, reason, because) in new (Mode[] Held, Mode[] Own, string Reason, string Because)[] + { + ([Mode.Exclusive, Mode.Exclusive, Mode.Exclusive], [Mode.None, Mode.None, Mode.None], UserFence, + "another backend holds every fence and this one none"), + ([Mode.Exclusive, Mode.None, Mode.None], [Mode.None, Mode.Exclusive, Mode.Exclusive], UserFence, + "another backend holds the User key and this one both tenant keys"), + ([Mode.None, Mode.Exclusive, Mode.Exclusive], [Mode.Exclusive, Mode.None, Mode.None], TenantFence, + "another backend holds both tenant keys and this one the User key"), + }) + { + await using var holder = await OpenAsync(database.PlatformConnectionString); + await using var holding = await holder.BeginTransactionAsync(); + await PersonAFences(held[0], held[1], held[2])(holder, holding); + (await HeldAdvisoryKeysAsync(database, holder)).Should().Be(held.Count(mode => mode != Mode.None), because); + + var refusal = await PlatformRefusedAsync(database, PersonAFences(own[0], own[1], own[2]), Format(Begin), ("id", arranged.DueClosureA)); + + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", reason), because); + } + + await PlatformCommitAsync(database, FullFencesOfPersonA, Format(Begin), arranged.DueClosureA); + (await RequestStateAsync(database, SchemaFixture.TenantA, null, arranged.DueClosureA)).Status.Should().Be("fulfilling", + "this backend's own fences admit the Begin once no other backend is involved"); + } + + /// + /// A fan-out erasure is completed only for a subject who is Closing or Closed. For a subject that is Active, which no + /// admitted path produces and the owner forces here, the arrow is refused even with both fences held, and admitted again + /// once the subject is Closing. + /// + [Fact] + public async Task A_fan_out_erasure_is_not_completed_for_a_subject_that_is_Active() + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(schema.Postgres); + await ArrangeAsync(database); + await MoveAsync(database, PersonA, Close, (SchemaFixture.TenantA, Mode.Exclusive), (SchemaFixture.TenantB, Mode.Exclusive)); + var fan = await FanOutAsync(database, SchemaFixture.TenantA, null, PersonA, LearnerMembershipA); + var databaseName = new NpgsqlConnectionStringBuilder(database.MigrationConnectionString).Database; + const string Redacted = "result='{\"consent_evidence\":2,\"audit_actor_reference\":4}'"; + Task Fences(NpgsqlConnection connection, NpgsqlTransaction transaction) => + ClosureFencesAsync(connection, transaction, PersonA, Mode.Exclusive, (SchemaFixture.TenantA, Mode.Exclusive)); + + await schema.Postgres.ExecuteAsSuperuserAsync( + $"SET session_replication_role = replica; UPDATE public.users SET status = 'Active' WHERE id = '{PersonA:D}'", databaseName); + var refusal = await PlatformRefusedAsync(database, Fences, Format(Finalize + "," + Redacted), ("id", fan)); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", Subject), "the subject is Active, which is neither Closing nor Closed"); + + await schema.Postgres.ExecuteAsSuperuserAsync( + $"SET session_replication_role = replica; UPDATE public.users SET status = 'Closing' WHERE id = '{PersonA:D}'", databaseName); + await PlatformAdmittedAsync(database, Fences, Format(Finalize + "," + Redacted), fan); + } + + /// The advisory keys another backend holds, granted, by its process. + private static async Task HeldAdvisoryKeysAsync(DisposableSchemaDatabase database, NpgsqlConnection holder) + { + await using var observer = await OpenAsync(database.MigrationConnectionString); + return await ScalarAsync(observer, null, + "SELECT count(*) FROM pg_catalog.pg_locks WHERE pid = @pid AND locktype = 'advisory' AND granted", ("pid", holder.ProcessID)); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureStorageTests.FanOut.cs b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureStorageTests.FanOut.cs new file mode 100644 index 000000000..bd593bb0f --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureStorageTests.FanOut.cs @@ -0,0 +1,297 @@ +using FluentAssertions; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.DataRequestSchemaSeed; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class AccountClosureStorageTests +{ + private const string FanOutInsert = """ + 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,@origin,@subject,@requester::uuid,@status,@snapshot::jsonb,@execute::timestamptz, + now(),@creator) + """; + + private const string InitialState = "Data request initial state refused."; + private const string NotAdmitted = "Data request subject is not admitted."; + + /// + /// The request guard's one admitted birth in fulfilling: a closure's fan-out erasure (kind erasure, + /// origin closure_fanout, no window, no requester, the system actor) of a subject who is Closing, written by the + /// application role under the subject's exclusive User fence and the group's tenant fence, with the exact snapshot. + /// Each condition is removed alone, every other origin and status stays refused, and an Active or Closed subject has none. + /// + [Fact] + public async Task A_request_is_born_fulfilling_only_as_the_fan_out_erasure_of_a_Closing_subject() + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(schema.Postgres); + var arranged = await ArrangeAsync(database); + await MoveAsync(database, PersonA, Close, (SchemaFixture.TenantA, Mode.Exclusive), (SchemaFixture.TenantB, Mode.Exclusive)); + await using var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString); + + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, SchemaFixture.TenantA, null, PersonA); + await InsertFanOutAsync(app, transaction, Guid.CreateVersion7(), SchemaFixture.TenantA, null, PersonA, LearnerMembershipA); + // An organization's group, under that organization's announcement and the same two fences. + await ScopeAsync(app, transaction, SchemaFixture.TenantA, SchemaFixture.OrgA1); + await InsertFanOutAsync(app, transaction, Guid.CreateVersion7(), SchemaFixture.TenantA, SchemaFixture.OrgA1, PersonA, + BranchMembershipA1); + await transaction.RollbackAsync(); + } + + // The fences removed alone: the User fence, held shared, and the tenant fence. These are the arm's existing checks. + foreach (var (user, tenant, constraint) in new (Mode, Mode, string)[] + { + (Mode.None, Mode.Shared, "identity_user_fence"), + (Mode.Shared, Mode.Shared, "identity_user_fence"), + (Mode.Exclusive, Mode.None, "identity_tenant_fence"), + }) + { + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + await TakeAsync(app, transaction, IdentityAdvisoryLockKey.ForUser(UserId.From(PersonA)), user); + await TakeAsync(app, transaction, IdentityAdvisoryLockKey.ForTenant(TenantId.From(SchemaFixture.TenantA)), tenant); + var refusal = await DataExportTestKit.RefuseAsync(transaction, () => + InsertFanOutAsync(app, transaction, Guid.CreateVersion7(), SchemaFixture.TenantA, null, PersonA, LearnerMembershipA)); + (refusal.SqlState, refusal.ConstraintName).Should().Be(("P0301", constraint), $"user {user}, tenant {tenant}"); + } + + // Every other field of the fan-out removed alone, each refused by the guard before any constraint. + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, SchemaFixture.TenantA, null, PersonA); + Task Born(string kind = "erasure", string origin = "closure_fanout", string status = "fulfilling", Guid? requester = null, + DateTime? executeAt = null, Guid? creator = null, Guid? membership = null) => + InsertFanOutAsync(app, transaction, Guid.CreateVersion7(), SchemaFixture.TenantA, null, PersonA, + membership ?? LearnerMembershipA, kind, origin, status, requester, executeAt, creator); + var tomorrow = DateTime.UtcNow.AddHours(24); + foreach (var (born, reason, because) in new (Func, string, string)[] + { + (() => Born(executeAt: tomorrow), InitialState, "a fan-out has no window"), + (() => Born(requester: PersonA, creator: PersonA), InitialState, "a fan-out has no requester"), + (() => Born(creator: PersonA), InitialState, "a fan-out is the system actor's"), + (() => Born(kind: "export"), InitialState, "a fan-out is an erasure"), + (() => Born(kind: "closure"), InitialState, "a fan-out is an erasure, never a closure"), + (() => Born(membership: BranchMembershipA1), "Data request snapshot refused.", "the snapshot is exactly the group's Memberships"), + (() => Born(origin: "self", requester: PersonA, creator: PersonA), InitialState, "a person's erasure is born scheduled"), + (() => Born(origin: "administrator", requester: AdminA, creator: AdminA), InitialState, "an administrator's erasure is born scheduled"), + (() => Born(kind: "closure", origin: "self", requester: PersonA, creator: PersonA, executeAt: tomorrow), InitialState, + "a closure is born scheduled"), + (() => Born(kind: "export", origin: "self", requester: PersonA, creator: PersonA), InitialState, "an export is born requested"), + }) + { + var refusal = await DataExportTestKit.RefuseAsync(transaction, born); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", reason), because); + } + + foreach (var status in new[] { "requested", "scheduled", "awaiting_privileged_step", "completed", "blocked", "failed", "cancelled" }) + { + var refusal = await DataExportTestKit.RefuseAsync(transaction, () => Born(status: status)); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", InitialState), "a fan-out is never born " + status); + } + + await transaction.RollbackAsync(); + } + + // An Active subject has no fan-out. + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, SchemaFixture.TenantB, SchemaFixture.OrgB1, PersonB); + var refusal = await DataExportTestKit.RefuseAsync(transaction, () => + InsertFanOutAsync(app, transaction, Guid.CreateVersion7(), SchemaFixture.TenantB, SchemaFixture.OrgB1, PersonB, BranchMembershipB)); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", NotAdmitted), "person B is Active"); + } + + // Nor has a Closed one: once Finalize closed the User, no group's erasure starts. + await MoveAsync(database, PersonA, Closed, (SchemaFixture.TenantA, Mode.Exclusive), (SchemaFixture.TenantB, Mode.Exclusive)); + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, SchemaFixture.TenantB, null, PersonA); + var refusal = await DataExportTestKit.RefuseAsync(transaction, () => + InsertFanOutAsync(app, transaction, Guid.CreateVersion7(), SchemaFixture.TenantB, null, PersonA, arranged.ForeignMembership)); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", NotAdmitted), "person A is Closed"); + } + } + + /// + /// Every request the CHECKs admit, each kind and origin, is filed only for a subject in the one status its origin + /// allows, read by the guard under the subject's exclusive User fence: Active for an export, an erasure and a closure + /// of the person or an administrator, Closing for a closure's fan-out. The same filings are admitted while person A is + /// Active, refused once person A is Closing but the fan-out, and refused once person A is Closed. + /// + [Fact] + public async Task Every_request_is_filed_only_for_a_subject_in_the_status_its_origin_admits() + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(schema.Postgres); + await using var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString); + (string Kind, string Origin, string Status, Guid? Requester, bool Window)[] filings = + [ + ("export", "self", "requested", PersonA, false), + ("export", "administrator", "requested", AdminA, false), + ("erasure", "self", "scheduled", PersonA, true), + ("erasure", "administrator", "scheduled", AdminA, true), + ("closure", "self", "scheduled", PersonA, true), + ("erasure", "closure_fanout", "fulfilling", null, false), + ]; + + async Task ExpectAsync(string subjectStatus, Func admitted) + { + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, SchemaFixture.TenantA, null, PersonA); + foreach (var (kind, origin, status, requester, window) in filings) + { + // The window is the CHECK's exact 24 hours after the row's own creation time, which is the transaction's. + Task File() => ExecuteAsync(app, transaction, FanOutInsert.Replace("@execute::timestamptz", + window ? "now() + interval '24 hours'" : "NULL::timestamptz", StringComparison.Ordinal), + ("id", Guid.CreateVersion7()), ("tenant", SchemaFixture.TenantA), ("organization", null), ("kind", kind), + ("origin", origin), ("subject", PersonA), ("requester", requester), ("status", status), + ("snapshot", Snapshot(LearnerMembershipA)), ("creator", requester ?? SystemActor)); + var label = $"{kind}/{origin} for a {subjectStatus} subject"; + if (admitted(origin)) + { + await transaction.SaveAsync("filing"); + await File(); + await transaction.RollbackAsync("filing"); + } + else + { + var refusal = await DataExportTestKit.RefuseAsync(transaction, File); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", NotAdmitted), label); + } + } + + await transaction.RollbackAsync(); + } + + await ExpectAsync("Active", origin => origin != "closure_fanout"); + await MoveAsync(database, PersonA, Close, (SchemaFixture.TenantA, Mode.Exclusive)); + await ExpectAsync("Closing", origin => origin == "closure_fanout"); + await MoveAsync(database, PersonA, Closed, (SchemaFixture.TenantA, Mode.Exclusive)); + await ExpectAsync("Closed", _ => false); + } + + /// + /// The race the witness closes: a person's filing whose transaction reaches the User fence only after a Begin that + /// moved the person to Closing committed. It waits on the fence the platform holds, then reads the committed status + /// under it and inserts nothing, so no closure stays scheduled behind a closing account. + /// + [Fact] + public async Task A_filing_that_waited_on_the_User_fence_behind_a_Begin_reads_the_committed_status_and_inserts_nothing() + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(schema.Postgres); + await using var platform = await OpenAsync(database.PlatformConnectionString); + await using var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString); + await using var observer = await OpenAsync(database.MigrationConnectionString); + + await using var begin = await platform.BeginTransactionAsync(); + await ClosureFencesAsync(platform, begin, PersonA, Mode.Exclusive, (SchemaFixture.TenantA, Mode.Exclusive)); + await ExecuteAsync(platform, begin, Close, ("user", PersonA)); + + await using var filing = await app.BeginTransactionAsync(); + var filed = Task.Run(async () => + { + await FenceAsync(app, filing, SchemaFixture.TenantA, SchemaFixture.OrgA1, PersonA); + await InsertRequestAsync(app, filing, Guid.CreateVersion7(), SchemaFixture.TenantA, SchemaFixture.OrgA1, PersonA, + [BranchMembershipA1], "closure"); + }); + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(30); + while (!await ScalarAsync(observer, null, + "SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_locks WHERE pid=@pid AND locktype='advisory' AND NOT granted)", + ("pid", app.ProcessID))) + { + filed.IsCompleted.Should().BeFalse("the filing waits on the User fence the Begin holds"); + DateTime.UtcNow.Should().BeBefore(deadline); + await Task.Delay(TimeSpan.FromMilliseconds(20)); + } + + await begin.CommitAsync(); + var refusal = (await FluentActions.Awaiting(() => filed).Should().ThrowAsync()).Which; + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", NotAdmitted), + "the person was Active when the filing began and Closing when it reached the fence"); + } + + /// + /// The guard's witness returns the subject's status and nothing else, and only inside a trigger under the subject's + /// exclusive User fence: called directly it returns NULL, as it does without the fence, with the fence held shared and + /// for an unknown subject. It is a definer owned by the NOBYPASSRLS migration role with a fixed search path, and only + /// the application role may call it. + /// + [Fact] + public async Task The_status_witness_answers_only_inside_a_trigger_under_the_subject_s_exclusive_User_fence() + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(schema.Postgres); + await ArrangeAsync(database); + await MoveAsync(database, PersonA, Close, (SchemaFixture.TenantA, Mode.Exclusive), (SchemaFixture.TenantB, Mode.Exclusive)); + const string Direct = "SELECT COALESCE(public.fn_identity_user_status(@user), 'none')"; + + await using (var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await TakeAsync(app, transaction, IdentityAdvisoryLockKey.ForUser(UserId.From(PersonA)), Mode.Exclusive); + (await ScalarAsync(app, transaction, Direct, ("user", PersonA))).Should().Be("none", + "outside a trigger the witness reveals nothing, even under the subject's fence"); + } + + // A probe trigger on a temporary table of the owner's own session: the definer runs as its owner whoever calls it, + // so this observes exactly what the request guard's INSERT arm observes. + await using var owner = await OpenAsync(database.MigrationConnectionString); + await ExecuteAsync(owner, null, """ + CREATE TEMP TABLE status_probe (id uuid, status text); + CREATE FUNCTION pg_temp.status_probe() RETURNS trigger LANGUAGE plpgsql AS $probe$ + BEGIN NEW.status := COALESCE(public.fn_identity_user_status(NEW.id), 'none'); RETURN NEW; END $probe$; + CREATE TRIGGER status_probe BEFORE INSERT ON pg_temp.status_probe FOR EACH ROW EXECUTE FUNCTION pg_temp.status_probe(); + """); + Task Probe(NpgsqlTransaction transaction, Guid user) => + ScalarAsync(owner, transaction, "INSERT INTO pg_temp.status_probe(id) VALUES(@user) RETURNING status", ("user", user)); + + await using (var transaction = await owner.BeginTransactionAsync()) + { + (await Probe(transaction, PersonA)).Should().Be("none", "without the subject's User fence"); + await TakeAsync(owner, transaction, IdentityAdvisoryLockKey.ForUser(UserId.From(PersonA)), Mode.Shared); + (await Probe(transaction, PersonA)).Should().Be("none", "with the User fence held shared"); + await TakeAsync(owner, transaction, IdentityAdvisoryLockKey.ForUser(UserId.From(PersonA)), Mode.Exclusive); + (await Probe(transaction, PersonA)).Should().Be("Closing", "inside a trigger, under the exclusive fence"); + (await ScalarAsync(owner, transaction, Direct, ("user", PersonA))).Should().Be("none", "but never called directly"); + await TakeAsync(owner, transaction, IdentityAdvisoryLockKey.ForUser(UserId.From(PersonB)), Mode.Exclusive); + (await Probe(transaction, PersonB)).Should().Be("Active"); + var unknown = Guid.CreateVersion7(); + await TakeAsync(owner, transaction, IdentityAdvisoryLockKey.ForUser(UserId.From(unknown)), Mode.Exclusive); + (await Probe(transaction, unknown)).Should().Be("none", "no such User"); + await transaction.RollbackAsync(); + } + + await MoveAsync(database, PersonA, Closed, (SchemaFixture.TenantA, Mode.Exclusive), (SchemaFixture.TenantB, Mode.Exclusive)); + await using (var transaction = await owner.BeginTransactionAsync()) + { + await TakeAsync(owner, transaction, IdentityAdvisoryLockKey.ForUser(UserId.From(PersonA)), Mode.Exclusive); + (await Probe(transaction, PersonA)).Should().Be("Closed"); + await transaction.RollbackAsync(); + } + + (await SchemaQueries.ReadStringsAsync(owner, """ + SELECT concat_ws(':', pg_get_userbyid(p.proowner), p.prosecdef, p.provolatile, array_to_string(p.proconfig, ','), + r.rolbypassrls, has_function_privilege('learnstack_app', p.oid, 'EXECUTE'), + has_function_privilege('learnstack_platform', p.oid, 'EXECUTE'), + has_function_privilege('learnstack_outbox_admin', p.oid, 'EXECUTE'), + has_function_privilege('learnstack_identity_ingress', p.oid, 'EXECUTE'), + has_function_privilege('learnstack_identity_rebind', p.oid, 'EXECUTE'), + EXISTS (SELECT 1 FROM aclexplode(COALESCE(p.proacl, acldefault('f', p.proowner))) a WHERE a.grantee = 0), + pg_get_function_result(p.oid)) + FROM pg_proc p JOIN pg_roles r ON r.oid = p.proowner + WHERE p.oid = 'public.fn_identity_user_status(uuid)'::regprocedure + """)).Should().Equal(["learnstack_migration:t:v:search_path=pg_catalog:f:t:f:f:f:f:f:text"]); + } + + private static Task InsertFanOutAsync(NpgsqlConnection app, NpgsqlTransaction transaction, Guid id, Guid tenant, Guid? organization, + Guid subject, Guid membership, string kind = "erasure", string origin = "closure_fanout", string status = "fulfilling", + Guid? requester = null, DateTime? executeAt = null, Guid? creator = null) => + ExecuteAsync(app, transaction, FanOutInsert, ("id", id), ("tenant", tenant), ("organization", organization), ("kind", kind), + ("origin", origin), ("subject", subject), ("requester", requester), ("status", status), + ("snapshot", Snapshot(membership)), ("execute", executeAt), ("creator", creator ?? SystemActor)); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureStorageTests.Grants.cs b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureStorageTests.Grants.cs new file mode 100644 index 000000000..796dcc175 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureStorageTests.Grants.cs @@ -0,0 +1,154 @@ +using System.Reflection; +using FluentAssertions; +using LearnStack.Modules.Identity.Infrastructure.DataRequests; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class AccountClosureStorageTests +{ + /// + /// ADR-0107 § 8's platform grants, read from the attribute ACLs: column SELECT on users and memberships, + /// the last-administrator predicate's columns of the assignment, Role and grant tables, UPDATE of status and + /// provider_subject on users, and EXECUTE on the two lock observers; nothing table-wide, nothing on the + /// profile or the authority anchor. With them the role reads a person's participant groups in every tenant, a Revoked + /// tombstone's included, through the Membership user index, and nothing more. + /// + [Fact] + public async Task The_platform_role_holds_exactly_the_closed_columns_and_the_two_lock_observers() + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(schema.Postgres); + await ArrangeAsync(database); + await using var owner = await OpenAsync(database.MigrationConnectionString); + (await SchemaQueries.ReadStringsAsync(owner, """ + SELECT c.relname || '.' || a.attname || ':' || x.privilege_type + FROM pg_class c JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped + CROSS JOIN LATERAL aclexplode(a.attacl) x + WHERE c.relnamespace = 'public'::regnamespace + AND c.relname IN ('users','memberships','membership_profiles','membership_role_assignments','roles', + 'role_permission_grants','identity_authority') + AND x.grantee = 'learnstack_platform'::regrole + ORDER BY 1 + """)).Should().Equal( + "membership_role_assignments.membership_id:SELECT", "membership_role_assignments.role_id:SELECT", + "membership_role_assignments.tenant_id:SELECT", + "memberships.deleted_at:SELECT", "memberships.id:SELECT", "memberships.organization_id:SELECT", + "memberships.status:SELECT", "memberships.tenant_id:SELECT", "memberships.user_id:SELECT", + "role_permission_grants.permission_key:SELECT", "role_permission_grants.permission_scope:SELECT", + "role_permission_grants.role_id:SELECT", "role_permission_grants.tenant_id:SELECT", + "roles.built_in_key:SELECT", "roles.deleted_at:SELECT", "roles.deleted_by:SELECT", "roles.id:SELECT", + "roles.permission_scope:SELECT", "roles.tenant_id:SELECT", + "users.id:SELECT", "users.provider_subject:SELECT", "users.provider_subject:UPDATE", "users.status:SELECT", + "users.status:UPDATE", "users.subject_key:SELECT"); + (await SchemaQueries.ReadStringsAsync(owner, """ + SELECT c.relname || ':' || x.privilege_type + FROM pg_class c CROSS JOIN LATERAL aclexplode(c.relacl) x + WHERE c.relnamespace = 'public'::regnamespace + AND c.relname IN ('users','memberships','membership_profiles','membership_role_assignments','roles', + 'role_permission_grants','identity_authority') + AND x.grantee = 'learnstack_platform'::regrole + """)).Should().BeEmpty("no table-wide privilege: the role bypasses row security, so its column grants are its whole bound"); + (await SchemaQueries.ReadStringsAsync(owner, """ + SELECT p.oid::regprocedure::text + FROM pg_proc p CROSS JOIN LATERAL aclexplode(COALESCE(p.proacl, acldefault('f', p.proowner))) x + WHERE p.pronamespace = 'public'::regnamespace AND p.proname LIKE 'fn_identity_%' + AND x.grantee = 'learnstack_platform'::regrole AND x.privilege_type = 'EXECUTE' + ORDER BY 1 + """)).Should().Equal("fn_identity_contextual_lock_key(text,uuid)", "fn_identity_lock_held(text,uuid,boolean)"); + + await using var platform = await OpenAsync(database.PlatformConnectionString); + (await ScalarAsync(platform, null, """ + SELECT string_agg(grp, ',' ORDER BY grp COLLATE "C") FROM (SELECT DISTINCT member.tenant_id::text || '/' + || COALESCE(member.organization_id::text, '-') AS grp FROM public.memberships AS member WHERE member.user_id=@user) AS groups + """, ("user", PersonA))).Should().Be(string.Join(',', new[] + { + $"{SchemaFixture.TenantA:D}/-", $"{SchemaFixture.TenantA:D}/{SchemaFixture.OrgA1:D}", + $"{SchemaFixture.TenantA:D}/{SchemaFixture.OrgA2:D}", $"{SchemaFixture.TenantB:D}/-", + }.Order(StringComparer.Ordinal)), "every group of the person in every tenant, the Revoked tombstone's included, with no announcement"); + (await ScalarAsync(platform, null, """ + SELECT status || ':' || (provider_subject IS NOT NULL)::text || ':' || octet_length(subject_key)::text + FROM public.users WHERE id=@user + """, ("user", PersonA))).Should().Be("Active:true:32"); + + foreach (var statement in new[] + { + "SELECT * FROM public.users", "SELECT authority_id FROM public.users", "SELECT row_version FROM public.users", + "SELECT * FROM public.memberships", "SELECT created_by FROM public.memberships", "SELECT deleted_by FROM public.memberships", + "SELECT count(*) FROM public.membership_profiles", "SELECT organization_id FROM public.membership_role_assignments", + "SELECT created_at FROM public.roles", "SELECT count(*) FROM public.identity_authority", + "UPDATE public.users SET row_version=0", "INSERT INTO public.users(id) VALUES(uuidv7())", "DELETE FROM public.users", + "UPDATE public.memberships SET status='Active'", "DELETE FROM public.memberships", "UPDATE public.roles SET built_in_key=built_in_key", + "DELETE FROM public.membership_role_assignments", "INSERT INTO public.role_permission_grants(tenant_id) VALUES(uuidv7())", + }) + { + await using var transaction = await platform.BeginTransactionAsync(); + var act = () => ExecuteAsync(platform, transaction, statement); + (await act.Should().ThrowAsync(statement)).Which.SqlState.Should().Be("42501", statement); + } + + // The participant read is served by the Membership user index, as are the trigger's and the guard's fence checks. + await using (var transaction = await platform.BeginTransactionAsync()) + { + await ExecuteAsync(platform, transaction, "SET LOCAL enable_seqscan = off"); + (await ScalarAsync(platform, transaction, """ + EXPLAIN (FORMAT JSON) SELECT 1 FROM public.memberships AS member WHERE member.user_id = @user GROUP BY member.tenant_id + """, ("user", PersonA))).Should().Contain("ix_memberships_user_id"); + } + } + + /// + /// The last-administrator judgment of a participant tenant runs on the platform connection over exactly the predicate of + /// the deferred complete-graph guard, less member.deleted_by IS NULL, which ck_memberships_lifecycle makes + /// redundant beside member.status = 'Active' and which the role cannot read; it answers as the application role's + /// tenant-announced read answers. + /// + [Fact] + public async Task The_last_administrator_predicate_reads_the_same_answer_on_the_platform_connection() + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(schema.Postgres); + var standing = (string)typeof(DataRequestStore).GetField("AdministratorStanding", BindingFlags.Static | BindingFlags.NonPublic)! + .GetValue(null)!; + const string Redundant = " AND member.deleted_by IS NULL"; + standing.IndexOf(Redundant, StringComparison.Ordinal).Should().BeGreaterThan(0) + .And.Be(standing.LastIndexOf(Redundant, StringComparison.Ordinal), "the predicate names the Membership's deleter exactly once"); + var platformStanding = standing.Replace(Redundant, string.Empty, StringComparison.Ordinal); + + await using var platform = await OpenAsync(database.PlatformConnectionString); + await using (var transaction = await platform.BeginTransactionAsync()) + { + var verbatim = () => StandingAsync(platform, transaction, standing, SchemaFixture.TenantA, AdminA); + (await verbatim.Should().ThrowAsync()).Which.SqlState.Should().Be("42501", + "the deleter of a Membership is not among the role's columns"); + } + + await using var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString); + foreach (var (tenant, subject, expected) in new[] + { + (SchemaFixture.TenantA, AdminA, "True:False"), (SchemaFixture.TenantA, PersonA, "False:True"), + (SchemaFixture.TenantB, AdminB, "True:False"), (SchemaFixture.TenantB, PersonB, "False:True"), + }) + { + await using (var read = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, read, tenant); + (await StandingAsync(app, read, standing, tenant, subject)).Should().Be(expected); + } + + await using var transaction = await platform.BeginTransactionAsync(); + (await StandingAsync(platform, transaction, platformStanding, tenant, subject)).Should().Be(expected, + "the platform connection reads the application's answer for every tenant without announcing any"); + } + } + + private static async Task StandingAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, string sql, Guid tenant, Guid subject) + { + await using var command = new NpgsqlCommand(sql, connection, transaction); + command.Parameters.AddWithValue("tenant", tenant); + command.Parameters.AddWithValue("subject", subject); + await using var row = await command.ExecuteReaderAsync(); + (await row.ReadAsync()).Should().BeTrue(); + return (row.GetBoolean(0) ? "True" : "False") + ":" + (row.GetBoolean(1) ? "True" : "False"); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureStorageTests.Hardening.cs b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureStorageTests.Hardening.cs new file mode 100644 index 000000000..2a767f73f --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureStorageTests.Hardening.cs @@ -0,0 +1,106 @@ +using FluentAssertions; +using Xunit; +using static LearnStack.Tests.Integration.Database.DataRequestSchemaSeed; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// 20261123130000_harden_closure_request_guard on real PostgreSQL as the application role: a closure the platform +/// made fulfilling takes no application write at all, so its Begin moment, its result and its version are written +/// only by the platform's arrows, while a scheduled closure and every other kind keep their application arms; and the +/// INSERT arm answers a refused snapshot before it asks the subject's status, so the two refusals reveal no status. +/// +public sealed partial class AccountClosureStorageTests +{ + /// + /// Every status-preserving write of a begun closure (its result, its update stamp alone, a refusal code) is refused with + /// the transition refusal, under the fences an application writer holds; a scheduled closure's stamp, its cancellation + /// and a fulfilling erasure's result stay admitted. + /// + [Fact] + public async Task A_begun_closure_takes_no_application_write_and_a_scheduled_one_keeps_its_arms() + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(schema.Postgres); + var arranged = await ArrangeAsync(database); + await MoveAsync(database, PersonA, Close, (SchemaFixture.TenantA, Mode.Exclusive), (SchemaFixture.TenantB, Mode.Exclusive)); + await PlatformCommitAsync(database, FullFencesOfPersonA, Format(Begin), arranged.DueClosureA); + var begun = await RequestStateAsync(database, SchemaFixture.TenantA, null, arranged.DueClosureA); + begun.Status.Should().Be("fulfilling", "the platform's Begin arrow made it fulfilling"); + var fulfilling = Guid.CreateVersion7(); + await using var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString); + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, SchemaFixture.TenantA, SchemaFixture.OrgA2, PersonA); + await InsertFanOutAsync(app, transaction, fulfilling, SchemaFixture.TenantA, SchemaFixture.OrgA2, PersonA, BranchMembershipA2); + await transaction.CommitAsync(); + } + + foreach (var (set, because) in new[] + { + ("result='{\"consent_evidence\":7}'", "a result no participant produced"), + ("status=status", "a later update stamp, which is the Begin moment Finalize reads"), + ("last_refusal='blocked_hold'", "a refusal code"), + }) + { + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, SchemaFixture.TenantA, null, PersonA); + var refusal = await DataExportTestKit.RefuseAsync(transaction, () => StepAsync(app, transaction, arranged.DueClosureA, set)); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", Transition), because); + } + + (await RequestStateAsync(database, SchemaFixture.TenantA, null, arranged.DueClosureA)).Should().Be(begun, + "nothing the application role sent reached the begun closure"); + + // The application's arms that stay: a scheduled closure's own write and its cancellation in its window, and a + // fulfilling erasure's result, which is the job's. + foreach (var (tenant, organization, id, set) in new (Guid, Guid?, Guid, string)[] + { + (SchemaFixture.TenantA, SchemaFixture.OrgA1, arranged.PendingClosureA1, "status=status"), + (SchemaFixture.TenantA, SchemaFixture.OrgA1, arranged.PendingClosureA1, "status='cancelled'"), + (SchemaFixture.TenantA, SchemaFixture.OrgA2, fulfilling, "result='{\"consent_evidence\":7}'"), + }) + { + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, tenant, organization, PersonA); + await StepAsync(app, transaction, id, set); + await transaction.RollbackAsync(); + } + } + + /// + /// A filing whose snapshot is wrong is refused for its snapshot whatever the subject's status, so the refusal says + /// nothing about whether the person's account is closing; with the exact snapshot, a Closing subject is refused as not + /// admitted and an Active one is admitted. + /// + [Fact] + public async Task A_refused_snapshot_is_answered_before_the_subject_s_status_is_asked() + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(schema.Postgres); + await ArrangeAsync(database); + await MoveAsync(database, PersonA, Close, (SchemaFixture.TenantA, Mode.Exclusive), (SchemaFixture.TenantB, Mode.Exclusive)); + await using var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString); + + foreach (var (subject, tenant, organization, membership, reason, because) in new (Guid, Guid, Guid?, Guid, string, string)[] + { + (PersonA, SchemaFixture.TenantA, null, Guid.CreateVersion7(), "Data request snapshot refused.", "a Closing subject, a wrong snapshot"), + (PersonB, SchemaFixture.TenantB, SchemaFixture.OrgB1, Guid.CreateVersion7(), "Data request snapshot refused.", "an Active subject, a wrong snapshot"), + (PersonA, SchemaFixture.TenantA, null, LearnerMembershipA, NotAdmitted, "a Closing subject, the exact snapshot"), + }) + { + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, tenant, organization, subject); + var refusal = await DataExportTestKit.RefuseAsync(transaction, () => + InsertRequestAsync(app, transaction, Guid.CreateVersion7(), tenant, organization, subject, [membership], "erasure")); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", reason), because); + } + + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, SchemaFixture.TenantB, SchemaFixture.OrgB1, PersonB); + await InsertRequestAsync(app, transaction, Guid.CreateVersion7(), SchemaFixture.TenantB, SchemaFixture.OrgB1, PersonB, + [BranchMembershipB], "erasure"); + await transaction.RollbackAsync(); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureStorageTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureStorageTests.cs new file mode 100644 index 000000000..9e10bf8ea --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AccountClosureStorageTests.cs @@ -0,0 +1,407 @@ +using System.Globalization; +using FluentAssertions; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; +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 §§ 7 and 8 and ADR-0072 Amendment 8, on real PostgreSQL as each real role: the platform role's closed-column +/// grants, the one users trigger exception, the request guard's closure arrows and the fan-out erasure's INSERT +/// witness. Every arrow is admitted with its exact witnesses and refused with each one removed alone. +/// +/// +/// +/// Each case runs in its own disposable copy of the seeded schema, because a User a closure moved never returns to Active. +/// Person A holds Memberships in tenant A (tenant-wide and both branches) and a Revoked tombstone of a tenant-wide +/// Membership of tenant B, so tenant B is one of person A's participants through the tombstone alone. Person B holds one +/// Membership, in tenant B's branch. A closure of person A is due in tenant A's tenant-wide group and another is still +/// in its window in branch A1; a closure of person B is due in branch B1. +/// +/// +/// The platform role holds its fences the way the closure's acquirer does: transaction-scoped advisory locks, the User key +/// first and the tenant keys after it, ascending by key. A refusal probe rolls back. +/// +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed partial class AccountClosureStorageTests(SchemaFixture schema) +{ + private const string NoOwner = "Identity bindings have no admitted update or removal owner."; + private const string Close = "UPDATE public.users SET status='Closing' WHERE id=@user"; + private const string Closed = "UPDATE public.users SET status='Closed', provider_subject=NULL WHERE id=@user"; + + private const string RevokeSql = """ + UPDATE public.memberships SET status='Revoked', deleted_at=clock_timestamp(), deleted_by=@system, + updated_at=clock_timestamp(), updated_by=@system, row_version=row_version+1 + WHERE id=@member + """; + + private enum Mode { None, Shared, Exclusive } + + private sealed record Arranged(Guid ForeignMembership, Guid DueClosureA, Guid PendingClosureA1, Guid DueClosureB); + + /// + /// The User trigger exception: the platform session moves a User Active to Closing and Closing to Closed only with the + /// subject's User key and the key of every participant tenant held exclusively, changes nothing but the two columns, + /// and stamps the bookkeeping itself. Each condition is removed alone. + /// + [Fact] + public async Task The_platform_session_moves_a_User_only_by_the_two_transitions_under_every_participant_fence() + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(schema.Postgres); + await ArrangeAsync(database); + var before = await UserStateAsync(database, PersonA); + + // Each fence removed alone, or held shared: the User key, the tenant key of a live Membership's tenant, and the + // tenant key of the tenant person A holds only a Revoked tombstone in. + foreach (var (user, tenantA, tenantB, reason, because) in new (Mode, Mode, Mode, string, string)[] + { + (Mode.None, Mode.Exclusive, Mode.Exclusive, "User closure fence refused.", "without the User key"), + (Mode.Shared, Mode.Exclusive, Mode.Exclusive, "User closure fence refused.", "with the User key held shared"), + (Mode.Exclusive, Mode.Exclusive, Mode.None, "User closure tenant fence refused.", "without the tombstone tenant's key"), + (Mode.Exclusive, Mode.None, Mode.Exclusive, "User closure tenant fence refused.", "without the live tenant's key"), + (Mode.Exclusive, Mode.Shared, Mode.Exclusive, "User closure tenant fence refused.", "with a tenant key held shared"), + (Mode.Exclusive, Mode.Exclusive, Mode.Shared, "User closure tenant fence refused.", "with the tombstone tenant's key shared"), + }) + { + var refusal = await PlatformRefusedAsync(database, PersonAFences(user, tenantA, tenantB), Close, ("user", PersonA)); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", reason), because); + } + + // Every transition but the two, each with every fence held. + foreach (var (sql, because) in new[] + { + ("UPDATE public.users SET status='Closed', provider_subject=NULL WHERE id=@user", "Active to Closed skips Closing"), + ("UPDATE public.users SET status='Active' WHERE id=@user", "Active to Active is no transition"), + ("UPDATE public.users SET status='Closing', provider_subject=NULL WHERE id=@user", "Active to Closing keeps the subject"), + ("UPDATE public.users SET status='Closing', provider_subject='another-subject' WHERE id=@user", + "Active to Closing cannot rewrite the subject"), + }) + { + var refusal = await PlatformRefusedAsync(database, FullFencesOfPersonA, sql, ("user", PersonA)); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", "User closure transition refused."), because); + } + + await using (var platform = await OpenAsync(database.PlatformConnectionString)) + await using (var transaction = await platform.BeginTransactionAsync()) + { + await FullFencesOfPersonA(platform, transaction); + await ExecuteAsync(platform, transaction, Close, ("user", PersonA)); + foreach (var (sql, because) in new[] + { + ("UPDATE public.users SET status='Active' WHERE id=@user", "nothing returns to Active"), + ("UPDATE public.users SET status='Closing' WHERE id=@user", "Closing to Closing is no transition"), + ("UPDATE public.users SET status='Closed' WHERE id=@user", "Closed removes the raw subject"), + }) + { + var refusal = await DataExportTestKit.RefuseAsync(transaction, () => ExecuteAsync(platform, transaction, sql, ("user", PersonA))); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", "User closure transition refused."), because); + } + + await ExecuteAsync(platform, transaction, Closed, ("user", PersonA)); + foreach (var (sql, because) in new[] + { + ("UPDATE public.users SET status='Closing' WHERE id=@user", "Closed never reopens"), + ("UPDATE public.users SET status='Active' WHERE id=@user", "Closed never returns to Active"), + ("UPDATE public.users SET status='Closed' WHERE id=@user", "Closed to Closed is no transition"), + }) + { + var refusal = await DataExportTestKit.RefuseAsync(transaction, () => ExecuteAsync(platform, transaction, sql, ("user", PersonA))); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", "User closure transition refused."), because); + } + + await transaction.RollbackAsync(); + } + + // Only the two columns: a third is refused by the grant, and, with the grant widened in this disposable database, + // by the trigger itself. The bookkeeping columns are the trigger's to stamp, never the statement's. + foreach (var column in new[] { "row_version=row_version+1", "updated_at=now()", "subject_key=subject_key", "authority_id=authority_id" }) + { + var refusal = await PlatformRefusedAsync(database, FullFencesOfPersonA, $"UPDATE public.users SET status='Closing',{column} WHERE id=@user", + ("user", PersonA)); + refusal.SqlState.Should().Be("42501", column); + } + + await using (var owner = await OpenAsync(database.MigrationConnectionString)) + await ExecuteAsync(owner, null, "GRANT UPDATE (row_version, created_at, updated_by) ON public.users TO learnstack_platform"); + try + { + // Constants and the readable id only: the role still reads none of these columns. + foreach (var column in new[] { "row_version=99", "created_at='2001-01-01T00:00:00Z'", "updated_by=id" }) + { + var refusal = await PlatformRefusedAsync(database, FullFencesOfPersonA, + $"UPDATE public.users SET status='Closing',{column} WHERE id=@user", ("user", PersonA)); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", "User closure column refused."), column); + } + } + finally + { + await using var owner = await OpenAsync(database.MigrationConnectionString); + await ExecuteAsync(owner, null, "REVOKE UPDATE (row_version, created_at, updated_by) ON public.users FROM learnstack_platform"); + } + + // Admitted, committed, and stamped by the trigger: the version steps once per transition, the update is the + // system actor's, and the key, the authority and the creation evidence stay as the tombstone. + await MoveAsync(database, PersonA, Close, (SchemaFixture.TenantA, Mode.Exclusive), (SchemaFixture.TenantB, Mode.Exclusive)); + var closing = await UserStateAsync(database, PersonA); + closing.UpdatedAt.Should().NotBeNull(); + closing.Should().Be(before with { Status = "Closing", Version = before.Version + 1, UpdatedBy = SystemActor, UpdatedAt = closing.UpdatedAt }, + "Active to Closing keeps the raw subject and changes nothing else the statement could reach"); + await MoveAsync(database, PersonA, Closed, (SchemaFixture.TenantA, Mode.Exclusive), (SchemaFixture.TenantB, Mode.Exclusive)); + var closed = await UserStateAsync(database, PersonA); + closed.Should().Be(closing with { Status = "Closed", SubjectPresent = false, Version = before.Version + 2, UpdatedAt = closed.UpdatedAt }, + "Closing to Closed removes the raw subject and keeps the key and actor as the permanent tombstone"); + closed.UpdatedAt.Should().BeOnOrAfter(closing.UpdatedAt!.Value); + } + + /// + /// The exception is the platform session's alone: the application role, the migration owner and a superuser session + /// switched to the platform role are refused while holding every fence, and DELETE and TRUNCATE stay refused for + /// every role, the platform role included once its grant is widened in this disposable database. + /// + [Fact] + public async Task Every_other_session_and_every_removal_is_refused_even_under_every_fence() + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(schema.Postgres); + await ArrangeAsync(database); + + // The application role holds no UPDATE on users at all; widened to the status column and reading its own row + // through its identity announcement, it reaches the trigger, which refuses it. + await using (var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await AnnounceAsync(app, transaction, PersonA); + await FullFencesOfPersonA(app, transaction); + (await DataExportTestKit.RefuseAsync(transaction, () => ExecuteAsync(app, transaction, Close, ("user", PersonA)))) + .SqlState.Should().Be("42501", "the application role cannot make a User Closing"); + } + + await using (var owner = await OpenAsync(database.MigrationConnectionString)) + await ExecuteAsync(owner, null, "GRANT UPDATE (status) ON public.users TO learnstack_app"); + try + { + await using var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await AnnounceAsync(app, transaction, PersonA); + await FullFencesOfPersonA(app, transaction); + (await ScalarAsync(app, transaction, "SELECT count(*) FROM public.users WHERE id=@user", ("user", PersonA))) + .Should().Be(1, "the application role sees the row it would change, so only the trigger can refuse it"); + var refusal = await DataExportTestKit.RefuseAsync(transaction, () => ExecuteAsync(app, transaction, Close, ("user", PersonA))); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", NoOwner)); + } + finally + { + await using var owner = await OpenAsync(database.MigrationConnectionString); + await ExecuteAsync(owner, null, "REVOKE UPDATE (status) ON public.users FROM learnstack_app"); + } + + // The migration owner holds every privilege and reads every row; the trigger refuses it. + await using (var owner = await OpenAsync(database.MigrationConnectionString)) + await using (var transaction = await owner.BeginTransactionAsync()) + { + await FullFencesOfPersonA(owner, transaction); + var refusal = await DataExportTestKit.RefuseAsync(transaction, () => ExecuteAsync(owner, transaction, Close, ("user", PersonA))); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", NoOwner)); + } + + // A session whose current role is the platform role but whose login is not: the superuser, switched. + var keys = new[] { IdentityAdvisoryLockKey.ForUser(UserId.From(PersonA)) } + .Concat(new[] { SchemaFixture.TenantA, SchemaFixture.TenantB }.Select(tenant => IdentityAdvisoryLockKey.ForTenant(TenantId.From(tenant))).Order()) + .Select(key => $"SELECT pg_catalog.pg_advisory_xact_lock({key.ToString(CultureInfo.InvariantCulture)});"); + var switched = () => schema.Postgres.ExecuteAsSuperuserAsync( + $"BEGIN; SET LOCAL ROLE learnstack_platform; {string.Join(' ', keys)} " + + $"UPDATE public.users SET status='Closing' WHERE id='{PersonA:D}'; COMMIT;", + new NpgsqlConnectionStringBuilder(database.MigrationConnectionString).Database); + (await switched.Should().ThrowAsync()).Which.Message.Should().Be("Superuser statement failed (SQLSTATE 23514).", + "the trigger requires the platform login itself, not only its current role"); + + // Removal: refused by the missing grant, and by the trigger once the grant is widened. + string[] references = ["users", "memberships", "membership_profiles", "membership_role_assignments", "invitations", + "data_subject_requests", "data_export_artifacts", "data_export_tickets", "data_export_chunks"]; + // The users table first, so its own statement trigger is the first TRUNCATE trigger to fire. + var truncate = "TRUNCATE " + string.Join(", ", references.Select(table => "public." + table)); + var delete = $"DELETE FROM public.users WHERE id='{PersonA:D}'"; + foreach (var sql in new[] { delete, truncate }) + (await PlatformRefusedAsync(database, FullFencesOfPersonA, sql)).SqlState.Should().Be("42501", sql); + await using (var owner = await OpenAsync(database.MigrationConnectionString)) + await ExecuteAsync(owner, null, $""" + GRANT DELETE ON public.users TO learnstack_platform; + GRANT TRUNCATE ON {string.Join(", ", references.Select(table => "public." + table))} TO learnstack_platform; + """); + try + { + foreach (var sql in new[] { delete, truncate }) + { + var refusal = await PlatformRefusedAsync(database, FullFencesOfPersonA, sql); + (refusal.SqlState, refusal.MessageText).Should().Be(("23514", NoOwner), sql); + } + } + finally + { + await using var owner = await OpenAsync(database.MigrationConnectionString); + await ExecuteAsync(owner, null, $""" + REVOKE DELETE ON public.users FROM learnstack_platform; + REVOKE TRUNCATE ON {string.Join(", ", references.Select(table => "public." + table))} FROM learnstack_platform; + """); + } + + (await UserStateAsync(database, PersonA)).Status.Should().Be("Active", "nothing above changed the User"); + } + + /// + /// A subject with no Membership has no participant to fence and no closure to file (ADR-0107 § 10 gives that person to + /// Phase 11): an UPDATE with no fence at all is refused, and one holding the User key is refused for the empty set. + /// + [Fact] + public async Task A_subject_with_no_Membership_is_never_moved() + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(schema.Postgres); + var lonely = Guid.CreateVersion7(); + await InsertUserAsync(database.AppConnectionString, lonely); + + var unfenced = await PlatformRefusedAsync(database, (_, _) => Task.CompletedTask, Close, ("user", lonely)); + (unfenced.SqlState, unfenced.MessageText).Should().Be(("23514", "User closure fence refused.")); + var fenced = await PlatformRefusedAsync(database, (connection, transaction) => ClosureFencesAsync(connection, transaction, lonely, Mode.Exclusive), + Close, ("user", lonely)); + (fenced.SqlState, fenced.MessageText).Should().Be(("23514", "User closure participant refused.")); + (await UserStateAsync(database, lonely)).Status.Should().Be("Active"); + } + + /// Person A's tombstone in tenant B, and the three closures, two of them past their window. + private static async Task ArrangeAsync(DisposableSchemaDatabase database, bool pendingDue = false) + { + var arranged = new Arranged(Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.CreateVersion7()); + await using var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString); + await using (var transaction = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, transaction, SchemaFixture.TenantB); + await LockAsync(app, transaction, SchemaFixture.TenantB, PersonA, false); + await InsertMemberAsync(app, transaction, SchemaFixture.TenantB, null, arranged.ForeignMembership, PersonA, + RoleId(SchemaFixture.TenantB, BuiltInRoleKey.Learner, PermissionScope.Tenant)); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await transaction.CommitAsync(); + } + + await using (var transaction = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, transaction, SchemaFixture.TenantB); + await LockAsync(app, transaction, SchemaFixture.TenantB, PersonA, false); + await ExecuteAsync(app, transaction, RevokeSql, ("member", arranged.ForeignMembership), ("system", SystemActor)); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await transaction.CommitAsync(); + } + + (Guid Id, Guid Tenant, Guid? Organization, Guid Subject, Guid Membership, bool Due)[] closures = + [ + (arranged.DueClosureA, SchemaFixture.TenantA, null, PersonA, LearnerMembershipA, true), + (arranged.PendingClosureA1, SchemaFixture.TenantA, SchemaFixture.OrgA1, PersonA, BranchMembershipA1, pendingDue), + (arranged.DueClosureB, SchemaFixture.TenantB, SchemaFixture.OrgB1, PersonB, BranchMembershipB, true), + ]; + foreach (var closure in closures) + { + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, closure.Tenant, closure.Organization, closure.Subject); + await InsertRequestAsync(app, transaction, closure.Id, closure.Tenant, closure.Organization, closure.Subject, + [closure.Membership], "closure"); + await transaction.CommitAsync(); + } + + // What a closure filed 25 hours ago looks like: backdated by the owner with the one guard paused, then restored. + await using var owner = await 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"); + foreach (var closure in closures.Where(closure => closure.Due)) + { + await ScopeAsync(owner, transaction, closure.Tenant, closure.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", closure.Id)); + } + await ExecuteAsync(owner, transaction, "ALTER TABLE public.data_subject_requests ENABLE TRIGGER tg_data_subject_requests_mutation_guard"); + await transaction.CommitAsync(); + } + + return arranged; + } + + /// + /// The closure's fences on one transaction, as its acquirer takes them: the subject's User key first, then each tenant + /// key ascending by key, each in its own mode; leaves a key out. + /// + private static async Task ClosureFencesAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, Guid subject, Mode user, + params (Guid Tenant, Mode Mode)[] tenants) + { + await TakeAsync(connection, transaction, IdentityAdvisoryLockKey.ForUser(UserId.From(subject)), user); + foreach (var (tenant, mode) in tenants.OrderBy(entry => IdentityAdvisoryLockKey.ForTenant(TenantId.From(entry.Tenant)))) + await TakeAsync(connection, transaction, IdentityAdvisoryLockKey.ForTenant(TenantId.From(tenant)), mode); + } + + private static Task TakeAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, long key, Mode mode) => mode switch + { + Mode.None => Task.CompletedTask, + Mode.Shared => ExecuteAsync(connection, transaction, "SELECT pg_catalog.pg_advisory_xact_lock_shared(@key)", ("key", key)), + _ => ExecuteAsync(connection, transaction, "SELECT pg_catalog.pg_advisory_xact_lock(@key)", ("key", key)), + }; + + private static Func PersonAFences(Mode user, Mode tenantA, Mode tenantB) => + (connection, transaction) => ClosureFencesAsync(connection, transaction, PersonA, user, + (SchemaFixture.TenantA, tenantA), (SchemaFixture.TenantB, tenantB)); + + private static Task FullFencesOfPersonA(NpgsqlConnection connection, NpgsqlTransaction transaction) => + PersonAFences(Mode.Exclusive, Mode.Exclusive, Mode.Exclusive)(connection, transaction); + + /// Runs one statement on a fresh platform transaction holding , expects the refusal and rolls back. + private static async Task PlatformRefusedAsync(DisposableSchemaDatabase database, + Func fences, string sql, params (string Name, object? Value)[] values) + { + await using var platform = await OpenAsync(database.PlatformConnectionString); + await using var transaction = await platform.BeginTransactionAsync(); + await fences(platform, transaction); + var act = () => ExecuteAsync(platform, transaction, sql, values); + return (await act.Should().ThrowAsync(sql)).Which; + } + + /// Commits one User statement on the platform role under the subject's User key and the given tenant keys. + private static async Task MoveAsync(DisposableSchemaDatabase database, Guid user, string sql, params (Guid Tenant, Mode Mode)[] tenants) + { + await using var platform = await OpenAsync(database.PlatformConnectionString); + await using var transaction = await platform.BeginTransactionAsync(); + await ClosureFencesAsync(platform, transaction, user, Mode.Exclusive, tenants); + await ExecuteAsync(platform, transaction, sql, ("user", user)); + await transaction.CommitAsync(); + } + + private sealed record UserState(string Status, bool SubjectPresent, long Version, Guid? UpdatedBy, DateTime? UpdatedAt, string Tombstone); + + /// The User row as the owner reads it, the permanent columns folded into one comparable value. + private static async Task UserStateAsync(DisposableSchemaDatabase database, Guid user) + { + await using var owner = await OpenAsync(database.MigrationConnectionString); + await using var command = new NpgsqlCommand(""" + SELECT status, provider_subject IS NOT NULL, row_version, updated_by, updated_at, + concat_ws(':', id, authority_id, encode(subject_key, 'hex'), creation_audit_id, creation_audit_timestamp, created_at, created_by) + FROM public.users WHERE id=@user + """, owner); + command.Parameters.AddWithValue("user", user); + await using var row = await command.ExecuteReaderAsync(); + (await row.ReadAsync()).Should().BeTrue(); + return new UserState(row.GetString(0), row.GetBoolean(1), row.GetInt64(2), row.IsDBNull(3) ? null : row.GetGuid(3), + row.IsDBNull(4) ? null : row.GetDateTime(4), row.GetString(5)); + } + + /// Announces person A's own verified identity, so the application role sees exactly its own User row. + private static Task AnnounceAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, Guid user) => + GlobalIdentitySchemaTests.AnnounceAsync(connection, transaction, + new GlobalIdentitySubject(Authority.AuthorityId, Authority.Issuer, "fixture-subject-" + user.ToString("N"))); + + private static async Task OpenAsync(string connectionString) => + (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AuditRedactionCanaryTests.Batches.cs b/backend/tests/LearnStack.Tests.Integration/Database/AuditRedactionCanaryTests.Batches.cs new file mode 100644 index 000000000..5cc36279b --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AuditRedactionCanaryTests.Batches.cs @@ -0,0 +1,286 @@ +using System.Text.Json.Nodes; +using FluentAssertions; +using LearnStack.Infrastructure.Audit; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Platform; +using Microsoft.Extensions.Logging; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class AuditRedactionCanaryTests +{ + // Sizes small enough that a few dozen rows cross every kind of batch boundary the executor can draw. + private const int TinyBatchRows = 3; + private const long TinyBatchBytes = 6_000; + private const int TinyUpdateRows = 2; + + [Fact] + public async Task Small_batches_and_chunks_select_and_redact_exactly_what_one_batch_does() + { + // The same rows in a rolled-back transaction each: through the production sizes, which read this tenant in one + // batch; through batches of three rows or six kilobytes and UPDATEs of two keys; and through each budget alone. + var tenant = Guid.CreateVersion7(); + var rows = Batched(tenant, Guid.CreateVersion7()); + var single = await BatchRunAsync(tenant, rows, Executor()); + var tiny = await BatchRunAsync(tenant, rows, + new AuditRedactionExecutor(Registered.Value, TinyBatchRows, TinyBatchBytes, TinyUpdateRows), plan: true, again: true); + var rowsOnly = await BatchRunAsync(tenant, rows, + new AuditRedactionExecutor(Registered.Value, TinyBatchRows, long.MaxValue, TinyUpdateRows)); + var bytesOnly = await BatchRunAsync(tenant, rows, + new AuditRedactionExecutor(Registered.Value, int.MaxValue, TinyBatchBytes, TinyUpdateRows)); + + // The data crosses every boundary it claims to, by the executor's documented rule read from the stored sizes. + var batches = tiny.Planned!; + var label = rows.ToDictionary(row => row.Id); + batches.Count.Should().BeGreaterThan(6, "the rows span many small batches"); + batches.SkipLast(1).Should().Contain(batch => label[batch[batch.Count - 1].Id].Selected, "a boundary falls exactly on a selected row"); + batches.Zip(batches.Skip(1)).Should().Contain(pair => pair.First[pair.First.Count - 1].Timestamp == pair.Second[0].Timestamp, + "a block of identical timestamps straddles a boundary"); + batches.SkipLast(1).Should().Contain(batch => batch.Count < TinyBatchRows && batch.Count > 1, + "the byte budget ends a batch before the row cap"); + batches.Should().Contain(batch => batch.Count == 1 && batch[0].Bytes > TinyBatchBytes, + "a single row larger than the budget is a batch of its own"); + batches.Should().Contain(batch => batch.Count(row => label[row.Id].Selected) > TinyUpdateRows, + "one batch selects more rows than one UPDATE rewrites"); + + // And the executor drew exactly them. Each batch starts exactly one boundary statement, so the statements the + // connection ran are the batches drawn: the one-batch run draws one, and a last batch the rule closes is followed by + // an empty one. Counting statements, not scans of an index, keeps the proof independent of the planner, whose choice + // among the tenant, actor and entity indexes moves with table statistics. With both budgets there are more + // batches than with either alone. + var iterations = batches.Count + (Closed(batches[^1]) ? 1 : 0); + single.Boundaries.Should().Be(1, "the production sizes read this tenant in one batch"); + tiny.Boundaries.Should().Be(iterations, "the executor draws the {0} batches the rule draws", iterations); + tiny.Boundaries.Should().BeGreaterThan(rowsOnly.Boundaries, "the byte budget ends batches") + .And.BeGreaterThan(bytesOnly.Boundaries, "the row cap ends batches"); + single.Scans.Should().BeGreaterThan(0, "the reads were served by an index, since the planner may not scan sequentially"); + tiny.Scans.Should().BeGreaterThan(single.Scans, "many batches start many more index scans than one"); + + // Exactly the selected rows change, and every run leaves every row as the one batch does and reports the same. + tiny.After.Where(entry => entry.Value != tiny.Before[entry.Key]).Select(entry => label[entry.Key].Label).Should() + .BeEquivalentTo(rows.Where(row => row.Selected).Select(row => row.Label), "exactly the selected rows change"); + foreach (var run in new[] { tiny, rowsOnly, bytesOnly }) + { + run.After.Should().Equal(single.After); + run.Report.RowsSelected.Should().Be(rows.Count(row => row.Selected)).And.Be(single.Report.RowsSelected); + run.Report.Redacted.Should().Equal(single.Report.Redacted); + Retained(run.Report).Should().Equal(Retained(single.Report)); + } + + foreach (var row in rows.Where(row => row.Selected)) + { + var after = tiny.After[row.Id]; + (after.IpAddress, after.UserAgent, after.ActorEmail).Should().Be((null, null, null), row.Label); + new[] { after.BeforeText, after.AfterText, after.ChangesText }.Should() + .NotContain(text => text != null && text.Contains(Text(Subject), StringComparison.OrdinalIgnoreCase), row.Label); + } + + Retained(tiny.Report)[RetainedReferenceKind.AuditMetadataReference].Should() + .Be(rows.Count(row => row.Tenant == tenant && row.Label.Contains("metadata", StringComparison.Ordinal))); + tiny.Again!.Redacted.Values.Should().AllSatisfy(count => count.Should().Be(0), "a second run changes no row"); + Retained(tiny.Again).Should().Equal(Retained(tiny.Report)); + tiny.AfterAgain.Should().Equal(tiny.After); + } + + /// One executor's run over the rows: what it reported, what the rows read before and after, and how many + /// scans of the timestamp index and how many boundary statements it started; optionally the planned batches and a + /// second run's report. + private sealed record BatchRun(AuditRedactionReport Report, Dictionary Before, Dictionary After, + long Scans, int Boundaries, List>? Planned, AuditRedactionReport? Again, Dictionary? AfterAgain); + + private async Task BatchRunAsync(Guid tenant, List rows, AuditRedactionExecutor executor, bool plan = false, + bool again = false) + { + // An executor that never moved its upper bound would loop; the token turns that into a failure. + using var deadline = new CancellationTokenSource(TimeSpan.FromMinutes(2)); + using var statements = new StatementLog(); + await using var source = new NpgsqlDataSourceBuilder(schema.Postgres.PlatformConnectionString) + .UseLoggerFactory(LoggerFactory.Create(builder => builder.SetMinimumLevel(LogLevel.Debug).AddProvider(statements))) + .Build(); + var connection = await source.OpenConnectionAsync(); + await using var scope = new Scope(connection, await connection.BeginTransactionAsync()); + + // The scan count is the proof, so the planner may not pick another access path for a statement: a sequential or + // bitmap scan on a small or freshly analysed table would otherwise make the count depend on statistics. + await using (var settings = new NpgsqlCommand("SET LOCAL enable_seqscan = off; SET LOCAL enable_bitmapscan = off", scope.Connection, + scope.Transaction)) + await settings.ExecuteNonQueryAsync(); + await InsertAsync(scope, rows); + var before = await ReadAsync(scope, rows); + var planned = plan ? await PlannedBatchesAsync(scope, tenant) : null; + var scans = await ScansAsync(scope); + statements.Clear(); + var report = await executor.RedactAsync(Plan(tenant, DataRequestOrigin.Self, null), Spent(PlatformOperations.ErasureComplete), + scope.Connection, scope.Transaction, deadline.Token); + scans = await ScansAsync(scope) - scans; + var boundaries = statements.Count(BoundaryMarker); + var after = await ReadAsync(scope, rows); + var second = again + ? await executor.RedactAsync(Plan(tenant, DataRequestOrigin.Self, null), Spent(PlatformOperations.ErasureComplete), + scope.Connection, scope.Transaction, deadline.Token) + : null; + var afterAgain = again ? await ReadAsync(scope, rows) : null; + await scope.Transaction.RollbackAsync(); + return new BatchRun(report, before, after, scans, boundaries, planned, second, afterAgain); + } + + /// + /// Rows of one tenant, newest first one second apart, that name the subject as actor, as entity and in a payload, name + /// it only in metadata, or name someone else; two of them large enough to end a batch on bytes, one larger than the + /// whole budget, and a block of six sharing one timestamp. Another tenant's rows sit at the same times. + /// + private static List Batched(Guid tenant, Guid foreign) + { + var subject = Text(Subject); + var administrator = Text(OtherPerson); + var start = DateTime.SpecifyKind(DateTime.UtcNow.AddHours(-1), DateTimeKind.Utc); + start = start.AddTicks(-(start.Ticks % TimeSpan.TicksPerMillisecond)); + var tie = start.AddSeconds(-10); + var next = 0; + DateTime At() => start.AddSeconds(-next++); + static string Noise(int characters) => + string.Concat(Enumerable.Range(0, (characters / 32) + 1).Select(_ => Guid.NewGuid().ToString("N")))[..characters]; + JsonObject Course(string creator, int noise = 0) => new() + { + ["Id"] = Guid.CreateVersion7().ToString("D"), + ["CreatedBy"] = creator, + ["UpdatedBy"] = administrator, + ["Description"] = noise > 0 ? Noise(noise) : "short", + }; + + CanaryRow Actor(string label, DateTime at, int noise = 0) => + new(label, tenant, null, Subject, "Course", Guid.CreateVersion7().ToString("D"), null, Course(administrator, noise), null, + null, Selected: true, null, null, null) + { At = at }; + CanaryRow Payload(string label, DateTime at, int noise = 0) => + new(label, tenant, null, OtherPerson, "Course", Guid.CreateVersion7().ToString("D"), Course(subject, noise), + Course(subject, noise), null, null, Selected: true, null, null, null) + { At = at }; + CanaryRow Entity(string label, DateTime at, Guid membership) => + new(label, tenant, null, OtherPerson, "Membership", Text(membership), + new JsonObject { ["Id"] = Text(membership), ["UserId"] = subject, ["UpdatedBy"] = administrator }, null, null, null, + Selected: true, null, null, null) + { At = at }; + CanaryRow Metadata(string label, DateTime at) => + new(label, tenant, null, UserId.SystemActor.Value, "Course", Guid.CreateVersion7().ToString("D"), null, + Course(administrator), null, $$"""{"causal_actor_user_id":"{{subject}}"}""", Selected: false, null, null, null) + { + At = at, + Attributed = false, + }; + CanaryRow Other(string label, DateTime at, int noise = 0) => + new(label, tenant, null, OtherPerson, "Course", Guid.CreateVersion7().ToString("D"), null, Course(administrator, noise), null, + null, Selected: false, null, null, null) + { At = at }; + + List rows = + [ + Actor("actor 1", At()), Other("other 1", At()), Payload("payload 1", At()), + Other("large other", At(), noise: 3_500), Payload("large payload", At(), noise: 3_500), + Actor("oversized actor", At(), noise: 9_000), + Metadata("metadata 1", At()), Entity("entity 1", At(), Membership1), + .. Tied(Actor("tie actor 1", tie), Payload("tie payload 1", tie), Entity("tie entity", tie, Membership2), + Actor("tie actor 2", tie), Metadata("tie metadata", tie), Payload("tie payload 2", tie)), + ]; + next = 11; + rows.AddRange( + [ + Other("other 2", At()), Actor("actor 2", At()), Metadata("metadata 2", At()), Payload("payload 2", At()), + Other("other 3", At()), Other("other 4", At()), Entity("entity 2", At(), Membership1), Actor("actor 3", At()), + Payload("payload 3", At()), Other("other 5", At()), + ]); + rows.AddRange(rows.Where(row => row.Label.StartsWith("actor", StringComparison.Ordinal)).ToList() + .Select(row => Actor("foreign " + row.Label, row.At!.Value) with { Tenant = foreign, Selected = false })); + return rows; + } + + /// + /// Rows sharing one timestamp, given identifiers that order them as listed in the batches' order (newest first, so by + /// id descending): the boundaries then fall inside the block at known rows, whatever identifiers are drawn. + /// + private static IEnumerable Tied(params CanaryRow[] rows) + { + var identifiers = rows.Select(_ => Guid.CreateVersion7()).OrderByDescending(id => id.ToString("D"), StringComparer.Ordinal).ToList(); + return rows.Select((row, index) => row with { Id = identifiers[index] }); + } + + /// Whether the rule closes a planned batch at its last row (a full batch), rather than the rows running out. + private static bool Closed(List batch) => batch.Count == TinyBatchRows || batch.Sum(row => row.Bytes) >= TinyBatchBytes; + + /// The text only the executor's boundary statement carries. + private const string BoundaryMarker = "count(*) OVER batch"; + + /// The commands one connection completed, as the driver logs them. + private sealed class StatementLog : ILoggerProvider, ILogger + { + private readonly System.Collections.Concurrent.ConcurrentQueue _commands = new(); + + public ILogger CreateLogger(string categoryName) => this; + + public void Clear() => _commands.Clear(); + + /// The commands that ran to completion and carry ; the start of each is logged too. + public int Count(string marker) => _commands.Count(command => + command.StartsWith("Command execution completed", StringComparison.Ordinal) && command.Contains(marker, StringComparison.Ordinal)); + + public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Debug; + + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) => + _commands.Enqueue(formatter(state, exception)); + + public void Dispose() + { + } + } + + /// One row as the batches order and size it. + private sealed record BatchRow(Guid Id, DateTime Timestamp, long Bytes); + + /// + /// The batches the executor's documented rule draws over the tenant's rows, newest first by ("timestamp", id): + /// a batch ends at the row that makes it rows or brings its stored payload to + /// . + /// + private static async Task>> PlannedBatchesAsync(Scope scope, Guid tenant) + { + await using var command = new NpgsqlCommand(""" + SELECT a.id, a."timestamp", COALESCE(pg_column_size(a.before_state), 0) + COALESCE(pg_column_size(a.after_state), 0) + + COALESCE(pg_column_size(a.changes), 0) + FROM public.audit_log AS a WHERE a.tenant_id = @tenant ORDER BY a."timestamp" DESC, a.id DESC + """, scope.Connection, scope.Transaction); + command.Parameters.AddWithValue("tenant", tenant); + var batches = new List> { new() }; + long bytes = 0; + await using var reader = await command.ExecuteReaderAsync(); + while (await reader.ReadAsync()) + { + var row = new BatchRow(reader.GetGuid(0), reader.GetDateTime(1), reader.GetInt32(2)); + batches[^1].Add(row); + bytes += row.Bytes; + if (batches[^1].Count == TinyBatchRows || bytes >= TinyBatchBytes) + { + batches.Add([]); + bytes = 0; + } + } + + return [.. batches.Where(batch => batch.Count > 0)]; + } + + /// + /// How many scans of ix_audit_log_tenant_id_timestamp this transaction has started so far: every batch's + /// boundary statement starts one, so the count bounds the batches the executor drew from below. + /// + private static async Task ScansAsync(Scope scope) + { + await using var command = new NpgsqlCommand( + "SELECT pg_stat_get_xact_numscans('public.ix_audit_log_tenant_id_timestamp'::regclass)", scope.Connection, scope.Transaction); + return (long)(await command.ExecuteScalarAsync())!; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AuditRedactionCanaryTests.Capture.cs b/backend/tests/LearnStack.Tests.Integration/Database/AuditRedactionCanaryTests.Capture.cs new file mode 100644 index 000000000..1d2d7dedd --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AuditRedactionCanaryTests.Capture.cs @@ -0,0 +1,102 @@ +using System.Text.Json.Nodes; +using FluentAssertions; +using LearnStack.Infrastructure.Audit; +using LearnStack.Infrastructure.Audit.Capture; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.Modules.Tenancy.Domain; +using LearnStack.Modules.Tenancy.Infrastructure.Persistence; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Entitlements; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Secrets; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class AuditRedactionCanaryTests +{ + [Fact] + public async Task Real_captures_are_redacted_at_every_path_shape() + { + // The generated canaries above are built in the capture's shape; this is that shape as the capture writes it, for + // each form of the grammar: a property (a request's subject and requester), an array of identifiers (its frozen + // Memberships) and a contained collection's member (a tenant's feature flags, keyed by flag). + var tenant = Guid.CreateVersion7(); + var clock = new FixedClock(DateTimeOffset.UtcNow); + var request = DataSubjectRequest.FileForSubject(DataSubjectRequestId.From(Guid.CreateVersion7()), DataRequestKind.Erasure, + UserId.From(OtherPerson), UserId.From(Subject), new DataRequestScopeGroup(TenantId.From(tenant), null), + [MembershipId.From(Membership1), MembershipId.From(Membership2)], clock.UtcNow).Value!; + var aggregate = Tenant.Create(TenantId.From(tenant), "canary-" + tenant.ToString("N")[..12], "Canary", clock, UserId.From(OtherPerson)); + aggregate.SetFeatureFlag(FeatureKeys.LessonPlayerV2, "true", clock, UserId.From(Subject)); + aggregate.SetFeatureFlag(FeatureKeys.AiPronunciationFeedback, "false", clock, UserId.From(OtherPerson)); + + var captured = new[] { await CaptureAsync(IdentityModel(), request), await CaptureAsync(TenancyModel(), aggregate) }; + var rows = captured.Select(change => new CanaryRow("captured " + change.EntityType, tenant, null, OtherPerson, change.EntityType, + change.EntityId!, Parse(change.BeforeJson), Parse(change.AfterJson), Parse(Diff(change.Fields)), null, Selected: true, + null, null, null)).ToList(); + + await using var scope = await OpenAsync(schema.Postgres.PlatformConnectionString); + await InsertAsync(scope, rows); + var report = await RedactAsync(scope, Plan(tenant, DataRequestOrigin.Self, organization: null)); + var after = await ReadAsync(scope, rows); + + report.RowsSelected.Should().Be(2); + var sentinel = SensitiveTokenCatalog.RedactedValue; + var dsr = after[rows[0].Id]; + var state = Parse(dsr.AfterText)!.AsObject(); + state["SubjectUserId"]!.GetValue().Should().Be(sentinel); + state["RequesterUserId"]!.GetValue().Should().Be(Text(OtherPerson), "the administrator who filed it is another person"); + state["CreatedBy"]!.GetValue().Should().Be(Text(OtherPerson)); + state["MembershipSnapshotJson"]!.AsArray().Select(element => element!.GetValue()).Should().Equal(sentinel, sentinel); + dsr.ChangesText.Should().NotContain(Text(Subject)).And.NotContain(Text(Membership1)).And.NotContain(Text(Membership2)) + .And.Contain(Text(OtherPerson)); + + var tenantRow = after[rows[1].Id]; + var flags = Parse(tenantRow.AfterText)!["FeatureFlags"]!.AsObject(); + flags[FeatureKeys.LessonPlayerV2.Value]!["UpdatedBy"]!.GetValue().Should().Be(sentinel); + flags[FeatureKeys.AiPronunciationFeedback.Value]!["UpdatedBy"]!.GetValue().Should().Be(Text(OtherPerson)); + tenantRow.ChangesText.Should().NotContain(Text(Subject)).And.Contain( + "/Tenant/" + tenant.ToString("D") + "/FeatureFlags/" + FeatureKeys.LessonPlayerV2.Value + "/UpdatedBy"); + tenantRow.AfterText.Should().NotContain(Text(Subject)); + await scope.Transaction.RollbackAsync(); + } + + /// Runs the real capture over one new aggregate on a model-only context, as a save would. + private async Task CaptureAsync(DbContext context, object aggregate) + { + await using var source = ApplicationDataSource.Build(schema.Postgres.AppConnectionString); + var unit = new NpgsqlUnitOfWork(source, NullLogger.Instance); + var capture = new AuditStateCapture(); + await using (context) + { + context.Add(aggregate); + new AuditChangeTrackerInterceptor(capture, unit).Capture(context); + } + + return capture.Changes.Should().ContainSingle(change => change.EntityType == aggregate.GetType().Name).Subject; + } + + /// The changes column the composer writes from one capture's fields (AuditDraftComposer). + private static string? Diff(IReadOnlyList fields) => + fields.Count == 0 + ? null + : "[" + string.Join(',', fields.Select(field => "{\"path\":" + AuditJson.Quote(field.Path) + ",\"before\":" + + (field.BeforeJson ?? AuditJson.Null) + ",\"after\":" + (field.AfterJson ?? AuditJson.Null) + "}")) + "]"; + + private static JsonNode? Parse(string? json) => json is null ? null : JsonNode.Parse(json); + + private static IdentityDbContext IdentityModel() => + new(new DbContextOptionsBuilder().UseNpgsql("Host=model-only;Database=model-only;Username=model-only").Options, + StaticTenantContextAccessor.Unresolved, EmptyIdentityScope.Instance); + + private static TenancyDbContext TenancyModel() => + new(new DbContextOptionsBuilder().UseNpgsql("Host=model-only;Database=model-only;Username=model-only").Options, + StaticTenantContextAccessor.Unresolved); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AuditRedactionCanaryTests.Closure.cs b/backend/tests/LearnStack.Tests.Integration/Database/AuditRedactionCanaryTests.Closure.cs new file mode 100644 index 000000000..efa5ae391 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AuditRedactionCanaryTests.Closure.cs @@ -0,0 +1,69 @@ +using FluentAssertions; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Platform; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class AuditRedactionCanaryTests +{ + [Fact] + public async Task A_closure_tenant_pass_redacts_exactly_what_the_whole_tenant_erasure_does_across_every_group_and_nothing_else() + { + // ADR-0108 § 4: a closure's tenant pass is the whole-tenant selection with every Membership the person holds in + // the tenant, so one pass covers all of the person's groups there. The same rows, in a rolled-back transaction + // each, go through a person's own erasure over the tenant-wide group and through the closure's pass: every declared + // path's canary, the reach cases in two organizations and at the tenant level (a Membership of each group as + // entity), another tenant's rows naming the same person, and a platform sentinel row whose actor is the person. + var tenant = Guid.CreateVersion7(); + var foreign = Guid.CreateVersion7(); + var rows = Reach(tenant, foreign, Guid.CreateVersion7(), Guid.CreateVersion7()) + .Concat(Registered.Value.SelectMany(locator => locator.Redactable).SelectMany(declaration => Canary(declaration, tenant))) + .Append(new CanaryRow("sentinel/actor", TenantId.PlatformSentinel.Value, null, Subject, "Course", + Guid.CreateVersion7().ToString("D"), null, null, null, null, Selected: false, null, null, null)) + .ToList(); + var selected = rows.Where(row => row.Selected && row.Tenant == tenant).Select(row => row.Label).ToList(); + + var erasure = await TenantPassAsync(rows, Plan(tenant, DataRequestOrigin.Self, organization: null), PlatformOperations.ErasureComplete); + var closure = await TenantPassAsync(rows, ClosureTenantPlan(tenant), PlatformOperations.ClosureFinalize); + + closure.Changed.Should().BeEquivalentTo(selected, "the pass changes exactly the rows naming the person in the tenant"); + closure.Changed.Should().BeEquivalentTo(erasure.Changed); + closure.After.Should().Equal(erasure.After, "each row's six columns read as the whole-tenant erasure leaves them"); + closure.Report.RowsSelected.Should().Be(erasure.Report.RowsSelected).And.Be(selected.Count); + closure.Report.Redacted.Should().Equal(erasure.Report.Redacted); + Retained(closure.Report).Should().Equal(Retained(erasure.Report)).And.ContainKeys( + RetainedReferenceKind.AuditActorReference, RetainedReferenceKind.AuditEntityReference, RetainedReferenceKind.AuditMetadataReference) + .And.NotContainKey(RetainedReferenceKind.UnscopedAuditRows, "a closure's pass reaches its whole tenant"); + rows.Where(row => row.Tenant != tenant).Select(row => row.Label).Should().NotIntersectWith(closure.Changed, + "another tenant's rows and the platform sentinel's are outside the pass"); + closure.Again.Redacted.Values.Should().AllSatisfy(count => count.Should().Be(0), "a repeated pass rewrites nothing"); + closure.AfterAgain.Should().Equal(closure.After); + } + + /// One redaction's run over the rows: the labels it changed, every row's six columns after it, and a re-run's. + private sealed record TenantPass(AuditRedactionReport Report, List Changed, Dictionary After, + AuditRedactionReport Again, Dictionary AfterAgain); + + private async Task TenantPassAsync(List rows, AuditRedactionPlan plan, PlatformOperation operation) + { + await using var scope = await OpenAsync(schema.Postgres.PlatformConnectionString); + await InsertAsync(scope, rows); + var before = await ReadAsync(scope, rows); + var report = await Executor().RedactAsync(plan, Spent(operation), scope.Connection, scope.Transaction); + var after = await ReadAsync(scope, rows); + var again = await Executor().RedactAsync(plan, Spent(operation), scope.Connection, scope.Transaction); + var afterAgain = await ReadAsync(scope, rows); + await scope.Transaction.RollbackAsync(); + + // The six columns only: the rest of a row carries the insert's own clock, which differs between the two runs. + static Dictionary Columns(Dictionary read) => read.ToDictionary(entry => entry.Key, + entry => string.Join('|', entry.Value.IpAddress, entry.Value.UserAgent, entry.Value.ActorEmail, entry.Value.BeforeText, + entry.Value.AfterText, entry.Value.ChangesText)); + + return new TenantPass(report, [.. rows.Where(row => after[row.Id] != before[row.Id]).Select(row => row.Label)], Columns(after), + again, Columns(afterAgain)); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AuditRedactionCanaryTests.Compression.cs b/backend/tests/LearnStack.Tests.Integration/Database/AuditRedactionCanaryTests.Compression.cs new file mode 100644 index 000000000..c896baad8 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AuditRedactionCanaryTests.Compression.cs @@ -0,0 +1,154 @@ +using System.Text.Json.Nodes; +using FluentAssertions; +using LearnStack.Infrastructure.Audit; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Platform; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class AuditRedactionCanaryTests +{ + // Forty payloads of 200,000 repeated characters: each compresses to a few kilobytes, so by stored size the whole + // tenant is far below this budget, and by decompressed size every second row reaches it. + private const int SqueezedRows = 40; + private const int SqueezedCharacters = 200_000; + private const long SqueezedBudget = 300_000; + + [Fact] + public async Task A_byte_budget_counts_a_compressed_payload_at_its_decompressed_size() + { + var tenant = Guid.CreateVersion7(); + var rows = Squeezed(tenant); + var single = await SqueezedRunAsync(tenant, rows, Executor()); + var budgeted = await SqueezedRunAsync(tenant, rows, + new AuditRedactionExecutor(Registered.Value, int.MaxValue, SqueezedBudget, 1_000)); + + // The rows are what the case claims: compressed, at under a twentieth of their decompressed size, so a budget read + // from stored sizes would draw one batch where the decompressed rule draws one per two rows. + budgeted.Sizes.Should().HaveCount(rows.Count); + budgeted.Sizes.Should().OnlyContain(size => size.Compressed && size.Stored * 20 < size.Decompressed, + "a payload of repeated characters is stored compressed"); + Batches(budgeted.Sizes.Select(size => size.Stored)).Should().Be(1, "stored sizes alone never reach the budget"); + var planned = Batches(budgeted.Sizes.Select(size => size.Decompressed)); + planned.Should().Be(SqueezedRows / 2); + + // Every batch's boundary statement reads the log at least once, whatever plan serves it: the executor drew at + // least the planned batches, where a stored-size budget would have drawn one. + budgeted.Scans.Should().BeGreaterThanOrEqualTo(planned, "the budget is reached by decompressed bytes"); + + budgeted.After.Should().Equal(single.After); + budgeted.Report.RowsSelected.Should().Be(rows.Count(row => row.Selected)).And.Be(single.Report.RowsSelected); + budgeted.Report.Redacted.Should().Equal(single.Report.Redacted); + Retained(budgeted.Report).Should().Equal(Retained(single.Report)); + rows.Where(row => budgeted.After[row.Id] != budgeted.Before[row.Id]).Select(row => row.Label).Should() + .BeEquivalentTo(rows.Where(row => row.Selected).Select(row => row.Label), "exactly the selected rows change"); + + // Outside the reach a payload is never walked, so it counts no bytes: an organization group's request over the + // same tenant-level rows draws one batch, where counting them would draw the twenty above. + var branch = await SqueezedRunAsync(tenant, rows, + new AuditRedactionExecutor(Registered.Value, int.MaxValue, SqueezedBudget, 1_000), Guid.CreateVersion7()); + branch.Report.RowsSelected.Should().Be(0, "every row is at the tenant level, outside the organization group"); + branch.Scans.Should().BeLessThan(planned, "rows outside the reach end no batch"); + } + + /// + /// Rows one second apart, newest first, each a Course whose state holds repeated + /// characters; the subject created three of them and acted in one, and everyone else's are left alone. + /// + private static List Squeezed(Guid tenant) + { + var start = DateTime.SpecifyKind(DateTime.UtcNow.AddHours(-2), DateTimeKind.Utc); + start = start.AddTicks(-(start.Ticks % TimeSpan.TicksPerMillisecond)); + var description = new string('a', SqueezedCharacters); + return + [ + .. Enumerable.Range(0, SqueezedRows).Select(index => + { + var creator = index % 13 == 1 ? Subject : OtherPerson; + var actor = index == 20 ? Subject : ThirdPerson; + var state = new JsonObject + { + ["Id"] = Guid.CreateVersion7().ToString("D"), + ["Description"] = description, + ["CreatedBy"] = Text(creator), + ["UpdatedBy"] = Text(OtherPerson), + }; + return new CanaryRow($"squeezed {index}", tenant, null, actor, "Course", Guid.CreateVersion7().ToString("D"), null, + state, null, null, Selected: creator == Subject || actor == Subject, null, null, null) + { + At = start.AddSeconds(-index), + }; + }), + ]; + } + + /// How many batches the documented rule draws over sizes taken newest first, by bytes alone. + private static int Batches(IEnumerable sizes) + { + var (batches, open, bytes) = (0, false, 0L); + foreach (var size in sizes) + { + (open, bytes) = (true, bytes + size); + if (bytes >= SqueezedBudget) + { + (batches, open, bytes) = (batches + 1, false, 0L); + } + } + + return batches + (open ? 1 : 0); + } + + /// One row's payload as stored: whether it is compressed, its stored size and its decompressed size. + private sealed record PayloadSize(bool Compressed, long Stored, long Decompressed); + + /// One executor's run over the rows in its own rolled-back transaction. + private sealed record SqueezedRun(AuditRedactionReport Report, Dictionary Before, Dictionary After, + long Scans, List Sizes); + + private async Task SqueezedRunAsync(Guid tenant, List rows, AuditRedactionExecutor executor, + Guid? organization = null) + { + // An executor that never moved its upper bound would loop; the token turns that into a failure. + using var deadline = new CancellationTokenSource(TimeSpan.FromMinutes(2)); + await using var scope = await OpenAsync(schema.Postgres.PlatformConnectionString); + await InsertAsync(scope, rows); + var before = await ReadAsync(scope, rows); + var sizes = new List(); + await using (var command = new NpgsqlCommand(""" + SELECT pg_column_compression(a.after_state) IS NOT NULL, pg_column_size(a.after_state), pg_column_size(a.after_state #> '{}') + FROM public.audit_log AS a WHERE a.tenant_id = @tenant ORDER BY a."timestamp" DESC, a.id DESC + """, scope.Connection, scope.Transaction)) + { + command.Parameters.AddWithValue("tenant", tenant); + await using var reader = await command.ExecuteReaderAsync(); + while (await reader.ReadAsync()) + { + sizes.Add(new PayloadSize(reader.GetBoolean(0), reader.GetInt32(1), reader.GetInt32(2))); + } + } + + var scans = await TableScansAsync(scope); + var plan = organization is null + ? Plan(tenant, DataRequestOrigin.Self, null) + : Plan(tenant, DataRequestOrigin.Administrator, organization); + var report = await executor.RedactAsync(plan, Spent(PlatformOperations.ErasureComplete), scope.Connection, scope.Transaction, + deadline.Token); + scans = await TableScansAsync(scope) - scans; + var after = await ReadAsync(scope, rows); + await scope.Transaction.RollbackAsync(); + return new SqueezedRun(report, before, after, scans, sizes); + } + + /// How many scans of audit_log, sequential or by any index, this transaction has started so far. + private static async Task TableScansAsync(Scope scope) + { + await using var command = new NpgsqlCommand(""" + SELECT COALESCE(seq_scan, 0) + COALESCE(idx_scan, 0) FROM pg_stat_xact_user_tables + WHERE schemaname = 'public' AND relname = 'audit_log' + """, scope.Connection, scope.Transaction); + return (long)(await command.ExecuteScalarAsync())!; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AuditRedactionCanaryTests.Lookup.cs b/backend/tests/LearnStack.Tests.Integration/Database/AuditRedactionCanaryTests.Lookup.cs new file mode 100644 index 000000000..ca2daaf44 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AuditRedactionCanaryTests.Lookup.cs @@ -0,0 +1,83 @@ +using FluentAssertions; +using LearnStack.Infrastructure.Audit; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Platform; +using Microsoft.Extensions.Logging; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class AuditRedactionCanaryTests +{ + private const string ContainmentMarker = "'lax $.**{1 to 3}') ?|"; + private const string SetMarker = "jsonb_array_elements_text("; + + /// + /// The cheap payload filter's two forms answer the same question. A closure's pass at the tenant bound (the subject's two + /// Memberships and 254 that no row names, so 514 spellings, which PostgreSQL hashes) selects and redacts exactly the + /// same rows, with the same report, through the containment test and through the set lookup, over rows that name the + /// subject as actor, as entity, in a payload and only in metadata. By default that pass takes the set lookup, and an + /// erasure's few identifiers keep the containment test. + /// + [Fact] + public async Task The_set_lookup_selects_and_redacts_exactly_what_the_containment_test_does() + { + var tenant = Guid.CreateVersion7(); + var rows = Batched(tenant, Guid.CreateVersion7()); + var plan = AuditRedactionPlan.ForClosureTenant(TenantId.From(tenant), UserId.From(Subject), + [Membership1, Membership2, .. Enumerable.Range(0, ClosureLimits.MaximumTenantMemberships - 2).Select(_ => Guid.CreateVersion7())]); + + var containment = await LookupRunAsync(rows, plan, PlatformOperations.ClosureFinalize, setLookupFrom: int.MaxValue); + var set = await LookupRunAsync(rows, plan, PlatformOperations.ClosureFinalize, setLookupFrom: 1); + var byDefault = await LookupRunAsync(rows, plan, PlatformOperations.ClosureFinalize, AuditRedactionExecutor.SetLookupFrom); + var erasure = await LookupRunAsync(rows, Plan(tenant, DataRequestOrigin.Self, null), PlatformOperations.ErasureComplete, + AuditRedactionExecutor.SetLookupFrom); + + (containment.Containment, containment.Set).Should().Match<(int Containment, int Set)>(count => count.Containment > 0 && count.Set == 0, + "the containment run used that form alone"); + (set.Containment, set.Set).Should().Match<(int Containment, int Set)>(count => count.Containment == 0 && count.Set > 0, + "the set run used that form alone"); + byDefault.Set.Should().BeGreaterThan(0, "a closure pass of the tenant bound takes the set lookup by default"); + erasure.Containment.Should().BeGreaterThan(0, "an erasure's two Memberships keep the containment test by default"); + erasure.Set.Should().Be(0); + + set.After.Should().Equal(containment.After); + byDefault.After.Should().Equal(containment.After); + var label = rows.ToDictionary(row => row.Id); + set.After.Where(entry => entry.Value != set.Before[entry.Key]).Select(entry => label[entry.Key].Label).Should() + .BeEquivalentTo(rows.Where(row => row.Selected).Select(row => row.Label), "exactly the selected rows change"); + set.Report.RowsSelected.Should().Be(containment.Report.RowsSelected).And.Be(rows.Count(row => row.Selected)); + set.Report.Redacted.Should().Equal(containment.Report.Redacted); + Retained(set.Report).Should().Equal(Retained(containment.Report)); + } + + /// One run's report, the rows before and after it, and how many selections each form of the filter ran. + private sealed record LookupRun(AuditRedactionReport Report, Dictionary Before, Dictionary After, + int Containment, int Set); + + /// The rows inserted and redacted by an executor with the given set-lookup bound, in a rolled-back transaction. + private async Task LookupRunAsync(List rows, AuditRedactionPlan plan, PlatformOperation operation, + int setLookupFrom) + { + using var deadline = new CancellationTokenSource(TimeSpan.FromMinutes(2)); + using var statements = new StatementLog(); + await using var source = new NpgsqlDataSourceBuilder(schema.Postgres.PlatformConnectionString) + .UseLoggerFactory(LoggerFactory.Create(builder => builder.SetMinimumLevel(LogLevel.Debug).AddProvider(statements))) + .Build(); + var connection = await source.OpenConnectionAsync(); + await using var scope = new Scope(connection, await connection.BeginTransactionAsync()); + await InsertAsync(scope, rows); + var before = await ReadAsync(scope, rows); + statements.Clear(); + var executor = new AuditRedactionExecutor(Registered.Value, AuditRedactionExecutor.BatchRows, AuditRedactionExecutor.BatchBytes, + AuditRedactionExecutor.UpdateRows, setLookupFrom); + var report = await executor.RedactAsync(plan, Spent(operation), scope.Connection, scope.Transaction, deadline.Token); + var run = new LookupRun(report, before, await ReadAsync(scope, rows), statements.Count(ContainmentMarker), + statements.Count(SetMarker)); + await scope.Transaction.RollbackAsync(); + return run; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AuditRedactionCanaryTests.Rows.cs b/backend/tests/LearnStack.Tests.Integration/Database/AuditRedactionCanaryTests.Rows.cs new file mode 100644 index 000000000..477730294 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AuditRedactionCanaryTests.Rows.cs @@ -0,0 +1,151 @@ +using System.Text.Json.Nodes; +using LearnStack.SharedKernel.Identifiers; +using Npgsql; +using NpgsqlTypes; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class AuditRedactionCanaryTests +{ + /// The reach cases: one row per way a row can name the subject, in two organizations, the tenant level and another tenant. + private static List Reach(Guid tenant, Guid foreign, Guid branch, Guid otherBranch) + { + var subject = Text(Subject); + var administrator = Text(OtherPerson); + JsonObject Course(string creator, string updater) => new() + { + ["Id"] = Guid.CreateVersion7().ToString("D"), + ["CreatedBy"] = creator, + ["UpdatedBy"] = updater, + ["DeletedBy"] = null, + }; + + CanaryRow Actor(string label, Guid owner, Guid? organization, string? metadata = null) => + new(label, owner, organization, Subject, "Course", Guid.CreateVersion7().ToString("D"), + Course(administrator, administrator), Course(administrator, subject), null, metadata, Selected: true, null, null, null); + + CanaryRow Entity(string label, Guid? organization, Guid membership) => + new(label, tenant, organization, OtherPerson, "Membership", Text(membership), + new JsonObject { ["Id"] = Text(membership), ["UserId"] = subject, ["UpdatedBy"] = administrator }, null, null, null, + Selected: true, null, null, null); + + CanaryRow Payload(string label, Guid owner, Guid? organization) => + new(label, owner, organization, OtherPerson, "Course", Guid.CreateVersion7().ToString("D"), + Course(subject, administrator), Course(subject, administrator), null, null, Selected: true, null, null, null); + + var elided = Actor("elided/branch", tenant, branch) with + { + Before = JsonNode.Parse("""{"_elided":true,"bytes":300000,"sha256":"00"}"""), + After = JsonNode.Parse("""{"_elided":true,"bytes":300001,"sha256":"01"}"""), + Changes = JsonNode.Parse("""[{"_elided":true,"bytes":600000,"sha256":"02"}]"""), + }; + return + [ + Actor("actor/branch", tenant, branch), + Actor("actor/other-branch", tenant, otherBranch), + Actor("actor/tenant", tenant, null), + Actor("actor+authorization/branch", tenant, branch, $$$"""{"authorization":{"memberships":["{{{Text(Membership1)}}}"]}}"""), + elided, + Entity("entity/branch", branch, Membership1), + Entity("entity/tenant", null, Membership2), + Payload("payload/branch", tenant, branch), + Payload("payload/other-branch", tenant, otherBranch), + Payload("payload/tenant", tenant, null), + new("metadata/branch", tenant, branch, UserId.SystemActor.Value, "Course", Guid.CreateVersion7().ToString("D"), + null, Course(administrator, Text(UserId.SystemActor.Value)), null, + $$"""{"causal_actor_user_id":"{{subject}}","job_id":"{{Guid.CreateVersion7()}}"}""", Selected: false, null, null, null) + { + Attributed = false, + }, + Actor("foreign/actor", foreign, null), + Payload("foreign/payload", foreign, null), + ]; + } + + private static async Task OpenAsync(string platformConnectionString) + { + var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(platformConnectionString); + return new Scope(connection, await connection.BeginTransactionAsync()); + } + + private static async Task InsertAsync(Scope scope, IEnumerable rows) + { + foreach (var row in rows) + { + await using var command = new NpgsqlCommand(""" + INSERT INTO public.audit_log (id, "timestamp", tenant_id, organization_id, actor_user_id, actor_email, module, operation, + operation_type, operation_class, entity_type, entity_id, outcome, before_state, after_state, changes, correlation_id, + ip_address, user_agent, metadata) + VALUES (@id, COALESCE(@at, clock_timestamp()), @tenant, @organization, @actor, @email, 'canary', 'canary.redaction.row', 'Update', 'Must', + @entity_type, @entity_id, 'success', @before, @after, @changes, @correlation, @address, @agent, @metadata) + """, scope.Connection, scope.Transaction); + command.Parameters.AddWithValue("id", row.Id); + command.Parameters.AddWithValue("at", NpgsqlDbType.TimestampTz, (object?)row.At ?? DBNull.Value); + command.Parameters.AddWithValue("tenant", row.Tenant); + command.Parameters.AddWithValue("organization", NpgsqlDbType.Uuid, (object?)row.Organization ?? DBNull.Value); + command.Parameters.AddWithValue("actor", NpgsqlDbType.Uuid, (object?)row.Actor ?? DBNull.Value); + command.Parameters.AddWithValue("email", NpgsqlDbType.Varchar, row.Attributed ? "actor@example.test" : DBNull.Value); + command.Parameters.AddWithValue("entity_type", row.EntityType); + command.Parameters.AddWithValue("entity_id", row.EntityId); + command.Parameters.AddWithValue("before", NpgsqlDbType.Jsonb, (object?)row.Before?.ToJsonString() ?? DBNull.Value); + command.Parameters.AddWithValue("after", NpgsqlDbType.Jsonb, (object?)row.After?.ToJsonString() ?? DBNull.Value); + command.Parameters.AddWithValue("changes", NpgsqlDbType.Jsonb, (object?)row.Changes?.ToJsonString() ?? DBNull.Value); + command.Parameters.AddWithValue("correlation", "00-" + row.Id.ToString("N") + "-01"); + command.Parameters.AddWithValue("address", NpgsqlDbType.Inet, + row.Attributed ? System.Net.IPAddress.Parse("198.51.100.7") : DBNull.Value); + command.Parameters.AddWithValue("agent", NpgsqlDbType.Varchar, row.Attributed ? "Canary/1.0" : DBNull.Value); + command.Parameters.AddWithValue("metadata", NpgsqlDbType.Jsonb, (object?)row.Metadata ?? DBNull.Value); + await command.ExecuteNonQueryAsync(); + } + } + + /// Every row's six redactable columns, and every other column as one canonical document. + private static async Task> ReadAsync(Scope scope, IEnumerable rows) + { + await using var command = new NpgsqlCommand(""" + SELECT a.id, host(a.ip_address), a.user_agent, a.actor_email, a.before_state::text, a.after_state::text, a.changes::text, + (to_jsonb(a) - 'ip_address' - 'user_agent' - 'actor_email' - 'before_state' - 'after_state' - 'changes')::text + FROM public.audit_log AS a WHERE a.id = ANY(@ids) + """, scope.Connection, scope.Transaction); + command.Parameters.AddWithValue("ids", rows.Select(row => row.Id).ToArray()); + var read = new Dictionary(); + await using var reader = await command.ExecuteReaderAsync(); + while (await reader.ReadAsync()) + { + read[reader.GetGuid(0)] = new Snapshot(Nullable(reader, 1), Nullable(reader, 2), Nullable(reader, 3), Nullable(reader, 4), + Nullable(reader, 5), Nullable(reader, 6), reader.GetString(7)); + } + + return read; + } + + private static string? Nullable(NpgsqlDataReader reader, int ordinal) => reader.IsDBNull(ordinal) ? null : reader.GetString(ordinal); + + /// A platform-role connection and the work transaction every case rolls back. + private sealed record Scope(NpgsqlConnection Connection, NpgsqlTransaction Transaction) : IAsyncDisposable + { + public async ValueTask DisposeAsync() + { + await Transaction.DisposeAsync(); + await Connection.DisposeAsync(); + } + } + + /// One audit row a case writes, and what its payload must read after the redaction. + private sealed record CanaryRow(string Label, Guid Tenant, Guid? Organization, Guid? Actor, string EntityType, string EntityId, + JsonNode? Before, JsonNode? After, JsonNode? Changes, string? Metadata, bool Selected, JsonNode? ExpectedBefore, + JsonNode? ExpectedAfter, JsonNode? ExpectedChanges) + { + public Guid Id { get; init; } = Guid.CreateVersion7(); + + /// Whether the row carries an address, an agent and an e-mail, as a row with an authenticated actor does. + public bool Attributed { get; init; } = true; + + /// The row's timestamp; the insert's clock when none is given. + public DateTime? At { get; init; } + } + + /// A row as read back: the six columns, and the rest canonical, so two readings compare by value. + private sealed record Snapshot(string? IpAddress, string? UserAgent, string? ActorEmail, string? BeforeText, string? AfterText, + string? ChangesText, string Retained); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AuditRedactionCanaryTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/AuditRedactionCanaryTests.cs new file mode 100644 index 000000000..5aed6a2ab --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/AuditRedactionCanaryTests.cs @@ -0,0 +1,419 @@ +using System.Text.Json.Nodes; +using FluentAssertions; +using LearnStack.Api.Composition; +using LearnStack.Infrastructure.Audit; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Secrets; +using LearnStack.Tests.Fixtures; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Npgsql; +using NpgsqlTypes; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// ADR-0108 §§ 4–7 against PostgreSQL: every path every registered declares is +/// redacted for the subject and left alone for anyone else, as learnstack_platform on a work transaction that +/// every case rolls back, so nothing the shared sweeps count moves. +/// +/// +/// +/// A canary per declared path, generated from the declaration. Each declaration gets a row in the capture's +/// exact shape (CapturedEntityChange: the entity's property, a contained collection's member keyed by its own +/// key with a / escaped as ~1 in the changes path, an array of identifiers) holding the subject's +/// identifier of the declaration's kind beside another person's at the same path, a twin holding only another +/// person's, and a twin holding the subject's identifier of the other kind. A declaration a module adds is a canary +/// here without a line of this file, and a shape the generator cannot build fails it, so no declared path goes +/// unproven. drives the real capture for each shape. +/// +/// +/// The rows' tenants are this class's own and not in tenants, which audit_log does not require. +/// +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed partial class AuditRedactionCanaryTests(SchemaFixture schema) +{ + private static readonly Lazy> Registered = new(RegisteredLocators); + + private static readonly string[] ModulesWithLocators = ["Customization", "Education", "Identity", "Tenancy"]; + + private static readonly Guid Subject = Guid.Parse("0190c0de-5b1e-7aaa-8000-00000000c0de"); + private static readonly Guid Membership1 = Guid.Parse("0190c0de-5b1e-7aaa-8000-0000000000a1"); + private static readonly Guid Membership2 = Guid.Parse("0190c0de-5b1e-7aaa-8000-0000000000a2"); + private static readonly Guid OtherPerson = Guid.Parse("0190adad-0000-7aaa-8000-00000000adad"); + private static readonly Guid ThirdPerson = Guid.Parse("0190bbbb-0000-7aaa-8000-00000000bbbb"); + private static readonly Guid OtherMembership = Guid.Parse("0190adad-0000-7aaa-8000-0000000000a9"); + + /// Every module that registers a locator through the API composition. + public static TheoryData LocatorModules() + { + var data = new TheoryData(); + foreach (var module in Registered.Value.Select(ModuleOf).Order(StringComparer.Ordinal)) + { + data.Add(module); + } + + return data; + } + + [Fact] + public void Every_module_with_a_locator_has_a_canary_and_every_declaration_a_case() + { + // The census over canary coverage: the theory below runs once per module that registers a locator, and each + // run generates one case per declaration, so a module or a declared path cannot go without a canary. + LocatorModules().Cast().Select(row => (string)row[0]).Should().BeEquivalentTo(ModulesWithLocators); + Registered.Value.Sum(locator => locator.Redactable.Count) + .Should().Be(new UserReferenceCatalog(Registered.Value).Redactable.Length); + Registered.Value.SelectMany(locator => locator.Redactable).Select(declaration => declaration.Path.Shape).Distinct() + .Should().BeEquivalentTo(Enum.GetValues(), + "the shipped declarations exercise every shape of the grammar"); + } + + [Theory] + [MemberData(nameof(LocatorModules))] + public async Task Every_declared_path_of_a_module_is_redacted_for_the_subject_only(string module) + { + var tenant = Guid.CreateVersion7(); + var declarations = Registered.Value.Single(locator => ModuleOf(locator) == module).Redactable; + declarations.Should().NotBeEmpty("a locator that lost every declaration would otherwise pass this module vacuously"); + var rows = declarations.SelectMany(declaration => Canary(declaration, tenant)).ToList(); + rows.Should().HaveCount(3 * declarations.Count); + + await using var scope = await OpenAsync(schema.Postgres.PlatformConnectionString); + await InsertAsync(scope, rows); + var before = await ReadAsync(scope, rows); + + var report = await RedactAsync(scope, Plan(tenant, DataRequestOrigin.Self, organization: null)); + + var after = await ReadAsync(scope, rows); + var own = rows.Where(row => row.Selected).ToList(); + own.Should().HaveCount(declarations.Count); + foreach (var row in rows) + { + var was = before[row.Id]; + var now = after[row.Id]; + now.Retained.Should().Be(was.Retained, "actor, entity, metadata and every column outside the grant survive ({0})", row.Label); + if (!row.Selected) + { + now.Should().Be(was, "a row that names the subject at no declared path of its kind is not touched ({0})", row.Label); + continue; + } + + (now.IpAddress, now.UserAgent, now.ActorEmail).Should().Be((null, null, null), row.Label); + JsonNode.DeepEquals(Parse(now.BeforeText), row.ExpectedBefore).Should().BeTrue("{0}: {1}", row.Label, now.BeforeText); + JsonNode.DeepEquals(Parse(now.AfterText), row.ExpectedAfter).Should().BeTrue("{0}: {1}", row.Label, now.AfterText); + JsonNode.DeepEquals(Parse(now.ChangesText), row.ExpectedChanges).Should().BeTrue("{0}: {1}", row.Label, now.ChangesText); + } + + report.RowsSelected.Should().Be(own.Count); + report.Redacted.Values.Should().AllSatisfy(count => count.Should().Be(own.Count), + "every canary row the subject is named in carries all six columns"); + Retained(report).Should().Equal(new Dictionary + { + [RetainedReferenceKind.AuditActorReference] = 0, + [RetainedReferenceKind.AuditEntityReference] = 0, + [RetainedReferenceKind.AuditMetadataReference] = 0, + }); + + // Idempotent: the re-run rewrites nothing. It selects nothing either, because a payload that no longer holds the + // subject's identifier no longer names the subject; a row the actor or the entity selects stays selected. + var again = await RedactAsync(scope, Plan(tenant, DataRequestOrigin.Self, organization: null)); + again.Redacted.Values.Should().AllSatisfy(count => count.Should().Be(0)); + again.RowsSelected.Should().Be(0); + (await ReadAsync(scope, rows)).Should().Equal(after); + await scope.Transaction.RollbackAsync(); + } + + [Fact] + public async Task The_reach_follows_who_asked_another_tenant_is_never_touched_and_the_report_counts_what_survives() + { + var tenant = Guid.CreateVersion7(); + var foreign = Guid.CreateVersion7(); + var branch = Guid.CreateVersion7(); + var otherBranch = Guid.CreateVersion7(); + var rows = Reach(tenant, foreign, branch, otherBranch); + + // A person's own request reaches the whole tenant; an administrator's only the group's organization, or only the + // tenant level for the tenant-wide group, and reports what lies outside as unscoped (ADR-0108 § 4). + var cases = new (DataRequestOrigin Origin, Guid? Organization, string[] Selected, long Actor, long Entity, long Metadata, long? Unscoped)[] + { + (DataRequestOrigin.Self, branch, + ["actor/branch", "actor/other-branch", "actor/tenant", "actor+authorization/branch", "elided/branch", + "entity/branch", "entity/tenant", "payload/branch", "payload/other-branch", "payload/tenant"], 5, 2, 2, null), + (DataRequestOrigin.Administrator, branch, + ["actor/branch", "actor+authorization/branch", "elided/branch", "entity/branch", "payload/branch"], 3, 1, 2, 3), + (DataRequestOrigin.Administrator, null, + ["actor/tenant", "entity/tenant", "payload/tenant"], 1, 1, 0, 5), + }; + foreach (var (origin, organization, selected, actor, entity, metadata, unscoped) in cases) + { + await using var scope = await OpenAsync(schema.Postgres.PlatformConnectionString); + await InsertAsync(scope, rows); + var before = await ReadAsync(scope, rows); + + var report = await RedactAsync(scope, Plan(tenant, origin, organization)); + + var after = await ReadAsync(scope, rows); + var changed = rows.Where(row => after[row.Id] != before[row.Id]).Select(row => row.Label).ToList(); + changed.Should().BeEquivalentTo(selected, "{0} in {1}", origin, organization is null ? "the tenant-wide group" : "an organization group"); + rows.Where(row => row.Tenant == foreign).Should().OnlyContain(row => after[row.Id] == before[row.Id], + "another tenant's rows naming the same person are outside every reach"); + if (selected.Contains("elided/branch")) + { + after[rows.Single(row => row.Label == "elided/branch").Id].BeforeText.Should() + .Contain("_elided", "an elided state holds no value, so it has no path to redact"); + } + + report.RowsSelected.Should().Be(selected.Length); + var expected = new Dictionary + { + [RetainedReferenceKind.AuditActorReference] = actor, + [RetainedReferenceKind.AuditEntityReference] = entity, + [RetainedReferenceKind.AuditMetadataReference] = metadata, + }; + if (unscoped is { } outside) + { + expected[RetainedReferenceKind.UnscopedAuditRows] = outside; + } + + Retained(report).Should().Equal(expected, "{0} in {1}", origin, organization); + report.Redacted[AuditRedactedColumn.IpAddress].Should().Be(selected.Length, "every selected row carried an address"); + + // The re-run changes nothing and keeps the rows the actor or the entity selects. + var again = await RedactAsync(scope, Plan(tenant, origin, organization)); + again.Redacted.Values.Should().AllSatisfy(count => count.Should().Be(0)); + again.RowsSelected.Should().Be(selected.Count(label => !label.StartsWith("payload/", StringComparison.Ordinal))); + Retained(again).Should().Equal(expected); + (await ReadAsync(scope, rows)).Should().Equal(after); + await scope.Transaction.RollbackAsync(); + } + } + + [Fact] + public async Task A_refused_admission_or_plan_runs_no_statement() + { + var tenant = Guid.CreateVersion7(); + var rows = Reach(tenant, Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.CreateVersion7()); + await using var scope = await OpenAsync(schema.Postgres.PlatformConnectionString); + await InsertAsync(scope, rows); + var before = await ReadAsync(scope, rows); + var jit = await SettingAsync(scope, "jit"); + var executor = Executor(); + var plan = Plan(tenant, DataRequestOrigin.Self, organization: null); + + // Every other registered operation over the erasure's plan, every operation but the closure's Finalize over each + // of a closure's two passes (complete_erasure included), and an admission no scope spent. + const string Sanction = "*does not name an operation that may redact*"; + var closures = new[] { ("closure tenant pass", ClosureTenantPlan(tenant)), ("closure sentinel pass", ClosureSentinelPlan()) }; + var refusals = PlatformOperations.All.Where(operation => !ReferenceEquals(operation, PlatformOperations.ErasureComplete)) + .Select(operation => (Name: operation.AuditSlug, Plan: plan, Admission: Spent(operation), Message: Sanction)) + .Concat(closures.SelectMany(closure => PlatformOperations.All + .Where(operation => !ReferenceEquals(operation, PlatformOperations.ClosureFinalize)) + .Select(operation => (closure.Item1 + " under " + operation.AuditSlug, closure.Item2, Spent(operation), Sanction)))) + .Append(("unspent admission", plan, TestPlatformAdmissions.Admission(PlatformOperations.ErasureComplete), + "*platform scope its admission opened*")) + .ToList(); + refusals.Should().HaveCount((3 * (PlatformOperations.All.Count - 1)) + 1); + foreach (var (name, refusedPlan, admission, message) in refusals) + { + await FluentActions.Awaiting(() => executor.RedactAsync(refusedPlan, admission, scope.Connection, scope.Transaction)) + .Should().ThrowAsync(name).WithMessage(message); + } + + // Nothing ran: the first statement switches JIT off for the transaction, and the transaction is still usable. + (await SettingAsync(scope, "jit")).Should().Be(jit); + (await ReadAsync(scope, rows)).Should().Equal(before); + + // The sanctioned acts on the same transaction then run, and leave the setting as they found it. + (await RedactAsync(scope, plan)).RowsSelected.Should().BeGreaterThan(0); + (await SettingAsync(scope, "jit")).Should().Be(jit); + (await executor.RedactAsync(ClosureTenantPlan(tenant), Spent(PlatformOperations.ClosureFinalize), scope.Connection, + scope.Transaction)).RowsSelected.Should().BeGreaterThan(0, "the actor and entity rows stay selected after the erasure"); + (await SettingAsync(scope, "jit")).Should().Be(jit); + await scope.Transaction.RollbackAsync(); + } + + [Fact] + public async Task A_connection_of_another_role_is_refused_before_anything_is_read() + { + var tenant = Guid.CreateVersion7(); + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(schema.Postgres.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + + await FluentActions.Awaiting(() => Executor().RedactAsync(Plan(tenant, DataRequestOrigin.Self, null), + Spent(PlatformOperations.ErasureComplete), app, transaction)) + .Should().ThrowAsync() + .WithMessage("*platform role*", "learnstack_app sees only what its row policy shows and holds no UPDATE"); + await transaction.RollbackAsync(); + } + + [Fact] + public async Task The_platform_role_still_cannot_change_any_column_outside_the_grant() + { + var tenant = Guid.CreateVersion7(); + var rows = Reach(tenant, Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.CreateVersion7()); + await using var scope = await OpenAsync(schema.Postgres.PlatformConnectionString); + await InsertAsync(scope, rows); + await RedactAsync(scope, Plan(tenant, DataRequestOrigin.Self, null)); + var target = rows[0].Id; + + foreach (var statement in new[] + { + "UPDATE audit_log SET metadata = '{}'::jsonb WHERE id = @id", + "UPDATE audit_log SET actor_user_id = NULL WHERE id = @id", + "UPDATE audit_log SET entity_id = 'x', changes = NULL WHERE id = @id", + }) + { + var refusal = await DataExportTestKit.RefuseAsync(scope.Transaction, async () => + { + await using var command = new NpgsqlCommand(statement, scope.Connection, scope.Transaction); + command.Parameters.AddWithValue("id", target); + await command.ExecuteNonQueryAsync(); + }); + refusal.SqlState.Should().Be(PostgresErrorCodes.InsufficientPrivilege, statement); + } + + await scope.Transaction.RollbackAsync(); + } + + private static IReadOnlyList RegisteredLocators() + { + var services = new ServiceCollection(); + services.AddIdentityContextualFoundation(); + services.AddDataExportCustody(new ConfigurationBuilder().Build()); + using var provider = services.BuildServiceProvider(); + return [.. provider.GetServices()]; + } + + private static AuditRedactionExecutor Executor() => new(Registered.Value); + + private static string ModuleOf(IUserReferenceLocator locator) => ModuleOf(locator.GetType()); + + private static string ModuleOf(Type type) + { + var name = type.Assembly.GetName().Name!; + const string prefix = "LearnStack.Modules."; + return name.StartsWith(prefix, StringComparison.Ordinal) ? name[prefix.Length..name.IndexOf('.', prefix.Length)] : name; + } + + private static PlatformAdmission Spent(PlatformOperation operation) + { + var admission = TestPlatformAdmissions.Admission(operation); + admission.TryConsume().Should().BeTrue("the scope spends the admission on entry"); + return admission; + } + + private static AuditRedactionPlan Plan(Guid tenant, DataRequestOrigin origin, Guid? organization) => + new(new UserDataSubject(Guid.CreateVersion7(), DataRequestKind.Erasure, origin, UserId.From(Subject), + new DataRequestScopeGroup(TenantId.From(tenant), organization is { } org ? OrganizationId.From(org) : null), + [Membership1, Membership2])); + + /// A closure's pass over , with both Memberships the subject holds there. + private static AuditRedactionPlan ClosureTenantPlan(Guid tenant) => + AuditRedactionPlan.ForClosureTenant(TenantId.From(tenant), UserId.From(Subject), [Membership1, Membership2]); + + /// A closure's pass over the platform sentinel tenant, by a key no row of this class carries. + private static AuditRedactionPlan ClosureSentinelPlan() => + AuditRedactionPlan.ForClosureSentinel(UserId.From(Subject), + IdentitySubjectKey.FromBytes(System.Security.Cryptography.RandomNumberGenerator.GetBytes(32))); + + private static async Task RedactAsync(Scope scope, AuditRedactionPlan plan) => + await Executor().RedactAsync(plan, Spent(PlatformOperations.ErasureComplete), scope.Connection, scope.Transaction); + + private static Dictionary Retained(AuditRedactionReport report) => + report.Retained.ToDictionary(entry => entry.Kind, entry => entry.Count); + + private static async Task SettingAsync(Scope scope, string name) + { + await using var command = new NpgsqlCommand("SELECT current_setting(@name)", scope.Connection, scope.Transaction); + command.Parameters.AddWithValue("name", name); + return (string)(await command.ExecuteScalarAsync())!; + } + + /// + /// The three canaries of one declaration: the subject's identifier of the declaration's kind at the path, beside + /// another person's at the same path; only other people's; and the subject's identifier of the other kind. + /// + private static IEnumerable Canary(UserReferenceDeclaration declaration, Guid tenant) + { + var label = declaration.EntityName + "." + declaration.Path; + var own = Text(declaration.Kind == UserReferenceKind.User ? Subject : Membership1); + var other = Text(declaration.Kind == UserReferenceKind.User ? OtherPerson : OtherMembership); + var wrongKind = Text(declaration.Kind == UserReferenceKind.User ? Membership2 : Subject); + var sentinel = SensitiveTokenCatalog.RedactedValue; + + var entity = Guid.CreateVersion7().ToString("D"); + var (before, after, changes) = Payload(declaration, entity, own, own.ToUpperInvariant(), other, own); + var (expectedBefore, expectedAfter, expectedChanges) = Payload(declaration, entity, sentinel, sentinel, other, own); + yield return new CanaryRow(label + " (subject)", tenant, null, ThirdPerson, declaration.EntityName, entity, + before, after, changes, null, Selected: true, expectedBefore, expectedAfter, expectedChanges); + + var twin = Guid.CreateVersion7().ToString("D"); + var third = Text(declaration.Kind == UserReferenceKind.User ? ThirdPerson : Guid.CreateVersion7()); + (before, after, changes) = Payload(declaration, twin, third, third.ToUpperInvariant(), other, third); + yield return new CanaryRow(label + " (others only)", tenant, null, ThirdPerson, declaration.EntityName, twin, + before, after, changes, null, Selected: false, before, after, changes); + + var mismatch = Guid.CreateVersion7().ToString("D"); + (before, after, changes) = Payload(declaration, mismatch, wrongKind, wrongKind.ToUpperInvariant(), other, wrongKind); + yield return new CanaryRow(label + " (other kind)", tenant, null, ThirdPerson, declaration.EntityName, mismatch, + before, after, changes, null, Selected: false, before, after, changes); + } + + /// + /// The capture's shape for one declared path: own where the path points in each column, other at the + /// same path in the other slot, and remark under a property no locator declares, which nothing may redact. + /// + private static (JsonNode Before, JsonNode After, JsonNode Changes) Payload(UserReferenceDeclaration declaration, + string entity, string own, string ownUpper, string other, string remark) + { + var path = declaration.Path; + var type = declaration.EntityName; + switch (path.Shape) + { + case UserReferenceShape.Property: + return (State(entity, (path.Property, own), ("Remark", remark)), State(entity, (path.Property, own), ("Remark", remark)), + new JsonArray(Item(type, entity, path.Property, other, own), Item(type, entity, "Remark", remark, remark))); + case UserReferenceShape.Member: + JsonObject Members() => new() + { + ["k1"] = new JsonObject { [path.Property] = own, ["Remark"] = remark }, + ["b/2"] = new JsonObject { [path.Property] = other }, + }; + return (State(entity, (path.Navigation!, Members())), State(entity, (path.Navigation!, Members())), + new JsonArray(Item(type, entity, path.Navigation + "/k1/" + path.Property, other, own), + Item(type, entity, path.Navigation + "/b~12/" + path.Property, other, other), + Item(type, entity, path.Navigation + "/k1/Remark", remark, remark))); + case UserReferenceShape.Elements: + return (State(entity, (path.Property, new JsonArray(own, other, ownUpper))), + State(entity, (path.Property, new JsonArray(other, own))), + new JsonArray(Item(type, entity, path.Property, new JsonArray(other), new JsonArray(own, other)))); + default: + throw new NotSupportedException("A path shape the canary cannot build is a path no canary proves: " + path); + } + } + + private static JsonObject State(string entity, params (string Name, JsonNode? Value)[] members) + { + var state = new JsonObject { ["Id"] = entity, ["Title"] = "canary" }; + foreach (var (name, value) in members) + { + state[name] = value; + } + + return state; + } + + private static JsonObject Item(string type, string entity, string rest, JsonNode? before, JsonNode? after) => + new() { ["path"] = "/" + type + "/" + entity + "/" + rest, ["before"] = before, ["after"] = after }; + + private static string Text(Guid value) => value.ToString("D"); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AuthorizationPoolProgressTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/AuthorizationPoolProgressTests.cs index f22768c02..3e68d91b7 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/AuthorizationPoolProgressTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/AuthorizationPoolProgressTests.cs @@ -282,6 +282,10 @@ private sealed class LifecycleObserver(string directConnection, HeldBusinessOwne public Task ReadAsync(TenantId tenantId, OrganizationId? organizationId, CancellationToken cancellationToken = default) => _actual.ReadAsync(tenantId, organizationId, cancellationToken); + public Task> ReadOnPlatformScopeAsync( + LearnStack.SharedKernel.Tenancy.IPlatformAdminScopeHandle handle, IReadOnlyList scopes, + CancellationToken cancellationToken = default) => _actual.ReadOnPlatformScopeAsync(handle, scopes, cancellationToken); + public async Task ReadAuthorizationAsync(IUnitOfWork child, AuthorizationCandidate candidate, CancellationToken cancellationToken = default) { diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobStorageMigrationTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobStorageMigrationTests.cs index 34c79a078..7a17c165f 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobStorageMigrationTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobStorageMigrationTests.cs @@ -67,7 +67,7 @@ public async Task Fresh_down_reapply_restores_every_job_object_and_retains_exist (await SchemaQueries.ReadStringsAsync(owner, SchemaQueries.TableNames)).Should() .BeEquivalentTo(SchemaTableClasses.Existing.Concat(SchemaTableClasses.GlobalIdentity) .Concat(SchemaTableClasses.IdentityPlatform).Concat(SchemaTableClasses.IdentityContextual) - .Concat(SchemaTableClasses.ProviderIngress), + .Concat(SchemaTableClasses.ProviderIngress).Concat(SchemaTableClasses.IdentityDataRequest), "all event-era and independently added Identity data tables survive this Platform-only reversal"); } diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BoundedAdministrationHttpTests.InvitationEntryWaitRaces.cs b/backend/tests/LearnStack.Tests.Integration/Database/BoundedAdministrationHttpTests.InvitationEntryWaitRaces.cs index 2f374ca39..bae59a236 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BoundedAdministrationHttpTests.InvitationEntryWaitRaces.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BoundedAdministrationHttpTests.InvitationEntryWaitRaces.cs @@ -132,9 +132,9 @@ public async Task Actual_invitation_entry_defensively_rechecks_global_users_afte "SELECT pg_get_expr(polwithcheck,polrelid) FROM pg_policy WHERE polrelid='public.users'::regclass AND polname='users_isolation'"); Assert.True(await ScalarAsync(owner, null, "SELECT tgenabled='O' FROM pg_trigger WHERE tgrelid='public.users'::regclass AND tgname='tg_users_no_update'")); - // The production schema has no User closure writer. Reuse ADR-0074's - // isolated owner-only corruption setup to prove the actual defensive - // reread, without claiming a production closure or P03-10 capability. + // The production User closure writer is the platform session under the + // closure's fences (ADR-0107 § 7). Reuse ADR-0074's isolated owner-only + // corruption setup to prove the actual defensive reread without them. try { await ExecuteAsync(owner, null, $""" diff --git a/backend/tests/LearnStack.Tests.Integration/Database/ClosureAuditRedactionTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/ClosureAuditRedactionTests.cs new file mode 100644 index 000000000..9bc345eb9 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/ClosureAuditRedactionTests.cs @@ -0,0 +1,528 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using FluentAssertions; +using LearnStack.Api.Composition; +using LearnStack.Infrastructure.Audit; +using LearnStack.Infrastructure.MultiTenancy; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.Modules.Tenancy.Application.Audit; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Secrets; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using LearnStack.Tests.Fixtures; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; +using NpgsqlTypes; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// A closure Finalize's audit redaction against PostgreSQL (ADR-0107 § 7, ADR-0108 §§ 4, 8). The pass over the platform +/// sentinel tenant selects exactly the person's global creation rows, the failed and undetermined attempts that only the +/// subject key finds, and the rows naming the person as actor or User, and nothing else of that tenant or of any other; +/// it is idempotent and batches as the tenant pass does. The real platform scope, entered for the closure's Finalize, +/// runs every pass on its first transaction, which commits with the intent row carrying their summed counts, and refuses +/// an erasure's plan, as the erasure's completion refuses a closure's passes. +/// +/// +/// Each case has a database of its own: the global creation rows are written as learnstack_app under the creation +/// guard and committed, the platform role's planted rows beside them, and the shared schema's censuses count rows. Every +/// redaction under test runs as learnstack_platform. +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed class ClosureAuditRedactionTests(SchemaFixture schema) +{ + private static readonly string SystemActorText = UserId.SystemActor.Value.ToString("D"); + + /// The sentinel rows the pass selects, of the world writes. + private static readonly string[] SentinelSelected = ["creation", "failed attempt", "undetermined attempt", "actor", "user entity"]; + + [Fact] + public async Task The_sentinel_pass_selects_exactly_the_person_s_global_rows_redacts_them_and_reports_what_survives() + { + await using var world = await SeedAsync(); + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(world.Database.PlatformConnectionString); + await using var transaction = await connection.BeginTransactionAsync(); + var before = await ReadAsync(connection, transaction, world); + + var report = await Executor().RedactAsync(world.SentinelPass, Spent(PlatformOperations.ClosureFinalize), connection, transaction); + + var after = await ReadAsync(connection, transaction, world); + Changed(world, before, after).Should().BeEquivalentTo(["undetermined attempt", "actor"], + "a selected row changes where a granted column holds something of the person's, and no other row changes"); + world.Rows.Keys.Should().OnlyContain(label => after[label].Retained == before[label].Retained, + "the key, the actor, the entity and every column outside the grant survive (ADR-0108 § 6)"); + (after["actor"].IpAddress, after["actor"].UserAgent, after["actor"].ActorEmail).Should().Be((null, null, null)); + var attempt = JsonNode.Parse(after["undetermined attempt"].After!)!; + attempt["UpdatedBy"]!.GetValue().Should().Be(SensitiveTokenCatalog.RedactedValue, "a declared path naming the person"); + attempt["CreatedBy"]!.GetValue().Should().Be(SystemActorText, "the system attribution is no one's"); + after["failed attempt"].Should().Be(before["failed attempt"], "a creation row holds nothing of the person's in a granted column"); + + report.RowsSelected.Should().Be(SentinelSelected.Length); + Columns(report).Should().Equal(1, 1, 1, 0, 1, 0); + Kinds(report).Should().Equal(new Dictionary + { + [RetainedReferenceKind.AuditActorReference] = 1, + [RetainedReferenceKind.AuditEntityReference] = 2, + [RetainedReferenceKind.AuditMetadataReference] = 3, + }, "the actor row, the creation and the User entity row, and the three rows carrying the subject key"); + + // Idempotent: the re-run selects the same rows, by key, actor and entity, and rewrites none of them. + var again = await Executor().RedactAsync(world.SentinelPass, Spent(PlatformOperations.ClosureFinalize), connection, transaction); + again.RowsSelected.Should().Be(SentinelSelected.Length); + again.Redacted.Values.Should().AllSatisfy(count => count.Should().Be(0)); + Kinds(again).Should().Equal(Kinds(report)); + (await ReadAsync(connection, transaction, world)).Should().Equal(after); + await transaction.RollbackAsync(); + } + + [Fact] + public async Task Small_batches_draw_several_batches_over_the_sentinel_and_select_and_redact_exactly_what_one_batch_does() + { + await using var world = await SeedAsync(); + var single = await BatchRunAsync(world, Executor()); + var tiny = await BatchRunAsync(world, new AuditRedactionExecutor(Locators(), batchRows: 2, batchBytes: 300, updateRows: 1)); + + single.Boundaries.Should().Be(1, "the production sizes read the sentinel tenant in one batch"); + tiny.Boundaries.Should().BeGreaterThan(3, "two rows a batch over the sentinel tenant's rows draws several"); + tiny.After.Should().Equal(single.After); + tiny.Report.RowsSelected.Should().Be(single.Report.RowsSelected).And.Be(SentinelSelected.Length); + tiny.Report.Redacted.Should().Equal(single.Report.Redacted); + Kinds(tiny.Report).Should().Equal(Kinds(single.Report)); + } + + /// + /// The sentinel selection walks no payload, so the sentinel pass's batch boundary sizes none: with a byte budget every + /// payload exceeds and a row cap above the tenant's rows, it reads the whole sentinel tenant in one batch, where a pass + /// that sized payloads would end a batch at each sentinel row that carries one. + /// + [Fact] + public async Task The_sentinel_pass_sizes_no_payload_so_only_the_row_cap_ends_its_batches() + { + await using var world = await SeedAsync(); + await using (var platform = (NpgsqlConnection)await PostgresFixture.OpenAsync(world.Database.PlatformConnectionString)) + { + (await IdentityMembershipFixture.ScalarAsync(platform, null, """ + SELECT count(*) FROM public.audit_log + WHERE tenant_id = @sentinel AND (before_state IS NOT NULL OR after_state IS NOT NULL OR changes IS NOT NULL) + """, ("sentinel", TenantId.PlatformSentinel.Value))) + .Should().BeGreaterThan(1, "the premise: several sentinel rows carry a payload a byte budget of one would cut at"); + } + + var run = await BatchRunAsync(world, new AuditRedactionExecutor(Locators(), batchRows: 1_000, batchBytes: 1, updateRows: 1)); + + run.Boundaries.Should().Be(1, "the row cap alone ends a sentinel batch, and no payload is decompressed to be sized"); + run.Report.RowsSelected.Should().Be(SentinelSelected.Length); + } + + [Fact] + public async Task Through_the_real_scope_Finalize_redacts_every_participant_and_the_sentinel_and_commits_it_with_its_intent_row() + { + await using var world = await SeedAsync(); + await using var platform = PersistenceCompositionExtensions.BuildPlatformDataSource(world.Database.PlatformConnectionString); + var scope = Scope(platform); + var request = Guid.CreateVersion7(); + var original = await SnapshotAsync(world); + + // An act abandoned before its checkpoint redacts nothing: the passes ran on the first transaction, which the + // disposal rolls back, so no state exists where the redaction is done and its evidence is not (ADR-0108 § 8). + var abandoned = Admission("CHG-311"); + await using (var handle = await scope.EnterAsync(abandoned)) + { + await handle.RedactAuditAsync(world.TenantPass(world.ParticipantA)); + await handle.RedactAuditAsync(world.SentinelPass); + } + + (await SnapshotAsync(world)).Should().Equal(original, "the abandoned act's redaction rolled back"); + (await RowsAsync(world, abandoned.Operator.CorrelationId!)).Select(row => row.Operation) + .Should().Equal(PlatformAdminScope.EnterOperation); + + // The act: every pass on the first transaction, the intent row carrying their sum at the checkpoint, then the + // result row on the second. + var admission = Admission("CHG-312"); + AuditRedactionAggregate aggregate; + await using (var handle = await scope.EnterAsync(admission)) + { + var first = await handle.RedactAuditAsync(world.TenantPass(world.ParticipantA)); + var second = await handle.RedactAuditAsync(world.TenantPass(world.ParticipantB)); + var sentinel = await handle.RedactAuditAsync(world.SentinelPass); + var erasure = async () => await handle.RedactAuditAsync(new AuditRedactionPlan(new UserDataSubject(request, + DataRequestKind.Erasure, DataRequestOrigin.ClosureFanout, UserId.From(world.Person), + new DataRequestScopeGroup(TenantId.From(world.ParticipantA), null), [world.MembershipA]))); + await erasure.Should().ThrowAsync().WithMessage("*may not redact*", + "the closure's Finalize redacts its own passes, never an erasure's plan"); + (await handle.QueryAsync("SELECT 1", null, reader => reader.GetInt32(0))).Should().Equal([1], + "a refusal before anything ran leaves the act usable"); + + aggregate = new AuditRedactionAggregate( + new Dictionary + { + [TenantId.From(world.ParticipantA)] = first, + [TenantId.From(world.ParticipantB)] = second, + }, + sentinel); + await handle.WriteIntentAsync(new PlatformResult( + TenantId.PlatformSentinel, "DataSubjectRequest", request.ToString("D"), null, aggregate.ToClosedJson())); + + // The checkpoint committed the redaction with its evidence, before any effect the act goes on to make. + var committed = await SnapshotAsync(world); + ChangedLabels(original, committed).Should().BeEquivalentTo( + ["undetermined attempt", "actor", "a actor", "a membership", "b payload", "b membership"]); + var intent = (await RowsAsync(world, admission.Operator.CorrelationId!)).Should().HaveCount(2).And.Subject.Last(); + (intent.Tenant, intent.Operation, intent.Outcome, intent.Reason, intent.Actor).Should().Be( + (TenantId.PlatformSentinel.Value, "platform.closure.finalize_attempt", "indeterminate", "closure_finalize", (Guid?)null)); + JsonNode.DeepEquals(JsonNode.Parse(intent.After!), JsonNode.Parse(aggregate.ToClosedJson())).Should().BeTrue(intent.After); + intent.Metadata.Should().Contain("CHG-312", "a sentinel row carries the operator's ticket"); + + await handle.WriteResultAsync(new PlatformResult( + TenantId.PlatformSentinel, "DataSubjectRequest", request.ToString("D"), null, """{"status":"completed"}""")); + await handle.CommitAsync(); + } + + var rows = await RowsAsync(world, admission.Operator.CorrelationId!); + rows.Select(row => (row.Operation, row.Outcome)).Should().Equal( + (PlatformAdminScope.EnterOperation, "success"), ("platform.closure.finalize_attempt", "indeterminate"), + ("platform.closure.finalize", "success")); + rows.Should().OnlyContain(row => row.Tenant == TenantId.PlatformSentinel.Value && row.Actor == null); + + // The document is counts and tenant identifiers, never the person. + var document = aggregate.ToClosedJson(); + document.Should().Contain(world.ParticipantA.ToString("D")).And.Contain(world.ParticipantB.ToString("D")) + .And.NotContain(world.Person.ToString("D")).And.NotContain(world.Key.Hex); + aggregate.Total.RowsSelected.Should().Be(9, "two rows in each participant and five in the sentinel"); + Columns(aggregate.Total).Should().Equal(5, 5, 5, 0, 2, 0); + Kinds(aggregate.Total).Should().Equal(new Dictionary + { + [RetainedReferenceKind.AuditActorReference] = 2, + [RetainedReferenceKind.AuditEntityReference] = 4, + [RetainedReferenceKind.AuditMetadataReference] = 3, + }); + + // A repeat redacts nothing more, and the erasure's completion is refused a closure's pass, leaving its act usable. + await using (var repeat = await scope.EnterAsync(Admission(null))) + { + foreach (var pass in new[] { world.TenantPass(world.ParticipantA), world.TenantPass(world.ParticipantB), world.SentinelPass }) + { + (await repeat.RedactAuditAsync(pass)).Redacted.Values.Should().AllSatisfy(count => count.Should().Be(0)); + } + } + + await using (var completion = await scope.EnterAsync(TestPlatformAdmissions.Admission(PlatformOperations.ErasureComplete))) + { + foreach (var pass in new[] { world.TenantPass(world.ParticipantA), world.SentinelPass }) + { + var redact = async () => await completion.RedactAuditAsync(pass); + await redact.Should().ThrowAsync().WithMessage("*may not redact*"); + } + + (await completion.QueryAsync("SELECT 1", null, reader => reader.GetInt32(0))).Should().Equal([1]); + } + + ChangedLabels(original, await SnapshotAsync(world)).Should().BeEquivalentTo( + ["undetermined attempt", "actor", "a actor", "a membership", "b payload", "b membership"], + "the outsider tenant, the other person and the operator rows were never touched"); + } + + /// + /// The world: the person and another, each with a real global creation row written under the creation guard; the + /// person's failed attempt (a captured User the person never became) and undetermined attempt (whose state names the + /// person at a declared path, which no creation writes today), and the other's failed attempt, each found by its key + /// alone; platform-role rows of the sentinel tenant naming the person as actor, as User entity, as a Membership entity + /// (not a User), and an operator's and the other person's rows; and two participant tenants and an outsider, whose + /// rows name the person as actor, as Membership entity or in a payload. + /// + private async Task SeedAsync() + { + var database = await DisposableSchemaDatabase.CreateAsync(schema.Postgres); + await using (var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString)) + { + await IdentityAuthorityDeploymentInstaller.InstallAsync(owner, IdentityMembershipFixture.Authority); + } + + var (person, other) = (Guid.CreateVersion7(), Guid.CreateVersion7()); + await IdentityMembershipFixture.InsertUserAsync(database.AppConnectionString, person); + await IdentityMembershipFixture.InsertUserAsync(database.AppConnectionString, other); + var world = new World(database, person, Subject(person).SubjectKey, Guid.CreateVersion7(), Guid.CreateVersion7(), + Guid.CreateVersion7(), Guid.CreateVersion7()); + var sentinel = TenantId.PlatformSentinel.Value; + string Text(Guid value) => value.ToString("D"); + string Course(Guid? creator, Guid? updater) => + new JsonObject { ["Id"] = Text(Guid.CreateVersion7()), ["CreatedBy"] = Text(creator ?? other), ["UpdatedBy"] = Text(updater ?? other) } + .ToJsonString(); + string Captured(string updater) => + new JsonObject { ["Id"] = Text(Guid.CreateVersion7()), ["Status"] = "Active", ["CreatedBy"] = SystemActorText, ["UpdatedBy"] = updater } + .ToJsonString(); + + world.Rows["creation"] = await CreationAsync(database, person); + world.Rows["other creation"] = await CreationAsync(database, other); + world.Rows["failed attempt"] = await AttemptAsync(database, person, "failed", Captured(SystemActorText)); + world.Rows["undetermined attempt"] = await AttemptAsync(database, person, "indeterminate", Captured(Text(person))); + world.Rows["other failed attempt"] = await AttemptAsync(database, other, "failed", Captured(Text(other))); + world.Rows["actor"] = await PlantAsync(database, sentinel, person, "Course", Text(Guid.CreateVersion7()), null); + world.Rows["user entity"] = await PlantAsync(database, sentinel, null, "User", Text(person), null, attributed: false); + world.Rows["membership entity"] = await PlantAsync(database, sentinel, other, "Membership", Text(person), null); + world.Rows["operator"] = await PlantAsync(database, sentinel, null, "DataSubjectRequest", Text(Guid.CreateVersion7()), null); + world.Rows["other actor"] = await PlantAsync(database, sentinel, other, "Course", Text(Guid.CreateVersion7()), null); + world.Rows["a actor"] = await PlantAsync(database, world.ParticipantA, person, "Course", Text(Guid.CreateVersion7()), null); + world.Rows["a membership"] = await PlantAsync(database, world.ParticipantA, other, "Membership", Text(world.MembershipA), null); + world.Rows["a other"] = await PlantAsync(database, world.ParticipantA, other, "Course", Text(Guid.CreateVersion7()), Course(null, null)); + world.Rows["b payload"] = await PlantAsync(database, world.ParticipantB, other, "Course", Text(Guid.CreateVersion7()), Course(null, person)); + world.Rows["b membership"] = await PlantAsync(database, world.ParticipantB, other, "Membership", Text(world.MembershipB), null); + world.Rows["outsider actor"] = await PlantAsync(database, Guid.CreateVersion7(), person, "Course", Text(Guid.CreateVersion7()), Course(person, person)); + return world; + } + + private static GlobalIdentitySubject Subject(Guid user) => new(IdentityMembershipFixture.Authority.AuthorityId, + IdentityMembershipFixture.Authority.Issuer, "fixture-subject-" + user.ToString("N")); + + /// The identifier of a user's global creation row, which the fixture wrote under the creation guard. + private static async Task CreationAsync(DisposableSchemaDatabase database, Guid user) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.PlatformConnectionString); + await using var command = new NpgsqlCommand( + "SELECT id FROM public.audit_log WHERE operation = 'identity.user.create' AND outcome = 'success' AND entity_id = @user", + connection); + command.Parameters.AddWithValue("user", user.ToString("D")); + return (Guid)(await command.ExecuteScalarAsync())!; + } + + /// + /// A creation attempt that never became a User, as the application role writes it under the person's identity + /// announcement and the creation guard: its entity is a fresh identifier, so only the subject key finds it. + /// + private static async Task AttemptAsync(DisposableSchemaDatabase database, Guid user, string outcome, string after) + { + var subject = Subject(user); + var id = Guid.CreateVersion7(); + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await GlobalIdentitySchemaTests.AnnounceAsync(app, transaction, subject); + await using (var command = new NpgsqlCommand(""" + 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, after_state, metadata) + VALUES(@id, clock_timestamp(), @sentinel, NULL, NULL, 'identity', 'identity.user.create', 'SecurityEvent', 'Must', 'User', + @target, @outcome, @after::jsonb, @metadata::jsonb) + """, app, transaction)) + { + command.Parameters.AddWithValue("id", id); + command.Parameters.AddWithValue("sentinel", TenantId.PlatformSentinel.Value); + command.Parameters.AddWithValue("target", Guid.CreateVersion7().ToString("D")); + command.Parameters.AddWithValue("outcome", outcome); + command.Parameters.AddWithValue("after", after); + command.Parameters.AddWithValue("metadata", JsonSerializer.Serialize(new + { + identity_authority_id = subject.AuthorityId.Value.ToString("D"), + identity_subject_key = subject.SubjectKey.Hex, + identity_source = "identity-bootstrap", + })); + await command.ExecuteNonQueryAsync(); + } + + await transaction.CommitAsync(); + return id; + } + + /// A row the platform role writes, with an address, an agent and an e-mail unless it is unattributed. + private static async Task PlantAsync(DisposableSchemaDatabase database, Guid tenant, Guid? actor, string entityType, + string entityId, string? after, bool attributed = true) + { + var id = Guid.CreateVersion7(); + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.PlatformConnectionString); + await using var command = new NpgsqlCommand(""" + INSERT INTO public.audit_log (id, "timestamp", tenant_id, organization_id, actor_user_id, actor_email, module, operation, + operation_type, operation_class, entity_type, entity_id, outcome, after_state, correlation_id, ip_address, user_agent) + VALUES (@id, clock_timestamp(), @tenant, NULL, @actor, @email, 'canary', 'canary.closure.row', 'Update', 'Must', + @entity_type, @entity_id, 'success', @after, @correlation, @address, @agent) + """, connection); + command.Parameters.AddWithValue("id", id); + command.Parameters.AddWithValue("tenant", tenant); + command.Parameters.AddWithValue("actor", NpgsqlDbType.Uuid, (object?)actor ?? DBNull.Value); + command.Parameters.AddWithValue("email", NpgsqlDbType.Varchar, attributed ? "actor@example.test" : DBNull.Value); + command.Parameters.AddWithValue("entity_type", entityType); + command.Parameters.AddWithValue("entity_id", entityId); + command.Parameters.AddWithValue("after", NpgsqlDbType.Jsonb, (object?)after ?? DBNull.Value); + command.Parameters.AddWithValue("correlation", "00-" + id.ToString("N") + "-01"); + command.Parameters.AddWithValue("address", NpgsqlDbType.Inet, attributed ? System.Net.IPAddress.Parse("198.51.100.7") : DBNull.Value); + command.Parameters.AddWithValue("agent", NpgsqlDbType.Varchar, attributed ? "Canary/1.0" : DBNull.Value); + await command.ExecuteNonQueryAsync(); + return id; + } + + /// Every labelled row's six granted columns, and every other column as one canonical document. + private static async Task> ReadAsync(NpgsqlConnection connection, NpgsqlTransaction? transaction, World world) + { + await using var command = new NpgsqlCommand(""" + SELECT a.id, host(a.ip_address), a.user_agent, a.actor_email, a.before_state::text, a.after_state::text, a.changes::text, + (to_jsonb(a) - 'ip_address' - 'user_agent' - 'actor_email' - 'before_state' - 'after_state' - 'changes')::text + FROM public.audit_log AS a WHERE a.id = ANY(@ids) + """, connection, transaction); + command.Parameters.AddWithValue("ids", world.Rows.Values.ToArray()); + var labels = world.Rows.ToDictionary(entry => entry.Value, entry => entry.Key); + var read = new Dictionary(); + await using var reader = await command.ExecuteReaderAsync(); + while (await reader.ReadAsync()) + { + read[labels[reader.GetGuid(0)]] = new Snapshot(Text(reader, 1), Text(reader, 2), Text(reader, 3), Text(reader, 4), Text(reader, 5), + Text(reader, 6), reader.GetString(7)); + } + + read.Keys.Should().BeEquivalentTo(world.Rows.Keys, "every labelled row is read back"); + return read; + } + + private static async Task> SnapshotAsync(World world) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(world.Database.PlatformConnectionString); + return await ReadAsync(connection, null, world); + } + + private static List Changed(World world, Dictionary before, Dictionary after) => + [.. world.Rows.Keys.Where(label => after[label] != before[label])]; + + private static List ChangedLabels(Dictionary before, Dictionary after) => + [.. before.Keys.Where(label => after[label] != before[label])]; + + private static string? Text(NpgsqlDataReader reader, int ordinal) => reader.IsDBNull(ordinal) ? null : reader.GetString(ordinal); + + /// The operator rows one act wrote, in the order it wrote them. + private static async Task> RowsAsync(World world, string correlation) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(world.Database.PlatformConnectionString); + await using var command = new NpgsqlCommand(""" + SELECT tenant_id, operation, outcome, reason, actor_user_id, after_state::text, metadata::text + FROM public.audit_log WHERE correlation_id = @c ORDER BY "timestamp", id + """, connection); + command.Parameters.AddWithValue("c", correlation); + var rows = new List(); + await using var reader = await command.ExecuteReaderAsync(); + while (await reader.ReadAsync()) + { + rows.Add(new OperatorRow(reader.GetGuid(0), reader.GetString(1), reader.GetString(2), Text(reader, 3), + reader.IsDBNull(4) ? null : reader.GetGuid(4), Text(reader, 5), reader.GetString(6))); + } + + return rows; + } + + private static async Task BatchRunAsync(World world, AuditRedactionExecutor executor) + { + using var deadline = new CancellationTokenSource(TimeSpan.FromMinutes(2)); + using var statements = new StatementLog(); + await using var source = new NpgsqlDataSourceBuilder(world.Database.PlatformConnectionString) + .UseLoggerFactory(LoggerFactory.Create(builder => builder.SetMinimumLevel(LogLevel.Debug).AddProvider(statements))) + .Build(); + await using var connection = await source.OpenConnectionAsync(); + await using var transaction = await connection.BeginTransactionAsync(); + statements.Clear(); + var report = await executor.RedactAsync(world.SentinelPass, Spent(PlatformOperations.ClosureFinalize), connection, transaction, + deadline.Token); + var boundaries = statements.Completed("count(*) OVER batch"); + var after = await ReadAsync(connection, transaction, world); + await transaction.RollbackAsync(); + return new BatchRun(report, after, boundaries); + } + + private static PlatformAdminScope Scope(NpgsqlDataSource platform) => new( + new PrivilegedDataSource(() => platform), new AuditCatalog([new TenancyAuditCatalogSource()]), AuditServices(Executor()), + new SystemClock(), new SystemGuidFactory(), NullLogger.Instance); + + /// The audit store and the real executor, as the scope resolves them per call. + private static IServiceScopeFactory AuditServices(IAuditRedactor redactor) => + new ServiceCollection() + .AddSingleton(redactor) + .AddMetrics() + .AddLogging() + .AddScoped() + .AddSingleton() + .AddSingleton(new AuditCatalog([new TenancyAuditCatalogSource()])) + .AddSingleton(StaticTenantContextAccessor.Unresolved) + .AddScoped() + .AddSingleton(new Lazy( + () => throw new InvalidOperationException("The scope's rows are written on its own connection."))) + .AddScoped() + .BuildServiceProvider() + .GetRequiredService(); + + private static PlatformAdmission Admission(string? ticket) => TestPlatformAdmissions.Admission( + PlatformOperations.ClosureFinalize, ticket, correlationId: "00-closure-" + Guid.NewGuid().ToString("N")); + + private static AuditRedactionExecutor Executor() => new(Locators()); + + private static IReadOnlyList Locators() + { + var services = new ServiceCollection(); + services.AddIdentityContextualFoundation(); + services.AddDataExportCustody(new ConfigurationBuilder().Build()); + using var provider = services.BuildServiceProvider(); + return [.. provider.GetServices()]; + } + + private static PlatformAdmission Spent(PlatformOperation operation) + { + var admission = TestPlatformAdmissions.Admission(operation); + admission.TryConsume().Should().BeTrue("the scope spends the admission on entry"); + return admission; + } + + private static long[] Columns(AuditRedactionReport report) => + [.. Enum.GetValues().Select(column => report.Redacted[column])]; + + private static Dictionary Kinds(AuditRedactionReport report) => + report.Retained.ToDictionary(entry => entry.Kind, entry => entry.Count); + + /// One disposable database and what was written into it, by label. + private sealed record World(DisposableSchemaDatabase Database, Guid Person, IdentitySubjectKey Key, Guid ParticipantA, + Guid ParticipantB, Guid MembershipA, Guid MembershipB) : IAsyncDisposable + { + public Dictionary Rows { get; } = []; + + public AuditRedactionPlan SentinelPass => AuditRedactionPlan.ForClosureSentinel(UserId.From(Person), Key); + + public AuditRedactionPlan TenantPass(Guid tenant) => AuditRedactionPlan.ForClosureTenant(TenantId.From(tenant), UserId.From(Person), + [tenant == ParticipantA ? MembershipA : MembershipB]); + + public ValueTask DisposeAsync() => Database.DisposeAsync(); + } + + private sealed record Snapshot(string? IpAddress, string? UserAgent, string? ActorEmail, string? Before, string? After, string? Changes, + string Retained); + + private sealed record OperatorRow(Guid Tenant, string Operation, string Outcome, string? Reason, Guid? Actor, string? After, string Metadata); + + private sealed record BatchRun(AuditRedactionReport Report, Dictionary After, int Boundaries); + + /// The commands one data source's connections completed, as the driver logs them. + private sealed class StatementLog : ILoggerProvider, ILogger + { + private readonly System.Collections.Concurrent.ConcurrentQueue _commands = new(); + + public ILogger CreateLogger(string categoryName) => this; + + public void Clear() => _commands.Clear(); + + public int Completed(string marker) => _commands.Count(command => + command.StartsWith("Command execution completed", StringComparison.Ordinal) && command.Contains(marker, StringComparison.Ordinal)); + + public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Debug; + + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) => + _commands.Enqueue(formatter(state, exception)); + + public void Dispose() + { + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/ClosureFanOutTests.Coverage.cs b/backend/tests/LearnStack.Tests.Integration/Database/ClosureFanOutTests.Coverage.cs new file mode 100644 index 000000000..f7bdd3a52 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/ClosureFanOutTests.Coverage.cs @@ -0,0 +1,168 @@ +using FluentAssertions; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Platform; +using Xunit; +using static LearnStack.Tests.Integration.Database.DataRequestSchemaSeed; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The fan-out's branches the first suite left unreached, and the disposal of each case's database: a person's or an +/// administrator's own erasure that already awaits its privileged step, a completed erasure the group still holds, an +/// organization that stopped allowing ordinary work, and an organization's group fanned out without its tenant-wide group. +/// +public sealed partial class ClosureFanOutTests : IAsyncLifetime +{ + public Task InitializeAsync() => Task.CompletedTask; + + /// Each case owns a disposable copy of the seeded schema; it is dropped when the case ends. + public async Task DisposeAsync() + { + if (_database is { } database) + { + _database = null; + await database.DisposeAsync(); + } + } + + /// + /// An erasure the person or an administrator filed and whose own job already ended at the privileged step is adopted + /// as it is, whatever its origin: the group answers adopted, files nothing, enqueues no job and records the request it + /// adopted. + /// + [Theory] + [InlineData("self")] + [InlineData("administrator")] + public async Task An_erasure_the_person_or_an_administrator_filed_that_awaits_its_privileged_step_is_adopted_as_it_is(string origin) + { + await ArrangeAsync(); + var own = await AwaitingErasureAsync(TenantWideA, LearnerMembershipA, origin); + await CloseAsync(PersonA); + await using var host = Host(new Grants(true)); + + var reports = await FanOutAsync(host, [TenantWideA]); + + reports.Should().Equal([new ClosureGroupReport(TenantWideA, ClosureGroupOutcome.Adopted)]); + var held = (await RequestsAsync(TenantWideA)).Should().ContainSingle("nothing is filed beside the erasure the group holds").Subject; + (held.Id, held.Origin, held.Status).Should().Be((own, origin, "awaiting_privileged_step")); + (await JobsAsync(TenantWideA, own)).Should().Be(0, "an erasure awaiting its privileged step needs no job"); + (await AuditRowsAsync(TenantWideA)).Should().ContainSingle().Which.Should() + .Be(new AuditRow(own.ToString("D"), "success", "closure_fan_out", true, false, null), "the row names the request the group adopted"); + } + + /// + /// An erasure the group already completed (a person admitted again since) does not stand in for the closure's: the + /// group starts a new fan-out erasure beside it. + /// + [Fact] + public async Task A_completed_erasure_the_group_holds_is_replaced_by_a_new_fan_out() + { + await ArrangeAsync(); + var completed = Guid.CreateVersion7(); + await fixture.Postgres.ExecuteAsSuperuserAsync($""" + SET session_replication_role = replica; + INSERT INTO public.data_subject_requests(id,tenant_id,organization_id,kind,origin,subject_user_id,requester_user_id,status, + membership_snapshot,execute_at,completed_at,created_at,created_by,updated_at,updated_by,row_version) + VALUES('{completed}','{SchemaFixture.TenantA}',NULL,'erasure','self','{PersonA}','{PersonA}','completed', + '["{LearnerMembershipA}"]'::jsonb,now() - interval '1 day',now() - interval '1 day',now() - interval '2 days','{PersonA}', + now() - interval '1 day','{SystemActor}',2) + """, RebindProofSupport.DatabaseOf(_database!.MigrationConnectionString)); + await CloseAsync(PersonA); + await using var host = Host(new Grants(true)); + + var reports = await FanOutAsync(host, [TenantWideA]); + + reports.Should().Equal([new ClosureGroupReport(TenantWideA, ClosureGroupOutcome.Started)]); + var requests = await RequestsAsync(TenantWideA); + requests.Should().HaveCount(2); + requests.Single(row => row.Id == completed).Status.Should().Be("completed", "the earlier erasure is left as it ended"); + requests.Should().ContainSingle(row => row.Origin == "closure_fanout" && row.Status == "fulfilling"); + } + + /// + /// An organization that stopped allowing ordinary work after the Begin classified it fails alone, as a tenant that did: + /// no erasure is created in it, its MUST row records the refusal, and the other groups are still started. + /// + [Fact] + public async Task An_organization_that_stopped_allowing_ordinary_work_fails_alone() + { + await ArrangeAsync(); + await CloseAsync(PersonA); + await fixture.Postgres.ExecuteAsSuperuserAsync( + $"SET session_replication_role = replica; UPDATE public.organizations SET status = 'Archived' " + + $"WHERE tenant_id = '{SchemaFixture.TenantA}' AND id = '{SchemaFixture.OrgA1}'", + RebindProofSupport.DatabaseOf(_database!.MigrationConnectionString)); + await using var host = Host(new Grants(true)); + + var reports = await FanOutAsync(host, [TenantWideA, BranchA1, BranchA2]); + + reports.Should().Equal(new ClosureGroupReport(TenantWideA, ClosureGroupOutcome.Started), + new ClosureGroupReport(BranchA1, ClosureGroupOutcome.Failed), new ClosureGroupReport(BranchA2, ClosureGroupOutcome.Started)); + (await RequestsAsync(BranchA1)).Should().BeEmpty("a group whose organization no longer allows ordinary work is not started"); + (await AuditRowsAsync(BranchA1)).Should().ContainSingle().Which.Should() + .Be(new AuditRow(null, "failed", "closure_fan_out", true, false, "lockey_not_found")); + (await RequestsAsync(TenantWideA)).Should().ContainSingle(); + (await RequestsAsync(BranchA2)).Should().ContainSingle(); + } + + /// + /// An organization's group is fanned out and erased by itself: its erasure freezes the organization's Membership alone, + /// the job erases that Membership and leaves the person's tenant-wide Membership and the other branch's as they were. + /// + [Fact] + public async Task An_organization_group_is_fanned_out_and_erased_without_its_tenant_wide_group() + { + await ArrangeAsync(); + await CloseAsync(PersonA); + await using var host = Host(new Grants(true)); + + (await FanOutAsync(host, [BranchA1])).Should().Equal([new ClosureGroupReport(BranchA1, ClosureGroupOutcome.Started)]); + + var request = (await RequestsAsync(BranchA1)).Single(); + request.Snapshot.Should().Be(Snapshot([BranchMembershipA1])); + (await RequestsAsync(TenantWideA)).Should().BeEmpty("the tenant-wide group was not fanned out"); + (await RunJobAsync(host, BranchA1, request.Id)).Committed(); + (await RequestsAsync(BranchA1)).Single().Status.Should().Be("awaiting_privileged_step"); + (await MembershipAsync(BranchA1, BranchMembershipA1)).Should().Be(("Revoked", (string?)null, 0L)); + (await MembershipAsync(TenantWideA, LearnerMembershipA)).Should().Be(("Active", "profile-canary", 1L), + "the tenant-wide Membership is the tenant-wide group's"); + (await MembershipAsync(BranchA2, BranchMembershipA2)).Should().Be(("Active", "profile-canary", 1L), "so is the other branch's"); + } + + /// + /// An erasure a person or an administrator filed in the group, taken by the app role through its own arrows to the + /// privileged step as its job leaves it, while the person is still Active. + /// + private async Task AwaitingErasureAsync(ClosureParticipantGroup group, Guid membership, string origin) + { + var id = Guid.CreateVersion7(); + var requester = origin == "self" ? PersonA : AdminA; + var (tenant, organization) = (group.TenantId.Value, group.OrganizationId?.Value); + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, tenant, organization, PersonA); + await 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) + VALUES(@id,@tenant,@organization,'erasure',@origin,@subject,@requester,'scheduled',@snapshot::jsonb, + now() + interval '24 hours',now(),@requester) + """, ("id", id), ("tenant", tenant), ("organization", organization), ("origin", origin), ("subject", PersonA), + ("requester", requester), ("snapshot", DataRequestSchemaSeed.Snapshot(membership))); + await transaction.CommitAsync(); + } + + await DataErasureTestKit.BackdateAsync(_database!.MigrationConnectionString, tenant, organization, id); + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, tenant, organization, null); + await StepAsync(app, transaction, id, "status='fulfilling'"); + await StepAsync(app, transaction, id, "result='{\"consent_evidence\":2}'"); + await StepAsync(app, transaction, id, "status='awaiting_privileged_step'"); + await transaction.CommitAsync(); + } + + return id; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/ClosureFanOutTests.Finished.cs b/backend/tests/LearnStack.Tests.Integration/Database/ClosureFanOutTests.Finished.cs new file mode 100644 index 000000000..159ab9de2 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/ClosureFanOutTests.Finished.cs @@ -0,0 +1,78 @@ +using FluentAssertions; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Platform; +using LearnStack.Tests.Fixtures; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class ClosureFanOutTests +{ + /// + /// A repeated Begin's fan-out that reaches a group after the closure's Finalize committed (it read the person Closing + /// just before) finds the group's fan-out erasure completed: only Finalize completes one, in the transaction that closes + /// the person. The group is adopted with nothing stored and nothing designated, so its MUST row names neither the closed + /// person nor a request, and no failure row carries the person's identifiers into the tenant's trail after the closure's + /// redaction. + /// + [Fact] + public async Task A_group_whose_fan_out_the_closure_completed_is_adopted_with_a_row_that_names_no_one() + { + await ArrangeAsync(); + await CloseAsync(PersonA); + await using var host = Host(new Grants(true)); + (await FanOutAsync(host, [TenantWideA])).Should().Equal([new ClosureGroupReport(TenantWideA, ClosureGroupOutcome.Started)]); + var request = (await RequestsAsync(TenantWideA)).Single().Id; + (await RunJobAsync(host, TenantWideA, request)).Committed(); + await FinalizeAsync(request); + + var repeat = await FanOutAsync(host, [TenantWideA]); + + repeat.Should().Equal([new ClosureGroupReport(TenantWideA, ClosureGroupOutcome.Adopted)], + "the group's part of the closure is done, so a repeated Begin is owed nothing for it"); + (await RequestsAsync(TenantWideA)).Should().ContainSingle("nothing is filed for a Closed person") + .Which.Status.Should().Be("completed"); + var rows = await AuditRowsAsync(TenantWideA); + rows.Should().HaveCount(2); + rows[^1].Should().Be(new AuditRow(null, "success", "closure_fan_out", true, false, null), + "the adoption designates nothing, so its row names no request"); + (await LastRowStatesAsync(TenantWideA)).Should().NotContain(PersonA.ToString("D"), + "no state of the row names the closed person"); + } + + /// + /// The closure's Finalize as its second transaction leaves this group: the person Closed with the raw subject removed and + /// the group's fan-out erasure completed, on the platform role under the User key and every participant tenant's key. + /// + private async Task FinalizeAsync(Guid request) + { + await using var platform = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database!.PlatformConnectionString); + await using var transaction = await platform.BeginTransactionAsync(); + await ExecuteAsync(platform, transaction, "SELECT pg_catalog.pg_advisory_xact_lock(@key)", + ("key", IdentityAdvisoryLockKey.ForUser(UserId.From(PersonA)))); + foreach (var key in new[] { SchemaFixture.TenantA, SchemaFixture.TenantB } + .Select(tenant => IdentityAdvisoryLockKey.ForTenant(TenantId.From(tenant))).Order()) + await ExecuteAsync(platform, transaction, "SELECT pg_catalog.pg_advisory_xact_lock(@key)", ("key", key)); + await ExecuteAsync(platform, transaction, "UPDATE public.users SET status='Closed', provider_subject=NULL WHERE id=@user", + ("user", PersonA)); + await ExecuteAsync(platform, transaction, + "UPDATE public.data_subject_requests SET status='completed', row_version=row_version+1 WHERE id=@id", ("id", request)); + await transaction.CommitAsync(); + } + + /// The newest fan-out row's three states in exactly the group, as text, read under the group's own announcement. + private async Task LastRowStatesAsync(ClosureParticipantGroup group) + { + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, group.TenantId.Value, group.OrganizationId?.Value); + return await ScalarAsync(app, transaction, """ + SELECT concat_ws('|', before_state::text, after_state::text, changes::text, entity_id) FROM public.audit_log + WHERE operation=@operation AND organization_id IS NOT DISTINCT FROM @organization::uuid + ORDER BY timestamp DESC, id DESC LIMIT 1 + """, ("operation", Operation), ("organization", (object?)group.OrganizationId?.Value ?? DBNull.Value)); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/ClosureFanOutTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/ClosureFanOutTests.cs new file mode 100644 index 000000000..8b76680ce --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/ClosureFanOutTests.cs @@ -0,0 +1,584 @@ +using System.Diagnostics; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Application.Jobs; +using LearnStack.Infrastructure.Jobs; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Platform; +using LearnStack.Tests.Fixtures; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Hosting; +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 § 7's fan-out through the actual composition root, the actual gate, the actual operator act executor and the +/// actual pipeline, on real PostgreSQL as learnstack_app: one admitted act per participant group, announced for the +/// group's tenant and organization (ADR-0102 Amendment 2), creates the closing person's fan-out erasure and enqueues its +/// job, or adopts what the group already holds; the job then erases the group's every Membership of the person and awaits +/// the privileged step. +/// +/// +/// +/// Each case owns a disposable copy of the seeded schema, because a User a closure moved never returns to Active. Person A +/// holds Memberships in tenant A's tenant-wide group and its two branches, and the test gives them a Revoked tombstone and a +/// Suspended Membership in tenant B's tenant-wide group, so person A has four participant groups across two tenants. Begin is +/// another unit's; here the person's User is moved to Closing by the platform role under the closure's fences, exactly as +/// Begin's acquirer holds them, before the fan-out runs. +/// +/// +/// The gate is the production one over a grant source double that holds or withholds the operator's +/// platform.data_request.write grant, so the per-group admission is the real decision. +/// +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed partial class ClosureFanOutTests(SchemaFixture fixture) +{ + private const string Operation = "identity.data_request.fan_out_closure"; + private const string Ticket = "CHG-107-7"; + private DisposableSchemaDatabase? _database; + + private static readonly ClosureParticipantGroup TenantWideA = new(TenantId.From(SchemaFixture.TenantA), null); + private static readonly ClosureParticipantGroup BranchA1 = new(TenantId.From(SchemaFixture.TenantA), OrganizationId.From(SchemaFixture.OrgA1)); + private static readonly ClosureParticipantGroup BranchA2 = new(TenantId.From(SchemaFixture.TenantA), OrganizationId.From(SchemaFixture.OrgA2)); + private static readonly ClosureParticipantGroup TenantWideB = new(TenantId.From(SchemaFixture.TenantB), null); + private static readonly ClosureParticipantGroup[] Groups = [TenantWideA, BranchA1, BranchA2, TenantWideB]; + + private sealed record Arranged(Guid TombstoneB, Guid SuspendedB); + + /// + /// Every served group gets one fan-out erasure, fulfilling, the system actor's, with no window and the group's + /// every Membership of the person frozen, and one erasure job of its own scope on the same transaction; one MUST row per + /// group in that tenant names the operator and the closed reason and carries no ticket; a group's rows are invisible to + /// every other group. A repeat adopts each group's request and writes nothing new while each job is still queued. + /// + [Fact] + public async Task Every_served_group_gets_one_fan_out_erasure_and_its_job_and_a_repeat_adopts_them() + { + var arranged = await ArrangeAsync(); + await CloseAsync(PersonA); + await using var host = Host(new Grants(true)); + + // Listed out of the canonical order on purpose. + var reports = await FanOutAsync(host, [TenantWideB, BranchA2, TenantWideA, BranchA1]); + + reports.Should().Equal(Groups.Select(group => new ClosureGroupReport(group, ClosureGroupOutcome.Started)), + "every group is started, in the fan-out's own order"); + var snapshots = new Dictionary + { + [TenantWideA] = [LearnerMembershipA], + [BranchA1] = [BranchMembershipA1], + [BranchA2] = [BranchMembershipA2], + [TenantWideB] = new[] { arranged.TombstoneB, arranged.SuspendedB }.Order().ToArray(), + }; + var requests = new Dictionary(); + foreach (var group in Groups) + { + var request = (await RequestsAsync(group)).Should().ContainSingle().Subject; + request.Should().BeEquivalentTo(new RequestRow(request.Id, "erasure", "closure_fanout", "fulfilling", null, false, SystemActor, + Snapshot(snapshots[group])), group.ToString()); + requests[group] = request.Id; + (await JobsAsync(group, request.Id)).Should().Be(1, "the fan-out's job is enqueued on the transaction that created it"); + var row = (await AuditRowsAsync(group)).Should().ContainSingle().Subject; + row.Should().Be(new AuditRow(request.Id.ToString("D"), "success", "closure_fan_out", true, false, null), group.ToString()); + } + + // Each group's rows live under its own announcement only: the canonical row policy admits an organization the + // tenant-wide rows, never another organization's or another tenant's. + foreach (var group in Groups) + (await VisibleAsync(group, requests[group])).Should().Be(1, $"{group} sees its own request, so a zero below is isolation and not an unreadable table"); + (await VisibleAsync(BranchA1, requests[BranchA2])).Should().Be(0); + (await VisibleAsync(BranchA2, requests[BranchA1])).Should().Be(0); + (await VisibleAsync(TenantWideB, requests[TenantWideA])).Should().Be(0); + (await VisibleAsync(TenantWideA, requests[TenantWideB])).Should().Be(0); + (await VisibleAsync(TenantWideA, requests[BranchA1])).Should().Be(0, "a tenant-wide announcement shows no organization's rows"); + + var repeat = await FanOutAsync(host, Groups); + + repeat.Should().Equal(Groups.Select(group => new ClosureGroupReport(group, ClosureGroupOutcome.Adopted))); + foreach (var group in Groups) + { + (await RequestsAsync(group)).Should().ContainSingle("the one-active index holds and nothing is filed twice") + .Which.Id.Should().Be(requests[group]); + (await JobsAsync(group, requests[group])).Should().Be(1, "a queued job is not enqueued again"); + (await AuditRowsAsync(group)).Select(row => row.Entity).Should().Equal([requests[group].ToString("D"), requests[group].ToString("D")], + "the repeat's row names the request it adopted"); + } + + (await UserStatusAsync(PersonA)).Should().Be("Closing"); + } + + /// + /// The fan-out erasure runs through the actual erasure job for a Closing person: it starts at fulfilling, so no + /// eligibility is asked again and even a hold the eligibility port would report does not block it; it erases the group's + /// every Membership of the person, the Revoked tombstone's profile and the Suspended one included, records the retained + /// report and waits for the privileged step. Another tenant's Memberships of the same person are untouched. + /// + [Fact] + public async Task The_fan_out_job_erases_the_closing_persons_every_membership_of_the_group_and_awaits_the_privileged_step() + { + var arranged = await ArrangeAsync(); + await CloseAsync(PersonA); + await using var host = Host(new Grants(true), services => + { + services.RemoveAll(); + services.AddSingleton(new EveryHold()); + }); + (await FanOutAsync(host, [TenantWideB])).Should().Equal([new ClosureGroupReport(TenantWideB, ClosureGroupOutcome.Started)]); + var request = (await RequestsAsync(TenantWideB)).Single().Id; + + (await RunJobAsync(host, TenantWideB, request)).Committed(); + + var state = (await RequestsAsync(TenantWideB)).Single(); + state.Status.Should().Be("awaiting_privileged_step", "a closure's erasure is never blocked: its eligibility is Begin's"); + var (progress, result) = await RequestDocumentsAsync(TenantWideB, request); + JsonDocument.Parse(progress).RootElement.EnumerateObject().Select(entry => entry.Name).Should() + .BeEquivalentTo(["audit", "customization", "education", "identity", "tenancy"]); + JsonDocument.Parse(result).RootElement.EnumerateObject().Select(entry => entry.Name).Should().Contain("request_receipt"); + foreach (var membership in new[] { arranged.TombstoneB, arranged.SuspendedB }) + (await MembershipAsync(TenantWideB, membership)).Should().Be(("Revoked", (string?)null, 0L), + "every Membership of the group, of any status, loses its profile and assignments and is the Revoked tombstone"); + (await MembershipAsync(TenantWideA, LearnerMembershipA)).Should().Be(("Active", "profile-canary", 1L), + "another tenant's Membership of the person is that tenant's fan-out's"); + (await UserStatusAsync(PersonA)).Should().Be("Closing", "the erasure never touches users"); + (await AuditCountAsync(TenantWideB, "identity.data_request.fulfill_erasure", request)).Should().Be(1); + } + + /// + /// ADR-0107 § 7's adoption, group by group, of what each group already held when the closure began: a person's erasure + /// still in its window is cancelled by the system actor and replaced in the same transaction, the cancellation travelling + /// in the fan-out row's changes; one past its window waits for its own job; a terminal one is replaced by a new fan-out; + /// and one past its window whose job is dead is stored failed first, as every creation path stores it, then replaced. + /// + [Fact] + public async Task Each_group_adopts_cancels_waits_for_or_replaces_what_it_already_holds() + { + var arranged = await ArrangeAsync(); + var inWindow = await FileAsync(TenantWideA, PersonA, [LearnerMembershipA], "erasure"); + var pastWindow = await FileAsync(BranchA1, PersonA, [BranchMembershipA1], "erasure"); + await DataErasureTestKit.BackdateAsync(_database!.MigrationConnectionString, SchemaFixture.TenantA, SchemaFixture.OrgA1, pastWindow); + var cancelled = await FileAsync(BranchA2, PersonA, [BranchMembershipA2], "erasure"); + await CancelAsync(BranchA2, cancelled); + var deadJob = await FileAsync(TenantWideB, PersonA, [arranged.TombstoneB, arranged.SuspendedB], "erasure"); + await DataErasureTestKit.BackdateAsync(_database!.MigrationConnectionString, SchemaFixture.TenantB, null, deadJob); + await DataErasureTestKit.SubmitAsync(_database!, SchemaFixture.TenantB, null, deadJob); + await KillJobAsync(TenantWideB, deadJob); + await CloseAsync(PersonA); + await using var host = Host(new Grants(true)); + + var reports = await FanOutAsync(host, [TenantWideA, BranchA1, BranchA2, TenantWideB]); + + reports.Should().Equal(new ClosureGroupReport(TenantWideA, ClosureGroupOutcome.Started), + new ClosureGroupReport(BranchA1, ClosureGroupOutcome.Waiting), new ClosureGroupReport(BranchA2, ClosureGroupOutcome.Started), + new ClosureGroupReport(TenantWideB, ClosureGroupOutcome.Started)); + var tenantB = await RequestsAsync(TenantWideB); + tenantB.Single(row => row.Id == deadJob).Status.Should().Be("failed", "a dead job's erasure is stored failed before it is replaced"); + tenantB.Should().ContainSingle(row => row.Origin == "closure_fanout" && row.Status == "fulfilling"); + + var tenantWide = await RequestsAsync(TenantWideA); + tenantWide.Single(row => row.Id == inWindow).Should().Match(row => row.Status == "cancelled" && row.UpdatedBy == SystemActor, + "the person's erasure in its window is cancelled by the system actor"); + var replacement = tenantWide.Should().ContainSingle(row => row.Origin == "closure_fanout").Subject; + replacement.Status.Should().Be("fulfilling"); + var changes = await AuditChangesAsync(TenantWideA, replacement.Id); + changes.Should().Contain(inWindow.ToString("D"), "the cancelled erasure travels in the fan-out row's changes"); + + (await RequestsAsync(BranchA1)).Should().ContainSingle("a person's erasure past its window is its own job's; nothing is added") + .Which.Should().Match(row => row.Id == pastWindow && row.Status == "scheduled"); + var branch = (await AuditRowsAsync(BranchA1)).Should().ContainSingle().Subject; + branch.Entity.Should().Be(pastWindow.ToString("D"), "the waiting group's row names the erasure it waits for"); + + (await RequestsAsync(BranchA2)).Should().HaveCount(2).And.ContainSingle(row => row.Origin == "closure_fanout" && row.Status == "fulfilling", + "a terminal erasure is replaced by a new fan-out"); + } + + /// + /// A group's fan-out awaiting the privileged step is adopted as it is; one still fulfilling whose job is dead gets + /// its job enqueued again by the repeat, and the second job resumes it to the privileged step. + /// + [Fact] + public async Task A_repeat_adopts_an_awaiting_erasure_and_enqueues_a_dead_fan_out_job_again() + { + await ArrangeAsync(); + await CloseAsync(PersonA); + await using var host = Host(new Grants(true)); + (await FanOutAsync(host, [TenantWideA, BranchA1])).Should().OnlyContain(report => report.Outcome == ClosureGroupOutcome.Started); + var awaiting = (await RequestsAsync(TenantWideA)).Single().Id; + (await RunJobAsync(host, TenantWideA, awaiting)).Committed(); + var dead = (await RequestsAsync(BranchA1)).Single().Id; + await KillJobAsync(BranchA1, dead); + + var repeat = await FanOutAsync(host, [TenantWideA, BranchA1]); + + repeat.Should().Equal(new ClosureGroupReport(TenantWideA, ClosureGroupOutcome.Adopted), new ClosureGroupReport(BranchA1, ClosureGroupOutcome.Adopted)); + (await JobsAsync(TenantWideA, awaiting)).Should().Be(1, "an erasure awaiting its privileged step needs no job"); + (await JobsAsync(BranchA1, dead)).Should().Be(2, "the dead job's request is enqueued again"); + (await RequestsAsync(BranchA1)).Should().ContainSingle().Which.Status.Should().Be("fulfilling"); + + (await RunJobAsync(host, BranchA1, dead, newest: true)).Committed(); + (await RequestsAsync(BranchA1)).Single().Status.Should().Be("awaiting_privileged_step", "the second job resumes the request"); + } + + /// + /// The gate decides per act: an operator without platform.data_request.write starts no group, and nothing is + /// written anywhere. A group whose tenant stopped allowing ordinary work after Begin judged it fails alone, with its MUST + /// row and its refusal, and every other group is still started; the person not Closing is refused by the database. + /// + [Fact] + public async Task The_gate_refuses_every_group_for_an_ungranted_operator_and_a_failed_group_does_not_stop_the_others() + { + await ArrangeAsync(); + await using (var refused = Host(new Grants(false))) + { + // Person A is still Active: no admission means not even the database's refusal is reached. + (await FanOutAsync(refused, Groups)).Should().OnlyContain(report => report.Outcome == ClosureGroupOutcome.Failed); + foreach (var group in Groups) + { + (await RequestsAsync(group)).Should().BeEmpty(); + (await AuditRowsAsync(group)).Should().BeEmpty("a refused admission runs no act and writes no row"); + } + } + + await using var host = Host(new Grants(true)); + (await FanOutAsync(host, [TenantWideA])).Should().Equal([new ClosureGroupReport(TenantWideA, ClosureGroupOutcome.Failed)], + "an Active person has no fan-out: the request guard refuses the subject"); + (await RequestsAsync(TenantWideA)).Should().BeEmpty(); + var refusal = (await AuditRowsAsync(TenantWideA)).Should().ContainSingle().Subject; + refusal.Should().Be(new AuditRow(refusal.Entity, "failed", "closure_fan_out", true, false, "lockey_business_rule_violation"), + "the refused group's row records the refusal, naming the request it would have created, which was never stored"); + refusal.Entity.Should().NotBeNull(); + + await CloseAsync(PersonA); + await SetTenantStatusAsync(SchemaFixture.TenantB, "Suspended"); + var reports = await FanOutAsync(host, Groups); + + reports.Should().Equal(new ClosureGroupReport(TenantWideA, ClosureGroupOutcome.Started), new ClosureGroupReport(BranchA1, ClosureGroupOutcome.Started), + new ClosureGroupReport(BranchA2, ClosureGroupOutcome.Started), new ClosureGroupReport(TenantWideB, ClosureGroupOutcome.Failed)); + (await RequestsAsync(TenantWideB)).Should().BeEmpty("a group whose tenant no longer allows ordinary work is not started"); + (await AuditRowsAsync(TenantWideB)).Should().ContainSingle().Which.Should().Be(new AuditRow(null, "failed", "closure_fan_out", true, false, + "lockey_not_found")); + } + + /// Person A's tombstone and Suspended Membership in tenant B's tenant-wide group, written while person A is Active. + private async Task ArrangeAsync() + { + _database = await DataExportTestKit.CreateSeededDatabaseAsync(fixture.Postgres); + var arranged = new Arranged(Guid.CreateVersion7(), Guid.CreateVersion7()); + var learner = RoleId(SchemaFixture.TenantB, BuiltInRoleKey.Learner, PermissionScope.Tenant); + await using var app = await DataExportTestKit.OpenAppAsync(_database.AppConnectionString); + foreach (var step in new Func[] + { + transaction => InsertMemberAsync(app, transaction, SchemaFixture.TenantB, null, arranged.TombstoneB, PersonA, learner, "tombstone-canary"), + transaction => ExecuteAsync(app, transaction, """ + UPDATE public.memberships SET status='Revoked', deleted_at=clock_timestamp(), deleted_by=@system, + updated_at=clock_timestamp(), updated_by=@system, row_version=row_version+1 WHERE id=@member + """, ("member", arranged.TombstoneB), ("system", SystemActor)), + transaction => InsertMemberAsync(app, transaction, SchemaFixture.TenantB, null, arranged.SuspendedB, PersonA, learner, "suspended-canary"), + transaction => ExecuteAsync(app, transaction, """ + UPDATE public.memberships SET status='Suspended', updated_at=clock_timestamp(), updated_by=@system, + row_version=row_version+1 WHERE id=@member + """, ("member", arranged.SuspendedB), ("system", SystemActor)), + }) + { + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantB); + await LockAsync(app, transaction, SchemaFixture.TenantB, PersonA, false); + await step(transaction); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await transaction.CommitAsync(); + } + + return arranged; + } + + /// + /// The person's User Active to Closing on the platform role, under the closure's fences as Begin's acquirer takes them: + /// the User key, then each participant tenant's key ascending, all transaction-scoped and exclusive. + /// + private async Task CloseAsync(Guid user) + { + await using var platform = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database!.PlatformConnectionString); + await using var transaction = await platform.BeginTransactionAsync(); + await ExecuteAsync(platform, transaction, "SELECT pg_catalog.pg_advisory_xact_lock(@key)", + ("key", IdentityAdvisoryLockKey.ForUser(UserId.From(user)))); + foreach (var key in new[] { SchemaFixture.TenantA, SchemaFixture.TenantB } + .Select(tenant => IdentityAdvisoryLockKey.ForTenant(TenantId.From(tenant))).Order()) + await ExecuteAsync(platform, transaction, "SELECT pg_catalog.pg_advisory_xact_lock(@key)", ("key", key)); + await ExecuteAsync(platform, transaction, "UPDATE public.users SET status='Closing' WHERE id=@user", ("user", user)); + await transaction.CommitAsync(); + } + + /// The API composition over the disposable database, with the operator's grant held or withheld. + private WebApplicationFactory Host(Grants grants, Action? configure = null) => + new ConstructionOnlyApiFactory().WithWebHostBuilder(builder => + { + builder.UseEnvironment(Environments.Development); + builder.UseSetting("ConnectionStrings:Default", _database!.AppConnectionString); + builder.UseSetting("ConnectionStrings:OutboxDispatcher", _database!.OutboxConnectionString); + builder.UseSetting("ConnectionStrings:PlatformAdmin", _database!.PlatformConnectionString); + builder.ConfigureTestServices(services => + { + services.RemoveAll(); + services.AddSingleton(grants); + configure?.Invoke(services); + }); + }); + + /// Begin's call, from a request scope with the trace the HTTP request would carry. + private static async Task> FanOutAsync(WebApplicationFactory host, + IReadOnlyList groups) + { + using var activity = new Activity("closure-fan-out-test").Start(); + await using var scope = host.Services.CreateAsyncScope(); + return await scope.ServiceProvider.GetRequiredService().FanOutAsync(TestPlatformAdmissions.Witness(), Ticket, + new ClosureFanOutRequest(UserId.From(PersonA), groups)); + } + + /// Runs the request's newest (or only) erasure job through the actual runtime. + private async Task RunJobAsync(WebApplicationFactory host, ClosureParticipantGroup group, Guid request, + bool newest = false) + { + var job = await JobIdAsync(group, request, newest); + var executor = host.Services.GetRequiredService(); + var start = await executor.ExecuteAsync(await DataExportTestKit.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 RequestRow(Guid Id, string Kind, string Origin, string Status, Guid? Requester, bool Windowed, Guid CreatedBy, + string Snapshot) + { + public Guid? UpdatedBy { get; init; } + } + + /// + /// Every erasure of person A in the group, read under the group's own announcement; the seeded exports are not this + /// proof's. + /// + private async Task> RequestsAsync(ClosureParticipantGroup group) + { + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, group.TenantId.Value, group.OrganizationId?.Value); + await using var command = new NpgsqlCommand(""" + SELECT id, kind, origin, status, requester_user_id, execute_at IS NOT NULL, created_by, membership_snapshot::text, updated_by + FROM public.data_subject_requests + WHERE subject_user_id=@subject AND tenant_id=@tenant AND organization_id IS NOT DISTINCT FROM @organization::uuid + AND kind='erasure' + ORDER BY id + """, app, transaction); + command.Parameters.AddWithValue("subject", PersonA); + command.Parameters.AddWithValue("tenant", group.TenantId.Value); + command.Parameters.AddWithValue("organization", (object?)group.OrganizationId?.Value ?? DBNull.Value); + var rows = new List(); + await using var row = await command.ExecuteReaderAsync(); + while (await row.ReadAsync()) + rows.Add(new RequestRow(row.GetGuid(0), row.GetString(1), row.GetString(2), row.GetString(3), row.IsDBNull(4) ? null : row.GetGuid(4), + row.GetBoolean(5), row.GetGuid(6), Normalize(row.GetString(7))) + { UpdatedBy = row.IsDBNull(8) ? null : row.GetGuid(8) }); + return rows; + } + + private static string Snapshot(Guid[] memberships) => Normalize(DataRequestSchemaSeed.Snapshot(memberships)); + + private static string Normalize(string json) => + JsonSerializer.Serialize(JsonDocument.Parse(json).RootElement.EnumerateArray().Select(item => item.GetString()).Order(StringComparer.Ordinal)); + + private async Task<(string Progress, string Result)> RequestDocumentsAsync(ClosureParticipantGroup group, Guid request) + { + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, group.TenantId.Value, group.OrganizationId?.Value); + await using var command = new NpgsqlCommand("SELECT progress::text, result::text 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 (row.GetString(0), row.GetString(1)); + } + + /// + /// How many rows of the request the group's own announcement shows, as the application role: the plain count, so a row + /// the policy leaked is one however it is scoped. + /// + private async Task VisibleAsync(ClosureParticipantGroup group, Guid request) + { + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, group.TenantId.Value, group.OrganizationId?.Value); + return await ScalarAsync(app, transaction, "SELECT count(*) FROM public.data_subject_requests WHERE id=@id", ("id", request)); + } + + /// The erasure jobs of the request in its group, by the exact route the scheduler stored. + private async Task JobsAsync(ClosureParticipantGroup group, Guid request) + { + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, group.TenantId.Value, group.OrganizationId?.Value); + return await ScalarAsync(app, transaction, """ + SELECT count(*) FROM public.background_jobs + WHERE tenant_id=@tenant AND organization_id IS NOT DISTINCT FROM @organization::uuid AND definition_key=@definition + AND parameters=@parameters + """, ("tenant", group.TenantId.Value), ("organization", (object?)group.OrganizationId?.Value ?? DBNull.Value), + ("definition", Definition(group)), ("parameters", DataErasureTestKit.Parameters(request))); + } + + private async Task JobIdAsync(ClosureParticipantGroup group, Guid request, bool newest) + { + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, group.TenantId.Value, group.OrganizationId?.Value); + var id = await ScalarAsync(app, transaction, $""" + SELECT id FROM public.background_jobs + WHERE tenant_id=@tenant AND organization_id IS NOT DISTINCT FROM @organization::uuid AND definition_key=@definition + AND parameters=@parameters + ORDER BY created_at {(newest ? "DESC" : "ASC")}, id {(newest ? "DESC" : "ASC")} LIMIT 1 + """, ("tenant", group.TenantId.Value), ("organization", (object?)group.OrganizationId?.Value ?? DBNull.Value), + ("definition", Definition(group)), ("parameters", DataErasureTestKit.Parameters(request))); + return BackgroundJobId.From(id); + } + + /// Quarantines the request's job as the runtime does with an unknown outcome: the job is dead. + private async Task KillJobAsync(ClosureParticipantGroup group, Guid request) + { + var job = await JobIdAsync(group, request, newest: true); + await using var dispatcher = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database!.OutboxConnectionString); + (await ScalarAsync(dispatcher, null, """ + WITH moved AS (UPDATE public.background_jobs SET phase='quarantined', quarantine_reason='unknown_outcome' WHERE id=@job RETURNING 1) + SELECT count(*) FROM moved + """, ("job", job.Value))).Should().Be(1); + } + + private static string Definition(ClosureParticipantGroup group) => group.OrganizationId is null + ? "identity.data_erasure_tenant.v1" : "identity.data_erasure_organization.v1"; + + private sealed record AuditRow(string? Entity, string Outcome, string? Reason, bool Operator, bool Ticket, string? ErrorKey); + + /// The fan-out's rows in exactly the group, read under the group's own announcement. + private async Task> AuditRowsAsync(ClosureParticipantGroup group) + { + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, group.TenantId.Value, group.OrganizationId?.Value); + await using var command = new NpgsqlCommand(""" + SELECT entity_id, outcome, reason, metadata ? 'operator', metadata::text LIKE '%' || @ticket || '%', error_key + FROM public.audit_log + WHERE operation=@operation AND organization_id IS NOT DISTINCT FROM @organization::uuid + ORDER BY timestamp, id + """, app, transaction); + command.Parameters.AddWithValue("operation", Operation); + command.Parameters.AddWithValue("ticket", Ticket); + command.Parameters.AddWithValue("organization", (object?)group.OrganizationId?.Value ?? DBNull.Value); + var rows = new List(); + await using var row = await command.ExecuteReaderAsync(); + while (await row.ReadAsync()) + rows.Add(new AuditRow(row.IsDBNull(0) ? null : row.GetString(0), row.GetString(1), row.IsDBNull(2) ? null : row.GetString(2), + row.GetBoolean(3), row.GetBoolean(4), row.IsDBNull(5) ? null : row.GetString(5))); + return rows; + } + + private async Task AuditChangesAsync(ClosureParticipantGroup group, Guid request) + { + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, group.TenantId.Value, group.OrganizationId?.Value); + return await ScalarAsync(app, transaction, """ + SELECT coalesce(changes::text, '') FROM public.audit_log + WHERE operation=@operation AND outcome='success' AND entity_id=@entity + """, ("operation", Operation), ("entity", request.ToString("D"))); + } + + private async Task AuditCountAsync(ClosureParticipantGroup group, string operation, Guid entity) + { + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, group.TenantId.Value, group.OrganizationId?.Value); + return await ScalarAsync(app, transaction, """ + SELECT count(*) FROM public.audit_log WHERE operation=@operation AND outcome='success' AND entity_id=@entity + """, ("operation", operation), ("entity", entity.ToString("D"))); + } + + private async Task<(string Status, string? DisplayName, long Assignments)> MembershipAsync(ClosureParticipantGroup group, Guid membership) + { + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, group.TenantId.Value, group.OrganizationId?.Value); + await using var command = new NpgsqlCommand(""" + SELECT m.status, p.display_name, + (SELECT count(*) FROM public.membership_role_assignments a WHERE a.tenant_id=m.tenant_id AND a.membership_id=m.id) + FROM public.memberships m JOIN public.membership_profiles p ON p.tenant_id=m.tenant_id AND p.membership_id=m.id + WHERE m.id=@id + """, app, transaction); + command.Parameters.AddWithValue("id", membership); + await using var row = await command.ExecuteReaderAsync(); + (await row.ReadAsync()).Should().BeTrue(); + return (row.GetString(0), row.IsDBNull(1) ? null : row.GetString(1), row.GetInt64(2)); + } + + private async Task UserStatusAsync(Guid user) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database!.MigrationConnectionString); + return await ScalarAsync(owner, null, "SELECT status FROM public.users WHERE id=@id", ("id", user)); + } + + /// A self-filed request in its initial state, under the canonical fences, while the person is Active. + private async Task FileAsync(ClosureParticipantGroup group, Guid subject, Guid[] memberships, string kind) + { + var id = Guid.CreateVersion7(); + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, group.TenantId.Value, group.OrganizationId?.Value, subject); + await InsertRequestAsync(app, transaction, id, group.TenantId.Value, group.OrganizationId?.Value, subject, memberships, kind); + await transaction.CommitAsync(); + return id; + } + + /// The person cancels a scheduled erasure in its window, as the application role does. + private async Task CancelAsync(ClosureParticipantGroup group, Guid request) + { + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, group.TenantId.Value, group.OrganizationId?.Value, null); + await StepAsync(app, transaction, request, "status='cancelled'"); + await transaction.CommitAsync(); + } + + private async Task SetTenantStatusAsync(Guid tenant, string status) + { + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await EducationSchemaSeed.AnnounceAsync(app, transaction, tenant, null); + await TenancyLifecycleFixture.LockAsync(app, transaction, tenant); + await ExecuteAsync(app, transaction, "UPDATE tenants SET status = @status WHERE id = @tenant", ("status", status), ("tenant", tenant)); + await transaction.CommitAsync(); + } + + /// The operator's grant of the one key every fan-out act needs, held or withheld. + private sealed class Grants(bool held) : IPlatformOperatorGrantSource + { + public ValueTask IsGrantedAsync(string subjectDigest, string permissionKey, CancellationToken cancellationToken = default) => + ValueTask.FromResult(held && permissionKey == PlatformPermissions.DataRequestWrite.Key + && subjectDigest == TestPlatformAdmissions.Witness().SubjectDigest); + } + + /// A hold the eligibility port would report for every request: a closure's erasure never asks it. + private sealed class EveryHold : IDataRequestHoldSource + { + public Task HasHoldAsync(DataRequestHoldQuery query, CancellationToken cancellationToken) => Task.FromResult(true); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataErasureExecutionTests.Coverage.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataErasureExecutionTests.Coverage.cs new file mode 100644 index 000000000..1d83587a2 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataErasureExecutionTests.Coverage.cs @@ -0,0 +1,579 @@ +using System.Collections.Concurrent; +using System.Globalization; +using System.Text.Json; +using FluentAssertions; +using LearnStack.SharedKernel.DataProtection; +using Microsoft.Extensions.DependencyInjection; +using Npgsql; +using Serilog.Core; +using Serilog.Events; +using Xunit; +using static LearnStack.Tests.Integration.Database.DataRequestSchemaSeed; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The erasure's isolation across a person's groups, its resume from recorded progress, its early-run retry and the branches +/// of DataErasureService the first cases do not reach (ADR-0107 § 5), through the same job runtime and composition +/// root as the neighbouring cases. +/// +public sealed partial class DataErasureExecutionTests +{ + /// What the person owns in one group: an offer they issued, a readable export and a request not yet stored. + private sealed record Footprint(Guid Tenant, Guid? Organization, Guid Invitation, Guid Artifact, Guid Export); + + /// + /// ADR-0107 § 5 erases exactly the request's group. The person holds, in each of their other groups and in another + /// tenant, a pending invitation they issued, an available artifact and an export that is only requested; the job + /// withdraws those of the erased group and leaves every other one, and every audit row about them, absent. + /// + [Theory] + [InlineData("tenant")] + [InlineData("organization")] + public async Task Erasing_one_group_withdraws_its_offers_and_exports_and_touches_none_of_the_persons_other_groups(string scope) + { + await using var database = await OpenDatabaseAsync(); + var groups = new (Guid? Organization, Guid Membership, Row Seeded)[] + { + (null, LearnerMembershipA, TenantWideA), (SchemaFixture.OrgA1, BranchMembershipA1, BranchA1), + (SchemaFixture.OrgA2, BranchMembershipA2, BranchA2), + }; + var footprints = new List(); + foreach (var (organization, membership, seeded) in groups) + { + footprints.Add(new Footprint(SchemaFixture.TenantA, organization, await IssueInvitationAsync(SchemaFixture.TenantA, organization, PersonA), + seeded.Artifact!.Value, await FileAsync(SchemaFixture.TenantA, organization, PersonA, [membership], "export"))); + } + + // The same person in another tenant: tenant B's isolation is the policy's, not the job's own predicates. + var foreignMembership = Guid.CreateVersion7(); + await using (var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, transaction, SchemaFixture.TenantB, null); + await LockAsync(app, transaction, SchemaFixture.TenantB, PersonA, false); + await InsertMemberAsync(app, transaction, SchemaFixture.TenantB, null, foreignMembership, PersonA, + RoleId(SchemaFixture.TenantB, LearnStack.SharedKernel.Permissions.BuiltInRoleKey.Learner, + LearnStack.SharedKernel.Permissions.PermissionScope.Tenant)); + await transaction.CommitAsync(); + } + + var foreign = new Footprint(SchemaFixture.TenantB, null, await IssueInvitationAsync(SchemaFixture.TenantB, null, PersonA), + await SeedArtifactAsync(SchemaFixture.TenantB, null, PersonA, foreignMembership), Guid.Empty); + foreign = foreign with { Export = await FileAsync(SchemaFixture.TenantB, null, PersonA, [foreignMembership], "export") }; + footprints.Add(foreign); + + var targetIndex = scope == "tenant" ? 0 : 1; + var target = footprints[targetIndex]; + var erasure = await FileDueErasureAsync(target.Tenant, target.Organization, PersonA, [groups[targetIndex].Membership]); + foreach (var footprint in footprints) + { + (await InvitationAsync(footprint.Tenant, footprint.Organization, footprint.Invitation)).Status.Should().Be("Pending", "arranged"); + (await ArtifactAsync(footprint.Tenant, footprint.Organization, footprint.Artifact)).Should().Be(("available", 1L), "arranged"); + (await RequestAsync(footprint.Tenant, footprint.Organization, footprint.Export)).Status.Should().Be("requested", "arranged"); + } + + await using var host = Host(); + (await RunAsync(host.Services, await DataErasureTestKit.SubmitAsync(database, target.Tenant, target.Organization, erasure))).Committed(); + + (await RequestAsync(target.Tenant, target.Organization, erasure)).Status.Should().Be("awaiting_privileged_step"); + (await InvitationAsync(target.Tenant, target.Organization, target.Invitation)).Status.Should().Be("Revoked"); + (await ArtifactAsync(target.Tenant, target.Organization, target.Artifact)).Should().Be(("revoked", 0L)); + (await RequestAsync(target.Tenant, target.Organization, target.Export)).Status.Should().Be("cancelled"); + foreach (var other in footprints.Where(footprint => footprint != target)) + { + var group = other.Tenant == SchemaFixture.TenantB ? "another tenant" : other.Organization is null ? "the tenant-wide group" : "a branch"; + (await InvitationAsync(other.Tenant, other.Organization, other.Invitation)).Should().Be(("Pending", (Guid?)null), + "the person's offer in " + group + " is not this erasure's"); + (await ArtifactAsync(other.Tenant, other.Organization, other.Artifact)).Should().Be(("available", 1L), + "the person's readable export in " + group + " stays readable"); + (await RequestAsync(other.Tenant, other.Organization, other.Export)).Status.Should().Be("requested", + "the person's pending export in " + group + " is not cancelled"); + (await AuditAsync(other.Tenant, other.Organization, "identity.invitation.revoke", other.Invitation)).Should().Be(0); + (await AuditAsync(other.Tenant, other.Organization, "identity.data_export.revoke", other.Artifact)).Should().Be(0); + (await AuditAsync(other.Tenant, other.Organization, "identity.data_request.cancel", other.Export)).Should().Be(0); + } + } + + /// + /// ADR-0107 § 1: a request already fulfilling (a retried one, or a closure's fan-out erasure that starts there) + /// skips the participants its progress records and runs the rest once; a recorded real participant's work is not + /// repeated, which shows as its effect being absent. + /// + [Theory] + [InlineData("recorded_prefix")] + [InlineData("identity_recorded")] + [InlineData("empty_progress")] + public async Task A_fulfilling_erasure_skips_the_participants_its_progress_records_and_runs_the_rest_once(string variant) + { + await using var database = await OpenDatabaseAsync(); + var recorded = variant switch + { + "recorded_prefix" => new[] { "alpha", "audit", "beta", "customization", "education" }, + "identity_recorded" => ["alpha", "audit", "identity"], + _ => Array.Empty(), + }; + var counters = new[] { new CountingParticipant("alpha"), new CountingParticipant("beta"), new CountingParticipant("zeta") }; + var erasure = await FileDueErasureAsync(SchemaFixture.TenantA, null, PersonA, [LearnerMembershipA]); + await StartFulfillingAsync(SchemaFixture.TenantA, null, PersonA, erasure, recorded); + await using var host = Host(services => + { + foreach (var counter in counters) services.AddSingleton(counter); + }); + + (await RunAsync(host.Services, await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, null, erasure))).Committed(); + + var state = await RequestAsync(SchemaFixture.TenantA, null, erasure); + state.Status.Should().Be("awaiting_privileged_step"); + JsonDocument.Parse(state.Progress).RootElement.EnumerateObject().Select(entry => entry.Name).Should() + .BeEquivalentTo(Participants.Concat(["alpha", "beta", "zeta"]), "every participant is recorded once the erasure ends"); + counters.ToDictionary(counter => counter.Key, counter => counter.Erased).Should().Equal( + new Dictionary { ["alpha"] = recorded.Contains("alpha") ? 0 : 1, ["beta"] = recorded.Contains("beta") ? 0 : 1, ["zeta"] = 1 }, + "a recorded participant is not run again, every other runs exactly once"); + (await MembershipAsync(SchemaFixture.TenantA, null, LearnerMembershipA)).Status.Should().Be( + recorded.Contains("identity") ? "Active" : "Revoked", + "the Identity participant's erasure ran if and only if its progress did not record it"); + } + + /// + /// ADR-0106 § 8: a run that wakes before the window ends fails its attempt for the runtime's retry. The failure is that + /// one, nothing runs and the request stays scheduled; the same job then completes once the clock has passed the time. + /// + [Fact] + public async Task A_run_that_wakes_before_the_window_ends_fails_for_the_retry_runs_nothing_and_completes_once_due() + { + await using var database = await OpenDatabaseAsync(); + var counter = new CountingParticipant("alpha"); + var logs = new ErasureLogCapture(); + var erasure = await FileAsync(SchemaFixture.TenantA, null, PersonA, [LearnerMembershipA], "erasure"); + await using var host = Host(services => + { + services.AddSingleton(counter); + services.AddSingleton(logs); + }); + + var early = await RunAsync(host.Services, await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, null, erasure)); + + early.CommitAcknowledged.Should().BeFalse(); + early.KnownRollback.Should().BeTrue("the attempt failed, it did not merely not commit"); + early.Decision.ErrorCode.Should().NotBeNull("the runtime recorded a failure for its retry, not a success"); + logs.Rendered().Should().Contain("is not yet due", "the recorded cause is the early run, not any other failure") + .And.Contain(erasure.ToString("D")).And.NotContain("finished (", "the early run reached no outcome"); + counter.Erased.Should().Be(0, "no participant ran"); + (await RequestAsync(SchemaFixture.TenantA, null, erasure)).Status.Should().Be("scheduled"); + (await MembershipAsync(SchemaFixture.TenantA, null, LearnerMembershipA)).Status.Should().Be("Active"); + + await DataErasureTestKit.BackdateAsync(database.MigrationConnectionString, SchemaFixture.TenantA, null, erasure); + (await RunAsync(host.Services, await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, null, erasure))).Committed(); + + counter.Erased.Should().Be(1, "the retry, once due, ran every participant once"); + (await RequestAsync(SchemaFixture.TenantA, null, erasure)).Status.Should().Be("awaiting_privileged_step"); + (await MembershipAsync(SchemaFixture.TenantA, null, LearnerMembershipA)).Status.Should().Be("Revoked"); + } + + /// + /// A second erasure whose snapshot holds a Membership an earlier erasure already made the tombstone skips it without + /// writing it, and erases the one admitted since. + /// + [Fact] + public async Task A_second_erasure_over_an_already_erased_tombstone_writes_nothing_to_it_and_erases_the_rest() + { + await using var database = await OpenDatabaseAsync(); + await SetStatusAsync(SchemaFixture.TenantA, null, LearnerMembershipA, "Revoked"); + var first = await FileDueErasureAsync(SchemaFixture.TenantA, null, PersonA, [LearnerMembershipA]); + await using var host = Host(); + (await RunAsync(host.Services, await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, null, first))).Committed(); + var tombstone = await RowAsync(SchemaFixture.TenantA, null, LearnerMembershipA); + await CompleteAsOwnerAsync(database, SchemaFixture.TenantA, null, first); + + var current = Guid.CreateVersion7(); + await using (var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, transaction, SchemaFixture.TenantA, null); + await LockAsync(app, transaction, SchemaFixture.TenantA, PersonA, false); + await InsertMemberAsync(app, transaction, SchemaFixture.TenantA, null, current, PersonA, + RoleId(SchemaFixture.TenantA, LearnStack.SharedKernel.Permissions.BuiltInRoleKey.Learner, + LearnStack.SharedKernel.Permissions.PermissionScope.Tenant)); + await transaction.CommitAsync(); + } + + var second = await FileDueErasureAsync(SchemaFixture.TenantA, null, PersonA, [LearnerMembershipA, current]); + (await RunAsync(host.Services, await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, null, second))).Committed(); + + (await RequestAsync(SchemaFixture.TenantA, null, second)).Status.Should().Be("awaiting_privileged_step"); + (await RowAsync(SchemaFixture.TenantA, null, LearnerMembershipA)).Should().Be(tombstone, + "the tombstone is not written again: its version, stamps and status are as the first erasure left them"); + (await MembershipAsync(SchemaFixture.TenantA, null, current)).Should().Be(new MembershipState("Revoked", SystemActor, null, null, "[]", 0)); + (await AuditAsync(SchemaFixture.TenantA, null, "identity.membership.erase", LearnerMembershipA)).Should().Be(1, + "only the first erasure wrote it"); + (await AuditAsync(SchemaFixture.TenantA, null, "identity.membership.erase", current)).Should().Be(1, + "the second erasure's one row names the Membership it changed"); + } + + /// + /// A request whose snapshot names a Membership that is not the subject's in the request's group is not an erasure the + /// service performs: the attempt fails, rolls back, and the Membership is untouched. The request guard refuses to store + /// such a snapshot, so the case is the service's own defence in depth, reached by corrupting the stored snapshot as the + /// owner with the guard paused and restored. + /// + [Fact] + public async Task A_snapshot_membership_that_is_not_the_subjects_in_its_group_fails_the_attempt_and_changes_nothing() + { + await using var database = await OpenDatabaseAsync(); + var logs = new ErasureLogCapture(); + // Person A's branch Membership, named by a request of person A's tenant-wide group. + var erasure = await FileDueErasureAsync(SchemaFixture.TenantA, null, PersonA, [LearnerMembershipA]); + async Task CorruptSnapshotAsync(Guid membership) + { + 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, null); + (await ScalarAsync(owner, transaction, """ + WITH moved AS ( + UPDATE public.data_subject_requests SET membership_snapshot=@snapshot::jsonb WHERE id=@id RETURNING 1) + SELECT count(*) FROM moved + """, ("id", erasure), ("snapshot", Snapshot(membership)))).Should().Be(1); + await ExecuteAsync(owner, transaction, "ALTER TABLE public.data_subject_requests ENABLE TRIGGER tg_data_subject_requests_mutation_guard"); + await transaction.CommitAsync(); + } + + await CorruptSnapshotAsync(BranchMembershipA1); + + await using var host = Host(services => services.AddSingleton(logs)); + + var result = await RunAsync(host.Services, await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, null, erasure)); + + result.CommitAcknowledged.Should().BeFalse(); + result.KnownRollback.Should().BeTrue(); + (await RequestAsync(SchemaFixture.TenantA, null, erasure)).Status.Should().Be("scheduled"); + (await MembershipAsync(SchemaFixture.TenantA, SchemaFixture.OrgA1, BranchMembershipA1)).Status.Should().Be("Active"); + (await MembershipAsync(SchemaFixture.TenantA, null, LearnerMembershipA)).Status.Should().Be("Active"); + logs.Rendered().Should().Contain("attempt failed (\"InvalidOperationException\")", "the service refused, not a database or a participant"); + + // An InvalidOperationException has other sources (the window not ended, the fences, a transition the job's own + // preconditions admitted), so the cause is pinned two ways. The not-due refusal logs its own line, which is absent; + // and the same request, due and fenced exactly as before, with only its snapshot restored to the subject's own + // Membership, runs to the end: nothing but the snapshot made the first attempt fail. + logs.Rendered().Should().NotContain("is not yet due", "the window had ended: the attempt did not fail for being early"); + await CorruptSnapshotAsync(LearnerMembershipA); + + (await RunAsync(host.Services, await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, null, erasure))).Committed(); + + (await RequestAsync(SchemaFixture.TenantA, null, erasure)).Status.Should().Be("awaiting_privileged_step"); + (await MembershipAsync(SchemaFixture.TenantA, null, LearnerMembershipA)).Status.Should().Be("Revoked"); + (await MembershipAsync(SchemaFixture.TenantA, SchemaFixture.OrgA1, BranchMembershipA1)).Status.Should().Be("Active", + "the other group's Membership was never the subject's to erase here"); + } + + /// + /// CHARACTERIZATION of a decision still owed (amendments-owed item 34, ADR-0106 § 3): "an administrator erases only for a + /// Revoked Membership" holds at creation only. An administrator files for a Revoked Membership M1; the person is then + /// admitted again as M2 (Active) inside the 24-hour window; the job runs. Today the request's snapshot names only M1, + /// so M2 is not touched: it stays Active with its profile and assignment. But the withdrawal of exports, artifacts and + /// issued invitations is by subject and group, not by snapshot, so the NEW admission's artifact, pending export and + /// issued invitation are withdrawn, and the request ends awaiting_privileged_step: an erasure the person never + /// asked for takes the data of an admission it was not filed for. If the maintainer adds a closed refusal at execution + /// (blocked_membership_current) or accepts this, this case changes with that decision; an accidental change in + /// either direction fails it. The operator's audit redaction of the group is a separate act and not run here. + /// + [Fact] + public async Task An_administrator_erasure_of_a_revoked_membership_withdraws_what_a_person_admitted_again_in_the_window_owns_and_leaves_the_new_membership_active() + { + await using var database = await OpenDatabaseAsync(); + await SetStatusAsync(SchemaFixture.TenantA, null, LearnerMembershipA, "Revoked"); + var erasure = Guid.CreateVersion7(); + await using (var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, SchemaFixture.TenantA, null, PersonA); + await 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) + VALUES(@id,@tenant,NULL,'erasure','administrator',@subject,@requester,'scheduled',@snapshot::jsonb, + now() + interval '24 hours',now(),@requester) + """, ("id", erasure), ("tenant", SchemaFixture.TenantA), ("subject", PersonA), ("requester", AdminA), + ("snapshot", Snapshot(LearnerMembershipA))); + await transaction.CommitAsync(); + } + + // Inside the window the person is admitted again, with a pending export, an offer they issued and the artifact the + // seeded export left; the snapshot, frozen at filing, does not name the new Membership. + var readmitted = Guid.CreateVersion7(); + await using (var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, transaction, SchemaFixture.TenantA, null); + await LockAsync(app, transaction, SchemaFixture.TenantA, PersonA, false); + await InsertMemberAsync(app, transaction, SchemaFixture.TenantA, null, readmitted, PersonA, + RoleId(SchemaFixture.TenantA, LearnStack.SharedKernel.Permissions.BuiltInRoleKey.Learner, + LearnStack.SharedKernel.Permissions.PermissionScope.Tenant)); + await transaction.CommitAsync(); + } + + var export = await FileAsync(SchemaFixture.TenantA, null, PersonA, [LearnerMembershipA, readmitted], "export"); + var issued = await IssueInvitationAsync(SchemaFixture.TenantA, null, PersonA); + await DataErasureTestKit.BackdateAsync(database.MigrationConnectionString, SchemaFixture.TenantA, null, erasure); + await using var host = Host(); + + (await RunAsync(host.Services, await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, null, erasure))).Committed(); + + (await RequestAsync(SchemaFixture.TenantA, null, erasure)).Status.Should().Be("awaiting_privileged_step"); + (await MembershipAsync(SchemaFixture.TenantA, null, LearnerMembershipA)).Should().Be( + new MembershipState("Revoked", SystemActor, null, null, "[]", 0), "the Membership the request names is erased"); + (await MembershipAsync(SchemaFixture.TenantA, null, readmitted)).Should().Be( + new MembershipState("Active", null, "profile-canary", "en", "[]", 1), + "the new admission is not in the snapshot: it stays Active with its profile and its role"); + (await AuditAsync(SchemaFixture.TenantA, null, "identity.membership.erase", LearnerMembershipA)).Should().Be(1); + (await AuditAsync(SchemaFixture.TenantA, null, "identity.membership.erase", readmitted)).Should().Be(0); + (await ArtifactAsync(SchemaFixture.TenantA, null, TenantWideA.Artifact!.Value)).Should().Be(("revoked", 0L), + "withdrawn by subject and group: the person's artifact is revoked though the person is a current member again"); + (await RequestAsync(SchemaFixture.TenantA, null, export)).Status.Should().Be("cancelled", + "the pending export of the person in the group is cancelled by subject and group"); + (await InvitationAsync(SchemaFixture.TenantA, null, issued)).Status.Should().Be("Revoked", + "the offer the person issued after being admitted again is revoked by subject and group"); + } + + /// + /// Two erasures of two different people of one tenant, run at once through the real job runtime on one host: each takes + /// its subject's User fence and then the tenant key exclusively, in that order, so the second waits for the first and + /// neither deadlocks. The first is held inside its transaction (a participant that waits on a gate) until the second is + /// seen waiting on an advisory lock in pg_locks, so the contention is observed, not hoped for; then both + /// commit within a bounded wait, each erased only its own person's Membership, invitations and request, and neither + /// touched the other's. + /// + [Fact] + public async Task Two_erasures_of_two_people_of_one_tenant_run_at_once_serialize_on_the_tenant_key_and_both_complete() + { + await using var database = await OpenDatabaseAsync(); + var (personC, membershipC) = (Guid.CreateVersion7(), Guid.CreateVersion7()); + await InsertUserAsync(database.AppConnectionString, personC); + await using (var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, transaction, SchemaFixture.TenantA, null); + await LockAsync(app, transaction, SchemaFixture.TenantA, personC, false); + await InsertMemberAsync(app, transaction, SchemaFixture.TenantA, null, membershipC, personC, + RoleId(SchemaFixture.TenantA, LearnStack.SharedKernel.Permissions.BuiltInRoleKey.Learner, + LearnStack.SharedKernel.Permissions.PermissionScope.Tenant), "profile-canary-c"); + await transaction.CommitAsync(); + } + + var (invitationA, invitationC) = (await IssueInvitationAsync(SchemaFixture.TenantA, null, PersonA), + await IssueInvitationAsync(SchemaFixture.TenantA, null, personC)); + var (erasureA, erasureC) = (await FileDueErasureAsync(SchemaFixture.TenantA, null, PersonA, [LearnerMembershipA]), + await FileDueErasureAsync(SchemaFixture.TenantA, null, personC, [membershipC])); + var (jobA, jobC) = (await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, null, erasureA), + await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, null, erasureC)); + var gate = new GatedParticipant(PersonA); + await using var host = Host(services => services.AddSingleton(gate)); + + var first = Task.Run(() => RunAsync(host.Services, jobA)); + await gate.Entered.Task.WaitAsync(TimeSpan.FromSeconds(30)); + var second = Task.Run(() => RunAsync(host.Services, jobC)); + await using (var observer = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString)) + { + var deadline = DateTime.UtcNow.AddSeconds(30); + while (!await ScalarAsync(observer, null, + "SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_locks WHERE locktype = 'advisory' AND NOT granted)")) + { + second.IsCompleted.Should().BeFalse("the second erasure cannot finish while the first holds the tenant key"); + DateTime.UtcNow.Should().BeBefore(deadline, "the second erasure must be seen waiting on the first's tenant key"); + await Task.Delay(TimeSpan.FromMilliseconds(20)); + } + } + + gate.Release.TrySetResult(); + var results = await Task.WhenAll(first, second).WaitAsync(TimeSpan.FromSeconds(60)); + + results[0].Committed("the first erasure commits when released"); + results[1].Committed("the second erasure commits once the first has released the tenant key: no deadlock"); + (await RequestAsync(SchemaFixture.TenantA, null, erasureA)).Status.Should().Be("awaiting_privileged_step"); + (await RequestAsync(SchemaFixture.TenantA, null, erasureC)).Status.Should().Be("awaiting_privileged_step"); + var tombstone = new MembershipState("Revoked", SystemActor, null, null, "[]", 0); + (await MembershipAsync(SchemaFixture.TenantA, null, LearnerMembershipA)).Should().Be(tombstone); + (await MembershipAsync(SchemaFixture.TenantA, null, membershipC)).Should().Be(tombstone); + (await InvitationAsync(SchemaFixture.TenantA, null, invitationA)).Status.Should().Be("Revoked"); + (await InvitationAsync(SchemaFixture.TenantA, null, invitationC)).Status.Should().Be("Revoked"); + (await MembershipAsync(SchemaFixture.TenantA, SchemaFixture.OrgA1, BranchMembershipA1)).Status.Should().Be("Active", + "person A's other groups are not these requests'"); + foreach (var (request, membership) in new[] { (erasureA, LearnerMembershipA), (erasureC, membershipC) }) + { + (await AuditAsync(SchemaFixture.TenantA, null, "identity.data_request.fulfill_erasure", request)).Should().Be(1); + (await AuditAsync(SchemaFixture.TenantA, null, "identity.membership.erase", membership)).Should().Be(1, + "each erasure's audit row names its own person's Membership once"); + } + + JsonDocument.Parse((await RequestAsync(SchemaFixture.TenantA, null, erasureC)).Result).RootElement.GetProperty("request_receipt") + .GetInt64().Should().Be(1, "person C's receipt counts person C's request alone"); + } + + /// + /// ADR-0107 § 5.3: the pending invitations the subject issued are revoked a page at a time until none is left; one more + /// than a page is the case that ends a loop that stops after the first. + /// + [Fact] + public async Task More_pending_invitations_than_one_page_are_all_revoked_by_one_erasure() + { + await using var database = await OpenDatabaseAsync(); + var invitations = await IssueInvitationsAsync(SchemaFixture.TenantA, null, PersonA, 101); + var erasure = await FileDueErasureAsync(SchemaFixture.TenantA, null, PersonA, [LearnerMembershipA]); + await using var host = Host(); + + (await RunAsync(host.Services, await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, null, erasure))).Committed(); + + invitations.Should().HaveCount(101); + (await PendingInvitationsAsync(SchemaFixture.TenantA, null, PersonA)).Should().Be(0, "every page was revoked"); + (await CountRevokedAsync(SchemaFixture.TenantA, null, invitations)).Should().Be(101); + (await AuditCountOperationAsync(SchemaFixture.TenantA, null, "identity.invitation.revoke")).Should().Be(1, + "one row about the first instance; the others travel in its changes"); + } + + /// Moves a scheduled request, whose window has ended, to fulfilling with the given progress recorded. + private async Task StartFulfillingAsync(Guid tenant, Guid? organization, Guid subject, Guid request, string[] recorded) + { + var progress = "{" + string.Join(",", recorded.Select(key => "\"" + key + "\":\"2026-11-21T10:00:00.0000000Z\"")) + "}"; + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, tenant, organization, subject); + await StepAsync(app, transaction, request, "status='fulfilling'"); + if (recorded.Length > 0) await StepAsync(app, transaction, request, "progress='" + progress + "'::jsonb"); + await transaction.CommitAsync(); + } + + /// The operator's completion stood in for by the owner, with the request guard paused and restored. + private static async Task CompleteAsOwnerAsync(DisposableSchemaDatabase database, Guid tenant, Guid? organization, Guid request) + { + 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, tenant, organization); + (await ScalarAsync(owner, transaction, """ + WITH moved AS ( + UPDATE public.data_subject_requests SET status='completed', completed_at=now(), updated_at=now(), row_version=row_version+1 + WHERE id=@id AND status='awaiting_privileged_step' RETURNING 1) + SELECT count(*) FROM moved + """, ("id", request))).Should().Be(1); + await ExecuteAsync(owner, transaction, "ALTER TABLE public.data_subject_requests ENABLE TRIGGER tg_data_subject_requests_mutation_guard"); + await transaction.CommitAsync(); + } + + /// A completed export of the person in the group, written under the canonical fences, with its available artifact. + private async Task SeedArtifactAsync(Guid tenant, Guid? organization, Guid subject, Guid membership) + { + var row = new Row(tenant, organization, subject, membership, Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.CreateVersion7()); + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, tenant, organization, subject); + await InsertRequestAsync(app, transaction, row.Request, tenant, organization, subject, [row.Membership]); + await CompleteExportAsync(app, transaction, row, row.Artifact!.Value, row.Ticket!.Value); + await transaction.CommitAsync(); + return row.Artifact!.Value; + } + + /// Many pending offers the person issued, written in one transaction. + private async Task> IssueInvitationsAsync(Guid tenant, Guid? organization, Guid inviter, int count) + { + var ids = new List(); + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant, organization); + await LockAsync(app, transaction, tenant, null, false); + var role = RoleId(tenant, LearnStack.SharedKernel.Permissions.BuiltInRoleKey.Learner, organization is null + ? LearnStack.SharedKernel.Permissions.PermissionScope.Tenant : LearnStack.SharedKernel.Permissions.PermissionScope.Organization); + for (var index = 0; index < count; index++) + { + var id = Guid.CreateVersion7(); + ids.Add(id); + await ExecuteAsync(app, transaction, """ + INSERT INTO public.invitations(id,tenant_id,organization_id,recipient_email,inviter_user_id,role_id, + pinned_role_version,status,generation_id,generation,generation_created_at,expires_at, + verifier_digest,entry_origin,entry_locale,current_delivery_job_id,submission_status,created_at,created_by) + VALUES(@id,@tenant,@organization,@email,@inviter,@role,0,'Pending',@generation,1,@at, + @at+interval '14 days',@digest,'https://manage.invitation.invalid','en',@job,'Queued',@at,@inviter) + """, ("id", id), ("tenant", tenant), ("organization", organization), ("email", "page-" + id.ToString("N") + "@example.invalid"), + ("inviter", inviter), ("role", role), ("generation", Guid.CreateVersion7()), ("job", Guid.CreateVersion7()), + ("digest", InvitationSchemaSeed.Digest(id)), ("at", DateTimeOffset.UtcNow)); + } + + await transaction.CommitAsync(); + return ids; + } + + private async Task PendingInvitationsAsync(Guid tenant, Guid? organization, Guid inviter) + { + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant, organization); + return await ScalarAsync(app, transaction, + "SELECT count(*) FROM public.invitations WHERE inviter_user_id=@inviter AND status='Pending'", ("inviter", inviter)); + } + + private async Task CountRevokedAsync(Guid tenant, Guid? organization, List invitations) + { + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant, organization); + return await ScalarAsync(app, transaction, + "SELECT count(*) FROM public.invitations WHERE id = ANY(@ids) AND status='Revoked'", ("ids", invitations.ToArray())); + } + + private Task AuditCountOperationAsync(Guid tenant, Guid? organization, string operation) => AuditAsync(tenant, organization, operation, null); + + /// Counts its erasures; its retained report is empty. + private sealed class CountingParticipant(string key) : IUserDataParticipant + { + private int _erased; + + public string Key { get; } = key; + + public int Erased => Volatile.Read(ref _erased); + + public Task ExportAsync(UserDataSubject subject, IUserDataExportWriter writer, CancellationToken cancellationToken) => Task.CompletedTask; + + public Task EraseAsync(UserDataSubject subject, CancellationToken cancellationToken) + { + Interlocked.Increment(ref _erased); + return Task.CompletedTask; + } + + public Task> DescribeRetainedAsync(UserDataSubject subject, + CancellationToken cancellationToken) => Task.FromResult>([]); + } + + private sealed class ErasureLogCapture : ILogEventSink + { + private readonly ConcurrentQueue _entries = new(); + + public void Emit(LogEvent logEvent) => _entries.Enqueue(logEvent); + + public string Rendered() => string.Join('\n', _entries.Select(entry => entry.RenderMessage(CultureInfo.InvariantCulture))); + } + + /// Holds the erasure of one subject inside its transaction until released: the first of two concurrent runs. + private sealed class GatedParticipant(Guid held) : IUserDataParticipant + { + public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public string Key => "probe"; + + public Task ExportAsync(UserDataSubject subject, IUserDataExportWriter writer, CancellationToken cancellationToken) => Task.CompletedTask; + + public async Task EraseAsync(UserDataSubject subject, CancellationToken cancellationToken) + { + if (subject.SubjectUserId != held) + { + return; + } + + Entered.TrySetResult(); + await Release.Task.WaitAsync(TimeSpan.FromSeconds(60), cancellationToken); + } + + public Task> DescribeRetainedAsync(UserDataSubject subject, + CancellationToken cancellationToken) => Task.FromResult>([]); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataErasureExecutionTests.Redaction.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataErasureExecutionTests.Redaction.cs new file mode 100644 index 000000000..dae25fa78 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataErasureExecutionTests.Redaction.cs @@ -0,0 +1,234 @@ +using System.Text.Json.Nodes; +using FluentAssertions; +using LearnStack.SharedKernel.Platform; +using LearnStack.Tests.Fixtures; +using Microsoft.Extensions.DependencyInjection; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class DataErasureExecutionTests +{ + /// + /// ADR-0108 end to end: the erasure job writes its rows through the real capture, then the operator's completion runs + /// the real executor through the real platform scope of the API composition, and no payload column of the tenant's + /// audit log names the person or one of the request's Memberships any more, except the own key of a User or a + /// Membership row, which is that row's entity_id. The second case is a person admitted again after an earlier + /// Membership was revoked, whose erasure records two Memberships and two invitations on one row each. + /// + [Theory] + [InlineData("one_membership")] + [InlineData("readmitted")] + public async Task The_erasure_and_its_privileged_step_leave_no_identifier_of_the_person_in_any_audit_payload(string variant) + { + await using var database = await OpenDatabaseAsync(); + Guid[] memberships = [LearnerMembershipA]; + if (variant == "readmitted") + { + await SetStatusAsync(SchemaFixture.TenantA, null, LearnerMembershipA, "Revoked"); + var current = Guid.CreateVersion7(); + await using (var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, transaction, SchemaFixture.TenantA, null); + await LockAsync(app, transaction, SchemaFixture.TenantA, PersonA, false); + await InsertMemberAsync(app, transaction, SchemaFixture.TenantA, null, current, PersonA, + RoleId(SchemaFixture.TenantA, LearnStack.SharedKernel.Permissions.BuiltInRoleKey.Learner, + LearnStack.SharedKernel.Permissions.PermissionScope.Tenant)); + await transaction.CommitAsync(); + } + + memberships = [LearnerMembershipA, current]; + await IssueInvitationAsync(SchemaFixture.TenantA, null, PersonA); + } + + await IssueInvitationAsync(SchemaFixture.TenantA, null, PersonA); + await FileAsync(SchemaFixture.TenantA, null, PersonA, memberships, "export"); + var erasure = await FileDueErasureAsync(SchemaFixture.TenantA, null, PersonA, memberships); + await using var host = Host(platform: true); + (await RunAsync(host.Services, await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, null, erasure))) + .Committed(); + (await RequestAsync(SchemaFixture.TenantA, null, erasure)).Status.Should().Be("awaiting_privileged_step"); + // The identifiers, and the personal content the erasure removed: the profile's display name, which the payloads must + // not carry either, and the e-mail of an invitation the person issued. + string[] identifiers = [PersonA.ToString("D"), .. memberships.Select(membership => membership.ToString("D")), + "profile-canary", "@example.invalid"]; + + // The job's rows came from the capture and name the person: the proof below is not vacuous. + var named = await IdentifiersInPayloadsAsync(_database!.PlatformConnectionString, SchemaFixture.TenantA, identifiers); + named.Select(occurrence => occurrence.EntityType).Distinct().Should() + .Contain(["Membership", "Invitation", "DataSubjectRequest", "DataExportArtifact"]); + + // A row the person acted in, with every attributed scalar column set: the proof that those columns are cleared is + // not vacuous either, as the job's own rows carry no address or agent. + var attributed = Guid.CreateVersion7(); + await using (var platform = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.PlatformConnectionString)) + await using (var insert = new NpgsqlCommand(""" + INSERT INTO public.audit_log (id, "timestamp", tenant_id, organization_id, actor_user_id, actor_email, module, operation, + operation_type, operation_class, entity_type, entity_id, outcome, correlation_id, ip_address, user_agent) + VALUES (@id, clock_timestamp(), @tenant, NULL, @actor, 'person@example.test', 'e2e', 'e2e.redaction.row', 'Update', 'Must', + 'Course', @entity, 'success', @correlation, '198.51.100.7'::inet, 'E2E/1.0') + """, platform)) + { + insert.Parameters.AddWithValue("id", attributed); + insert.Parameters.AddWithValue("tenant", SchemaFixture.TenantA); + insert.Parameters.AddWithValue("actor", PersonA); + insert.Parameters.AddWithValue("entity", Guid.CreateVersion7().ToString("D")); + insert.Parameters.AddWithValue("correlation", "00-" + attributed.ToString("N") + "-01"); + await insert.ExecuteNonQueryAsync(); + } + + await using (var scope = host.Services.CreateAsyncScope()) + { + var result = await scope.ServiceProvider.GetRequiredService().CompleteErasureAsync( + TestPlatformAdmissions.Admission(PlatformOperations.ErasureComplete, "INC-E2E-1", + correlationId: "00-erasure-e2e-" + Guid.NewGuid().ToString("N")), erasure); + result.Outcome.Should().Be(ErasureCompletionOutcome.Completed); + result.Report!.RowsSelected.Should().BeGreaterThan(0); + } + + // Every survivor at once, one a line, so a failure names each undeclared reference rather than the first. + string.Join(Environment.NewLine, await IdentifiersInPayloadsAsync(_database!.PlatformConnectionString, SchemaFixture.TenantA, identifiers)).Should() + .BeEmpty("no payload names the person or a request Membership after the privileged step, except own keys"); + + // The scalar columns of every row that named the person, and of the row the person acted in, are cleared. + var rows = named.Select(occurrence => occurrence.Row).Append(attributed).Distinct().ToArray(); + await using var reader = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.PlatformConnectionString); + await using var survivors = new NpgsqlCommand(""" + SELECT count(*) FILTER (WHERE actor_email IS NOT NULL), count(*) FILTER (WHERE ip_address IS NOT NULL), + count(*) FILTER (WHERE user_agent IS NOT NULL), count(*) + FROM public.audit_log WHERE tenant_id = @tenant AND id = ANY(@rows) + """, reader); + survivors.Parameters.AddWithValue("tenant", SchemaFixture.TenantA); + survivors.Parameters.AddWithValue("rows", rows); + await using var counts = await survivors.ExecuteReaderAsync(); + (await counts.ReadAsync()).Should().BeTrue(); + (counts.GetInt64(0), counts.GetInt64(1), counts.GetInt64(2)).Should().Be((0, 0, 0), + "no e-mail, address or agent survives on a row that named the person"); + counts.GetInt64(3).Should().Be(rows.Length, "every row the proof names is still there: redaction rewrites rows, it deletes none"); + } + + private static readonly string[] Sides = ["before", "after"]; + + /// Where an identifier occurs in one audit row's payload. + internal sealed record PayloadOccurrence(Guid Row, string EntityType, string EntityId, string Column, string Pointer, string Text) + { + public override string ToString() => $"{EntityType} {EntityId} {Column}{Pointer}: {Text}"; + } + + /// + /// Every occurrence, case-insensitive and as a substring, of the identifiers in the tenant's before_state, + /// after_state and changes, in values, object keys and changes paths, read as the platform role; + /// the retained keys of a User or a Membership (a row's own Id state, and the instance segment of every + /// User or Membership changes path with that instance's Id item) are left out. The closure's end-to-end + /// proof asks it of every participant tenant and of the platform sentinel tenant. + /// + internal static async Task> IdentifiersInPayloadsAsync(string platformConnectionString, Guid tenant, string[] identifiers) + { + await using var platform = (NpgsqlConnection)await PostgresFixture.OpenAsync(platformConnectionString); + await using var command = new NpgsqlCommand(""" + SELECT id, entity_type, COALESCE(entity_id, ''), before_state::text, after_state::text, changes::text + FROM public.audit_log WHERE tenant_id = @tenant + """, platform); + command.Parameters.AddWithValue("tenant", tenant); + var found = new List(); + await using var reader = await command.ExecuteReaderAsync(); + while (await reader.ReadAsync()) + { + var (row, type, entity) = (reader.GetGuid(0), reader.IsDBNull(1) ? string.Empty : reader.GetString(1), reader.GetString(2)); + var ownKey = type is "User" or "Membership" ? entity : null; + foreach (var (ordinal, column) in new[] { (3, "before_state"), (4, "after_state"), (5, "changes") }) + { + if (reader.IsDBNull(ordinal)) + { + continue; + } + + var occurrences = new List<(string Pointer, string Text)>(); + Walk(WithoutOwnKey(JsonNode.Parse(reader.GetString(ordinal)), type, ownKey), string.Empty, identifiers, occurrences); + found.AddRange(occurrences.Select(occurrence => + new PayloadOccurrence(row, type, entity, column, occurrence.Pointer, occurrence.Text))); + } + } + + return found; + } + + private static void Walk(JsonNode? node, string pointer, string[] identifiers, List<(string Pointer, string Text)> found) + { + bool Names(string text) => identifiers.Any(identifier => text.Contains(identifier, StringComparison.OrdinalIgnoreCase)); + switch (node) + { + case JsonObject members: + foreach (var (key, value) in members) + { + if (Names(key)) + { + found.Add((pointer + "/" + key, "(key)")); + } + + Walk(value, pointer + "/" + key, identifiers, found); + } + + break; + case JsonArray items: + for (var index = 0; index < items.Count; index++) + { + Walk(items[index], pointer + "/" + index, identifiers, found); + } + + break; + case JsonValue value when value.TryGetValue(out var text) && Names(text): + found.Add((pointer, text)); + break; + } + } + + /// + /// The payload without the retained keys, which ADR-0108 § 6 keeps because a row's entity_id shows them: a + /// User's or Membership's top-level Id where it is exactly the row's entity_id, and in changes + /// the instance segment of every User or Membership path with the before and after of that instance's Id item. + /// A row that carries a second Membership of the person (the person was admitted again) names it only by that + /// segment; it is the same pseudonymous key, retained the same way. Everything else is walked. + /// + private static JsonNode? WithoutOwnKey(JsonNode? node, string type, string? ownKey) + { + bool Own(JsonNode? value) => ownKey is not null && value is JsonValue text && text.TryGetValue(out var spelled) + && string.Equals(spelled, ownKey, StringComparison.OrdinalIgnoreCase); + switch (node) + { + case JsonObject state when Own(state["Id"]): + state.Remove("Id"); + break; + case JsonArray items: + foreach (var item in items.OfType()) + { + if (item["path"] is not JsonValue path || !path.TryGetValue(out var spelled) + || InstanceSegment().Match(spelled) is not { Success: true } match) + { + continue; + } + + var (entity, instance, property) = (match.Groups["type"].Value, match.Groups["instance"].Value, match.Groups["rest"].Value); + item["path"] = "/" + entity + "/" + property; + if (property == "Id") + { + foreach (var side in Sides.Where(side => item[side] is JsonValue value && value.TryGetValue(out var spelledValue) + && string.Equals(spelledValue, instance, StringComparison.OrdinalIgnoreCase))) + { + item.Remove(side); + } + } + } + + break; + } + + return node; + } + + [System.Text.RegularExpressions.GeneratedRegex("^/(?User|Membership)/(?[0-9a-fA-F-]{36})/(?.*)$")] + private static partial System.Text.RegularExpressions.Regex InstanceSegment(); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataErasureExecutionTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataErasureExecutionTests.cs new file mode 100644 index 000000000..11423efd4 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataErasureExecutionTests.cs @@ -0,0 +1,671 @@ +using System.Text.Json; +using FluentAssertions; +using LearnStack.Application.Jobs; +using LearnStack.Application.Messaging; +using LearnStack.Infrastructure.Jobs; +using LearnStack.Infrastructure.Persistence; +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.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 Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.DataRequestSchemaSeed; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// ADR-0107 § 5 through the actual job runtime and the actual composition root, as learnstack_app on the job's own +/// tenant transaction: a due erasure revokes the subject's exports, erases the Memberships of its snapshot and revokes the +/// invitations the subject issued, in exactly its group, and waits for the operator's privileged step; a hold, a sole +/// administrator, a cancellation, an early run and a dead job each end it as ADR-0106 § 7 and § 8 say. Each case owns a +/// disposable copy of the seeded schema (two tenants; person A in tenant A's tenant-wide group and two branches). +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed partial class DataErasureExecutionTests(SchemaFixture fixture) +{ + private static readonly string[] Participants = ["audit", "customization", "education", "identity", "tenancy"]; + private DisposableSchemaDatabase? _database; + + [Theory] + [InlineData("tenant")] + [InlineData("organization")] + public async Task A_due_erasure_erases_exactly_the_subjects_group_and_waits_for_the_privileged_step(string scope) + { + await using var database = await OpenDatabaseAsync(); + var (organization, membership, artifact, otherOffer) = scope == "tenant" + ? ((Guid?)null, LearnerMembershipA, TenantWideA.Artifact!.Value, InvitationSchemaSeed.TenantOfferA) + : (SchemaFixture.OrgA1, BranchMembershipA1, BranchA1.Artifact!.Value, InvitationSchemaSeed.BranchOfferA1); + var issued = await IssueInvitationAsync(SchemaFixture.TenantA, organization, PersonA); + var export = await FileAsync(SchemaFixture.TenantA, organization, PersonA, [membership], "export"); + var erasure = await FileDueErasureAsync(SchemaFixture.TenantA, organization, PersonA, [membership]); + await using var host = Host(); + + (await RunAsync(host.Services, await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, organization, erasure))) + .Committed(); + + var state = await RequestAsync(SchemaFixture.TenantA, organization, erasure); + state.Status.Should().Be("awaiting_privileged_step"); + JsonDocument.Parse(state.Progress).RootElement.EnumerateObject().Select(entry => entry.Name).Should().BeEquivalentTo(Participants); + JsonDocument.Parse(state.Result).RootElement.EnumerateObject().Select(entry => entry.Name).Should() + .Contain(["request_receipt", "invitation_record", "attribution_reference", "consent_evidence", "audit_actor_reference"]) + .And.NotContain("invitation_envelope", "a kind no participant can count is absent, never zero"); + + var erased = await MembershipAsync(SchemaFixture.TenantA, organization, membership); + erased.Should().Be(new MembershipState("Revoked", SystemActor, null, null, "[]", 0)); + foreach (var (other, group) in new[] { (LearnerMembershipA, (Guid?)null), (BranchMembershipA1, SchemaFixture.OrgA1), + (BranchMembershipA2, SchemaFixture.OrgA2) }.Where(item => item.Item1 != membership)) + (await MembershipAsync(SchemaFixture.TenantA, group, other)).Should().Be(new MembershipState("Active", null, "profile-canary", + "en", "[]", 1), "the same person's Membership of another group is not this request's"); + (await MembershipAsync(SchemaFixture.TenantB, SchemaFixture.OrgB1, BranchMembershipB)).Status.Should().Be("Active"); + + (await RequestAsync(SchemaFixture.TenantA, organization, export)).Status.Should().Be("cancelled", + "an export not yet stored is cancelled, so its job discards anything it built"); + (await ArtifactAsync(SchemaFixture.TenantA, organization, artifact)).Should().Be(("revoked", 0L)); + (await InvitationAsync(SchemaFixture.TenantA, organization, issued)).Should().Be(("Revoked", PersonA), + "the person issued it; the aggregate's actor is the person, the audit actor the job"); + (await InvitationAsync(SchemaFixture.TenantA, organization, otherOffer)).Status.Should().Be("Pending", + "another person's offer is not the subject's to erase"); + (await UserStatusAsync(PersonA)).Should().Be("Active", "tenant erasure never touches users"); + + (await AuditAsync(SchemaFixture.TenantA, organization, "identity.data_request.fulfill_erasure", erasure)).Should().Be(1); + (await AuditAsync(SchemaFixture.TenantA, organization, "identity.membership.erase", membership)).Should().Be(1); + (await AuditAsync(SchemaFixture.TenantA, organization, "identity.invitation.revoke", issued)).Should().Be(1); + (await AuditAsync(SchemaFixture.TenantA, organization, "identity.data_export.revoke", artifact)).Should().Be(1); + + // Repeating the job is a recorded no-op. + (await RunAsync(host.Services, await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, organization, erasure))) + .Committed(); + (await RequestAsync(SchemaFixture.TenantA, organization, erasure)).Should().Be(state); + (await AuditAsync(SchemaFixture.TenantA, organization, "identity.data_request.fulfill_erasure", null)).Should().Be(2); + } + + /// + /// A Suspended Membership is erased to the tombstone by the same path; an earlier-revoked one loses its profile and + /// assignments through the guard's witnessed exception while its own row, which admits no UPDATE, keeps its stamps. + /// + [Theory] + [InlineData("Suspended")] + [InlineData("Revoked")] + public async Task A_suspended_or_earlier_revoked_membership_is_erased_and_a_revoked_row_is_never_updated(string status) + { + await using var database = await OpenDatabaseAsync(); + await SetStatusAsync(SchemaFixture.TenantA, SchemaFixture.OrgA2, BranchMembershipA2, status); + var before = await RowAsync(SchemaFixture.TenantA, SchemaFixture.OrgA2, BranchMembershipA2); + var erasure = await FileDueErasureAsync(SchemaFixture.TenantA, SchemaFixture.OrgA2, PersonA, [BranchMembershipA2]); + await using var host = Host(); + + (await RunAsync(host.Services, await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, SchemaFixture.OrgA2, erasure))) + .Committed(); + + (await RequestAsync(SchemaFixture.TenantA, SchemaFixture.OrgA2, erasure)).Status.Should().Be("awaiting_privileged_step"); + var erased = await MembershipAsync(SchemaFixture.TenantA, SchemaFixture.OrgA2, BranchMembershipA2); + (erased.Status, erased.DisplayName, erased.Locale, erased.CustomFields, erased.Assignments) + .Should().Be(("Revoked", (string?)null, (string?)null, "[]", 0L)); + var after = await RowAsync(SchemaFixture.TenantA, SchemaFixture.OrgA2, BranchMembershipA2); + if (status == "Revoked") + after.Should().Be(before, "the tombstone's own row is not written; its erasure is on the audit row"); + else + after.Version.Should().BeGreaterThan(before.Version); + } + + /// + /// ADR-0044 Amendment 6: a request about one instance writes one row. The erasure changes two Memberships of one person + /// (the earlier tombstone and the current row admitted after it) and two invitations the person issued, so each row + /// names the first instance it changed and carries the other in its changes; without the designation the composer + /// refuses the pair and the whole erasure rolls back. + /// + [Fact] + public async Task Several_instances_of_one_type_are_recorded_on_one_row_about_the_first() + { + await using var database = await OpenDatabaseAsync(); + await SetStatusAsync(SchemaFixture.TenantA, null, LearnerMembershipA, "Revoked"); + var current = Guid.CreateVersion7(); + await using (var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, transaction, SchemaFixture.TenantA, null); + await LockAsync(app, transaction, SchemaFixture.TenantA, PersonA, false); + await InsertMemberAsync(app, transaction, SchemaFixture.TenantA, null, current, PersonA, + RoleId(SchemaFixture.TenantA, LearnStack.SharedKernel.Permissions.BuiltInRoleKey.Learner, + LearnStack.SharedKernel.Permissions.PermissionScope.Tenant)); + await transaction.CommitAsync(); + } + + var invitations = new[] { await IssueInvitationAsync(SchemaFixture.TenantA, null, PersonA), + await IssueInvitationAsync(SchemaFixture.TenantA, null, PersonA) }.Order().ToArray(); + var erasure = await FileDueErasureAsync(SchemaFixture.TenantA, null, PersonA, [LearnerMembershipA, current]); + await using var host = Host(); + + (await RunAsync(host.Services, await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, null, erasure))) + .Committed(); + + foreach (var membership in new[] { LearnerMembershipA, current }) + (await MembershipAsync(SchemaFixture.TenantA, null, membership)).Should().Be(new MembershipState("Revoked", + SystemActor, null, null, "[]", 0)); + foreach (var invitation in invitations) + (await InvitationAsync(SchemaFixture.TenantA, null, invitation)).Status.Should().Be("Revoked"); + (await AuditChangesAsync(SchemaFixture.TenantA, "identity.membership.erase", LearnerMembershipA)) + .Should().Contain(current.ToString("D"), "the second Membership travels in the first one's row"); + (await AuditAsync(SchemaFixture.TenantA, null, "identity.membership.erase", current)).Should().Be(0); + (await AuditChangesAsync(SchemaFixture.TenantA, "identity.invitation.revoke", invitations[0])) + .Should().Contain(invitations[1].ToString("D"), "the second invitation travels in the first one's row"); + (await AuditAsync(SchemaFixture.TenantA, null, "identity.invitation.revoke", invitations[1])).Should().Be(0); + } + + [Theory] + [InlineData("sole_administrator")] + [InlineData("hold")] + public async Task A_sole_administrator_or_a_hold_ends_the_erasure_blocked_at_execution_and_nothing_is_erased(string variant) + { + await using var database = await OpenDatabaseAsync(); + var (subject, membership) = variant == "hold" ? (PersonA, LearnerMembershipA) : (AdminA, AdminMembershipA); + // Filed as if creation had passed: the re-check at execution is what decides (ADR-0106 § 7). + var erasure = await FileDueErasureAsync(SchemaFixture.TenantA, null, subject, [membership]); + await using var host = Host(variant == "hold" ? services => services.AddSingleton(new FixedHold()) : null); + + (await RunAsync(host.Services, await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, null, erasure))) + .Committed("the refusal is the committed business outcome"); + + var state = await RequestAsync(SchemaFixture.TenantA, null, erasure); + state.Status.Should().Be("blocked"); + state.Refusal.Should().Be(variant == "hold" ? "blocked_hold" : "blocked_last_administrator"); + (await MembershipAsync(SchemaFixture.TenantA, null, membership)).Status.Should().Be("Active"); + (await MembershipAsync(SchemaFixture.TenantA, null, membership)).DisplayName.Should().Be("profile-canary"); + (await ArtifactAsync(SchemaFixture.TenantA, null, TenantWideA.Artifact!.Value)).Status.Should().Be("available"); + (await AuditAsync(SchemaFixture.TenantA, null, "identity.data_request.fulfill_erasure", erasure)).Should().Be(1); + } + + /// + /// The runtime has no cancel call: a cancelled erasure's job is a recorded no-op. A run that wakes before the window ends + /// fails its attempt for the runtime's retry and changes nothing. + /// + [Theory] + [InlineData("cancelled")] + [InlineData("not_due")] + public async Task A_cancelled_or_not_yet_due_erasure_changes_nothing(string variant) + { + await using var database = await OpenDatabaseAsync(); + var erasure = await FileAsync(SchemaFixture.TenantA, null, PersonA, [LearnerMembershipA], "erasure"); + if (variant == "cancelled") + { + await using var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, SchemaFixture.TenantA, null, null); + await StepAsync(app, transaction, erasure, "status='cancelled'"); + await transaction.CommitAsync(); + } + + var logs = new ErasureLogCapture(); + await using var host = Host(services => services.AddSingleton(logs)); + + var result = await RunAsync(host.Services, await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, null, erasure)); + + result.CommitAcknowledged.Should().Be(variant == "cancelled"); + if (variant == "not_due") + { + result.KnownRollback.Should().BeTrue(); + logs.Rendered().Should().Contain("is not yet due", "the failure is the early run, not any other fault"); + } + else + { + logs.Rendered().Should().NotContain("attempt failed", "a cancelled erasure is a recorded no-op, not a failure"); + } + + (await RequestAsync(SchemaFixture.TenantA, null, erasure)).Status.Should().Be(variant == "cancelled" ? "cancelled" : "scheduled"); + (await MembershipAsync(SchemaFixture.TenantA, null, LearnerMembershipA)).Status.Should().Be("Active"); + (await ArtifactAsync(SchemaFixture.TenantA, null, TenantWideA.Artifact!.Value)).Status.Should().Be("available"); + } + + /// + /// ADR-0107 § 5 is silent on the tenant's lifecycle; the job runtime runs a transactional job of a tenant that does not + /// allow ordinary work like any other, so a due erasure of a Suspended tenant erases and waits for the privileged step. + /// + [Fact] + public async Task A_due_erasure_of_a_suspended_tenant_runs_as_the_runtime_runs_every_transactional_job() + { + await using var database = await OpenDatabaseAsync(); + var erasure = await FileDueErasureAsync(SchemaFixture.TenantA, SchemaFixture.OrgA1, PersonA, [BranchMembershipA1]); + await using (var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await EducationSchemaSeed.AnnounceAsync(app, transaction, SchemaFixture.TenantA, null); + await TenancyLifecycleFixture.LockAsync(app, transaction, SchemaFixture.TenantA); + await ExecuteAsync(app, transaction, "UPDATE tenants SET status='Suspended' WHERE id=@tenant", ("tenant", SchemaFixture.TenantA)); + await transaction.CommitAsync(); + } + + await using var host = Host(); + + (await RunAsync(host.Services, await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, SchemaFixture.OrgA1, erasure))) + .Committed(); + + (await RequestAsync(SchemaFixture.TenantA, SchemaFixture.OrgA1, erasure)).Status.Should().Be("awaiting_privileged_step"); + (await MembershipAsync(SchemaFixture.TenantA, SchemaFixture.OrgA1, BranchMembershipA1)).Status.Should().Be("Revoked"); + } + + /// + /// The lifecycle ADR-0107 § 5 is silent on, beyond Suspended: an Archived tenant is one that "does not allow ordinary + /// work" like a Suspended one, and the runtime claims a transactional job of such a tenant like any other, so the due + /// erasure of an Archived tenant runs: it erases and waits for the privileged step. This pins what is true today; + /// were a tenant lifecycle rule to stop jobs of an Archived tenant, this case is where it would show. + /// + [Fact] + public async Task A_due_erasure_of_an_archived_tenant_runs_and_waits_for_the_privileged_step_as_a_suspended_tenants_does() + { + await using var database = await OpenDatabaseAsync(); + var erasure = await FileDueErasureAsync(SchemaFixture.TenantA, SchemaFixture.OrgA1, PersonA, [BranchMembershipA1]); + await using (var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await EducationSchemaSeed.AnnounceAsync(app, transaction, SchemaFixture.TenantA, null); + await TenancyLifecycleFixture.LockAsync(app, transaction, SchemaFixture.TenantA); + await ExecuteAsync(app, transaction, "UPDATE tenants SET status='Archived' WHERE id=@tenant", ("tenant", SchemaFixture.TenantA)); + await transaction.CommitAsync(); + } + + await using var host = Host(); + + (await RunAsync(host.Services, await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, SchemaFixture.OrgA1, erasure))) + .Committed(); + + (await RequestAsync(SchemaFixture.TenantA, SchemaFixture.OrgA1, erasure)).Status.Should().Be("awaiting_privileged_step"); + (await MembershipAsync(SchemaFixture.TenantA, SchemaFixture.OrgA1, BranchMembershipA1)).Status.Should().Be("Revoked"); + (await MembershipAsync(SchemaFixture.TenantA, null, LearnerMembershipA)).Status.Should().Be("Active", + "only the request's own group is erased"); + } + + /// + /// ADR-0107 § 5.1: an export filed before the erasure is cancelled by it; its job, running after, reads its own request + /// cancelled under its fence and discards the bundle it built, so no artifact is stored over the erasure. + /// + [Fact] + public async Task An_export_filed_before_the_erasure_is_discarded_by_its_own_job_after_the_erasure() + { + await using var database = await OpenDatabaseAsync(); + var export = await FileAsync(SchemaFixture.TenantA, SchemaFixture.OrgA2, PersonA, [BranchMembershipA2], "export"); + var exportJob = await BackgroundJobRuntimeRows.InsertAsync(database.AppConnectionString, "identity.data_export_organization.v1", + organization: SchemaFixture.OrgA2, tenant: SchemaFixture.TenantA, parameters: BackgroundJobPayloadContract.Serialize( + new DataExportJobParameters(export), typeof(DataExportJobParameters), BackgroundJobPayloadKind.Parameters)); + var erasure = await FileDueErasureAsync(SchemaFixture.TenantA, SchemaFixture.OrgA2, PersonA, [BranchMembershipA2]); + await using var host = Host(); + + (await RunAsync(host.Services, await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, SchemaFixture.OrgA2, erasure))) + .Committed(); + (await RunAsync(host.Services, exportJob)).Committed(); + + (await RequestAsync(SchemaFixture.TenantA, SchemaFixture.OrgA2, export)).Status.Should().Be("cancelled"); + await using var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA, SchemaFixture.OrgA2); + (await ScalarAsync(app, transaction, "SELECT count(*) FROM public.data_export_artifacts WHERE request_id=@request", + ("request", export))).Should().Be(0, "the export's bundle is discarded"); + } + + /// + /// One transaction per attempt: a participant failing after the Identity participant erased rolls every write back, and + /// the runtime's retry erases once and records every participant, the failing one included. + /// + [Fact] + public async Task A_failed_attempt_rolls_every_erasure_write_back_and_the_retry_completes_once() + { + await using var database = await OpenDatabaseAsync(); + var erasure = await FileDueErasureAsync(SchemaFixture.TenantA, null, PersonA, [LearnerMembershipA]); + await using var host = Host(services => services.AddSingleton(new FailingParticipant())); + + var failed = await RunAsync(host.Services, await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, null, erasure)); + + failed.CommitAcknowledged.Should().BeFalse(); + failed.KnownRollback.Should().BeTrue(); + (await RequestAsync(SchemaFixture.TenantA, null, erasure)).Status.Should().Be("scheduled"); + (await MembershipAsync(SchemaFixture.TenantA, null, LearnerMembershipA)).Status.Should().Be("Active", + "the Identity participant's erasure rolled back with the attempt"); + (await ArtifactAsync(SchemaFixture.TenantA, null, TenantWideA.Artifact!.Value)).Status.Should().Be("available"); + + (await RunAsync(host.Services, await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, null, erasure))) + .Committed(); + var state = await RequestAsync(SchemaFixture.TenantA, null, erasure); + state.Status.Should().Be("awaiting_privileged_step"); + JsonDocument.Parse(state.Progress).RootElement.EnumerateObject().Select(entry => entry.Name).Should() + .BeEquivalentTo(Participants.Append("probe")); + (await MembershipAsync(SchemaFixture.TenantA, null, LearnerMembershipA)).Status.Should().Be("Revoked"); + (await AuditAsync(SchemaFixture.TenantA, null, "identity.membership.erase", LearnerMembershipA)).Should().Be(1, + "the rolled-back attempt left no row of a change that did not commit"); + } + + /// + /// ADR-0106 § 8: a scheduled erasure whose job is dead reads failed, and the reconciler stores it failed with + /// execution_failed once its window has ended, which frees the slot; before then it cannot start, so it stays. + /// + [Fact] + public async Task A_dead_erasure_job_is_stored_failed_once_its_window_has_ended() + { + await using var database = await OpenDatabaseAsync(); + var due = await FileDueErasureAsync(SchemaFixture.TenantA, null, PersonA, [LearnerMembershipA]); + var early = await FileAsync(SchemaFixture.TenantA, SchemaFixture.OrgA1, PersonA, [BranchMembershipA1], "erasure"); + foreach (var (organization, request) in new[] { ((Guid?)null, due), (SchemaFixture.OrgA1, early) }) + { + var job = await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, organization, request); + 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)); + } + + foreach (var (organization, request, stored) in new[] { ((Guid?)null, due, true), (SchemaFixture.OrgA1, early, false) }) + { + await using var scope = await DataExportTestKit.OpenAsync(database.AppConnectionString, SchemaFixture.TenantA, organization); + var store = new DataRequestStore(scope.Db, scope.Unit, new ProducerExecution(scope.Unit), scope.Context); + var phases = new DataRequestJobPhaseReader(scope.Unit, scope.Context); + var reconciler = new DataRequestFailureReconciler(store, phases, new IdentityMutationLocks(scope.Unit), scope.Context, + new SystemClock()); + var loaded = (await store.FindLockedAsync(DataSubjectRequestId.From(request), CancellationToken.None))!; + var phase = await phases.ReadAsync(loaded.Id, loaded.Kind, CancellationToken.None); + phase.Should().Be(DataRequestJobPhase.Dead); + DataRequestFailureReconciler.EffectiveStatus(loaded, phase).Should().Be(DataRequestStatus.Failed); + (await reconciler.ReconcileAsync(loaded, CancellationToken.None)).Should().Be(stored); + await scope.Frame.CompleteAsync(); + } + + var failed = await RequestAsync(SchemaFixture.TenantA, null, due); + (failed.Status, failed.Failure).Should().Be(("failed", "execution_failed")); + (await RequestAsync(SchemaFixture.TenantA, SchemaFixture.OrgA1, early)).Status.Should().Be("scheduled"); + var next = await FileAsync(SchemaFixture.TenantA, null, PersonA, [LearnerMembershipA], "erasure"); + (await RequestAsync(SchemaFixture.TenantA, null, next)).Status.Should().Be("scheduled", "the stored failure freed the slot"); + } + + /// + /// ADR-0106 § 8 for a due erasure in each phase of its job: only a dead job stores failed, and only a dead job's + /// receipt reads it. A job still queued or retrying after the window (Pending), a request no job is visible for + /// (Unavailable) and a job that ran to completion (Completed, whose request now waits for the operator) are each left + /// exactly as stored, read as stored, and still hold the group's one active slot; a dead one is stored + /// failed with execution_failed, reads failed before and after, and frees the slot. + /// + [Theory] + [InlineData("pending", DataRequestJobPhase.Pending, "scheduled", false)] + [InlineData("unavailable", DataRequestJobPhase.Unavailable, "scheduled", false)] + [InlineData("completed", DataRequestJobPhase.Completed, "awaiting_privileged_step", false)] + [InlineData("dead", DataRequestJobPhase.Dead, "scheduled", true)] + public async Task The_reconciler_stores_failed_for_a_due_erasure_only_when_its_job_is_dead(string variant, DataRequestJobPhase expected, + string stored, bool dead) + { + await using var database = await OpenDatabaseAsync(); + var request = await FileDueErasureAsync(SchemaFixture.TenantA, null, PersonA, [LearnerMembershipA]); + if (variant != "unavailable") + { + var job = await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, null, request); + if (variant == "dead") + { + 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)); + } + else if (variant == "completed") + { + await using var host = Host(); + (await RunAsync(host.Services, job)).Committed(); + } + } + + (await RequestAsync(SchemaFixture.TenantA, null, request)).Status.Should().Be(stored, "as filed, or as the finished job left it"); + DataRequestStatus effective; + await using (var scope = await DataExportTestKit.OpenAsync(database.AppConnectionString, SchemaFixture.TenantA, null)) + { + var store = new DataRequestStore(scope.Db, scope.Unit, new ProducerExecution(scope.Unit), scope.Context); + var phases = new DataRequestJobPhaseReader(scope.Unit, scope.Context); + var reconciler = new DataRequestFailureReconciler(store, phases, new IdentityMutationLocks(scope.Unit), scope.Context, + new SystemClock()); + var loaded = (await store.FindLockedAsync(DataSubjectRequestId.From(request), CancellationToken.None))!; + var phase = await phases.ReadAsync(loaded.Id, loaded.Kind, CancellationToken.None); + phase.Should().Be(expected); + (await phases.ReadManyAsync([loaded.Id], loaded.Kind, CancellationToken.None))[loaded.Id].Should().Be(expected, + "the page read answers as the single read does"); + effective = DataRequestFailureReconciler.EffectiveStatus(loaded, phase); + effective.Should().Be(dead ? DataRequestStatus.Failed : DataRequestCodes.Statuses.Parse(stored), + "the receipt reads failed only for a dead job, before anything is stored"); + (await reconciler.ReconcileAsync(loaded, CancellationToken.None)).Should().Be(dead); + await scope.Frame.CompleteAsync(); + } + + var state = await RequestAsync(SchemaFixture.TenantA, null, request); + (state.Status, state.Failure).Should().Be(dead ? ("failed", "execution_failed") : (stored, null)); + var refile = () => FileAsync(SchemaFixture.TenantA, null, PersonA, [LearnerMembershipA], "erasure"); + if (dead) + (await RequestAsync(SchemaFixture.TenantA, null, await refile())).Status.Should().Be("scheduled", "the stored failure freed the slot"); + else + (await refile.Should().ThrowAsync()).Which.ConstraintName.Should().Be("ux_data_subject_requests_active", + "a request that is not stored failed still holds the group's one active slot"); + } + + private async Task OpenDatabaseAsync() => + _database = await DataExportTestKit.CreateSeededDatabaseAsync(fixture.Postgres); + + private WebApplicationFactory Host(Action? configure = null, bool platform = false) => + new ConstructionOnlyApiFactory().WithWebHostBuilder(builder => + { + builder.UseEnvironment(Environments.Development); + builder.UseSetting("ConnectionStrings:Default", _database!.AppConnectionString); + builder.UseSetting("ConnectionStrings:OutboxDispatcher", _database!.OutboxConnectionString); + if (platform) builder.UseSetting("ConnectionStrings:PlatformAdmin", _database!.PlatformConnectionString); + if (configure is not null) builder.ConfigureTestServices(configure); + }); + + private async Task RunAsync(IServiceProvider services, BackgroundJobId job) + { + var executor = services.GetRequiredService(); + var start = await executor.ExecuteAsync(await DataExportTestKit.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)); + } + + /// A self-filed request in its initial state, under the canonical fences. + private async Task FileAsync(Guid tenant, Guid? organization, Guid subject, Guid[] memberships, string kind) + { + var id = Guid.CreateVersion7(); + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, tenant, organization, subject); + await InsertRequestAsync(app, transaction, id, tenant, organization, subject, memberships, kind); + await transaction.CommitAsync(); + return id; + } + + /// A self-filed erasure whose cancellable window has already ended by the database clock. + private async Task FileDueErasureAsync(Guid tenant, Guid? organization, Guid subject, Guid[] memberships) + { + var id = await FileAsync(tenant, organization, subject, memberships, "erasure"); + await DataErasureTestKit.BackdateAsync(_database!.MigrationConnectionString, tenant, organization, id); + return id; + } + + /// A pending offer the person issued in the group, written by the application role under the tenant fence. + private async Task IssueInvitationAsync(Guid tenant, Guid? organization, Guid inviter) + { + var id = Guid.CreateVersion7(); + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant, organization); + await LockAsync(app, transaction, tenant, null, false); + await ExecuteAsync(app, transaction, """ + INSERT INTO public.invitations(id,tenant_id,organization_id,recipient_email,inviter_user_id,role_id, + pinned_role_version,status,generation_id,generation,generation_created_at,expires_at, + verifier_digest,entry_origin,entry_locale,current_delivery_job_id,submission_status,created_at,created_by) + VALUES(@id,@tenant,@organization,@email,@inviter,@role,0,'Pending',@generation,1,@at, + @at+interval '14 days',@digest,'https://manage.invitation.invalid','en',@job,'Queued',@at,@inviter) + """, ("id", id), ("tenant", tenant), ("organization", organization), ("email", "erased-issuer-" + id.ToString("N") + "@example.invalid"), + ("inviter", inviter), ("role", RoleId(tenant, LearnStack.SharedKernel.Permissions.BuiltInRoleKey.Learner, organization is null + ? LearnStack.SharedKernel.Permissions.PermissionScope.Tenant : LearnStack.SharedKernel.Permissions.PermissionScope.Organization)), + ("generation", Guid.CreateVersion7()), ("job", Guid.CreateVersion7()), ("digest", InvitationSchemaSeed.Digest(id)), + ("at", DateTimeOffset.UtcNow)); + await transaction.CommitAsync(); + return id; + } + + /// A Membership moved out of Active by the application role under the canonical fences, as an administrator would. + private async Task SetStatusAsync(Guid tenant, Guid? organization, Guid membership, string status) + { + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant, organization); + await LockAsync(app, transaction, tenant, PersonA, false); + await ExecuteAsync(app, transaction, status == "Revoked" + ? "UPDATE public.memberships SET status='Revoked', deleted_at=clock_timestamp(), deleted_by=@system, updated_at=clock_timestamp(), updated_by=@system, row_version=row_version+1 WHERE id=@member" + : "UPDATE public.memberships SET status='Suspended', updated_at=clock_timestamp(), updated_by=@system, row_version=row_version+1 WHERE id=@member", + ("member", membership), ("system", SystemActor)); + await transaction.CommitAsync(); + } + + private sealed record RequestState(string Status, string Progress, string Result, string? Failure, string? Refusal); + + private sealed record MembershipState(string Status, Guid? DeletedBy, string? DisplayName, string? Locale, string CustomFields, + long Assignments); + + private sealed record RowState(long Version, DateTime? UpdatedAt, Guid? UpdatedBy, DateTime? DeletedAt); + + private async Task RequestAsync(Guid tenant, Guid? organization, Guid request) + { + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + 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, last_refusal 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), + row.IsDBNull(4) ? null : row.GetString(4)); + } + + private async Task MembershipAsync(Guid tenant, Guid? organization, Guid membership) + { + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant, organization); + await using var command = new NpgsqlCommand(""" + SELECT m.status, m.deleted_by, p.display_name, p.preferred_locale, p.custom_fields::text, + (SELECT count(*) FROM public.membership_role_assignments a WHERE a.tenant_id=m.tenant_id AND a.membership_id=m.id) + FROM public.memberships m JOIN public.membership_profiles p ON p.tenant_id=m.tenant_id AND p.membership_id=m.id + WHERE m.id=@id + """, app, transaction); + command.Parameters.AddWithValue("id", membership); + await using var row = await command.ExecuteReaderAsync(); + (await row.ReadAsync()).Should().BeTrue(); + return new MembershipState(row.GetString(0), row.IsDBNull(1) ? null : row.GetGuid(1), row.IsDBNull(2) ? null : row.GetString(2), + row.IsDBNull(3) ? null : row.GetString(3), row.GetString(4), row.GetInt64(5)); + } + + private async Task RowAsync(Guid tenant, Guid? organization, Guid membership) + { + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant, organization); + await using var command = new NpgsqlCommand( + "SELECT row_version, updated_at, updated_by, deleted_at FROM public.memberships WHERE id=@id", app, transaction); + command.Parameters.AddWithValue("id", membership); + await using var row = await command.ExecuteReaderAsync(); + (await row.ReadAsync()).Should().BeTrue(); + return new RowState(row.GetInt64(0), row.IsDBNull(1) ? null : row.GetDateTime(1), row.IsDBNull(2) ? null : row.GetGuid(2), + row.IsDBNull(3) ? null : row.GetDateTime(3)); + } + + private async Task<(string Status, long Chunks)> ArtifactAsync(Guid tenant, Guid? organization, Guid artifact) + { + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant, organization); + await using var command = new NpgsqlCommand(""" + SELECT a.status, (SELECT count(*) FROM public.data_export_chunks c WHERE c.tenant_id=a.tenant_id AND c.artifact_id=a.id) + FROM public.data_export_artifacts a WHERE a.id=@id + """, app, transaction); + command.Parameters.AddWithValue("id", artifact); + await using var row = await command.ExecuteReaderAsync(); + (await row.ReadAsync()).Should().BeTrue(); + return (row.GetString(0), row.GetInt64(1)); + } + + private async Task<(string Status, Guid? UpdatedBy)> InvitationAsync(Guid tenant, Guid? organization, Guid invitation) + { + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant, organization); + await using var command = new NpgsqlCommand("SELECT status, updated_by FROM public.invitations WHERE id=@id", app, transaction); + command.Parameters.AddWithValue("id", invitation); + await using var row = await command.ExecuteReaderAsync(); + (await row.ReadAsync()).Should().BeTrue(); + return (row.GetString(0), row.IsDBNull(1) ? null : row.GetGuid(1)); + } + + /// The changes of the one success row about . + private async Task AuditChangesAsync(Guid tenant, string operation, Guid entity) + { + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant, null); + return await ScalarAsync(app, transaction, """ + SELECT changes::text FROM public.audit_log + WHERE operation=@operation AND outcome='success' AND organization_id IS NULL AND entity_id=@entity + """, ("operation", operation), ("entity", entity.ToString("D"))); + } + + /// The application role reads only its own session's User, so the binding is read as the owner. + private async Task UserStatusAsync(Guid user) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database!.MigrationConnectionString); + return await ScalarAsync(owner, null, "SELECT status FROM public.users WHERE id=@id", ("id", user)); + } + + private async Task AuditAsync(Guid tenant, Guid? organization, string operation, Guid? entity) + { + await using var app = await DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + 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 outcome='success' 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?.ToString("D") ?? DBNull.Value)); + } + + /// Fails its first erasure and succeeds afterwards: a transient failure after the Identity participant erased. + private sealed class FailingParticipant : IUserDataParticipant + { + private int _calls; + + public string Key => "probe"; + + public Task ExportAsync(UserDataSubject subject, IUserDataExportWriter writer, CancellationToken cancellationToken) => Task.CompletedTask; + + public Task EraseAsync(UserDataSubject subject, CancellationToken cancellationToken) => + Interlocked.Increment(ref _calls) == 1 + ? throw new InvalidOperationException("Synthetic transient erasure failure.") + : Task.CompletedTask; + + public Task> DescribeRetainedAsync(UserDataSubject subject, + CancellationToken cancellationToken) => Task.FromResult>([]); + } + + private sealed class FixedHold : IDataRequestHoldSource + { + public Task HasHoldAsync(DataRequestHoldQuery query, CancellationToken cancellationToken) => Task.FromResult(true); + } +} + +internal static class DataErasureJobResults +{ + /// The job's attempt committed; a failure names the runtime's disposition and code. + internal static void Committed(this JobBusinessExecutionResult result, string because = "the attempt commits") => + result.CommitAcknowledged.Should().BeTrue(because + " (disposition {0}, code {1})", result.Decision.Disposition, + result.Decision.ErrorCode); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataErasureGuardTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataErasureGuardTests.cs new file mode 100644 index 000000000..d48f6af34 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataErasureGuardTests.cs @@ -0,0 +1,266 @@ +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; + +/// +/// ADR-0107 § 5's one database exception, as learnstack_app: the contextual mutation guard admits a clearing UPDATE +/// of exactly the three personal columns of a Revoked Membership's profile only while the connection holds that person's +/// User fence and the tenant key, both exclusively, and that person's erasure request for that very group is +/// fulfilling. Each condition is removed alone and the UPDATE is refused; every other refusal of the guard stands. +/// +/// +/// Tenant A's tenant-wide learner Membership of person A is Revoked and person A's tenant-wide erasure is durable +/// fulfilling; person A's first branch Membership is Revoked with no erasure in that branch; tenant B's branch +/// Membership of person B is Revoked with a scheduled erasure that is not yet due. Every probe runs in its own +/// transaction and rolls back. +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed class DataErasureGuardTests(SchemaFixture fixture) +{ + private const string Clear = """ + UPDATE public.membership_profiles SET display_name=NULL, preferred_locale=NULL, custom_fields='[]'::jsonb + WHERE membership_id=@member + """; + + private const string MembershipParentRefusal = "P0304"; + private const string FenceRefusal = "P0301"; + private const string PrivilegeRefusal = "42501"; + + [Fact] + public async Task A_clearing_update_of_a_revoked_profile_is_admitted_only_under_every_condition_of_the_erasure_witness() + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(fixture.Postgres); + var erasure = await ArrangeAsync(database); + + // Admitted: both fences exclusive, the person's fulfilling erasure of exactly this group, the three columns cleared. + await ProbeAsync(database, SchemaFixture.TenantA, null, PersonA, Fence.Exclusive, async (app, transaction) => + { + (await CountAsync(app, transaction, Clear, LearnerMembershipA)).Should().Be(1); + (await ScalarAsync(app, transaction, """ + SELECT display_name IS NULL AND preferred_locale IS NULL AND custom_fields='[]'::jsonb + FROM public.membership_profiles WHERE membership_id=@member + """, ("member", LearnerMembershipA))).Should().BeTrue(); + // A role assignment DELETE of a Revoked parent was admitted before this exception and still is. + (await CountAsync(app, transaction, "DELETE FROM public.membership_role_assignments WHERE membership_id=@member", + LearnerMembershipA)).Should().Be(1); + }); + + // Each condition removed alone. + await RefusedAsync(database, SchemaFixture.TenantA, null, null, Fence.Exclusive, Clear, LearnerMembershipA, MembershipParentRefusal, + "without the subject's User fence"); + await RefusedAsync(database, SchemaFixture.TenantA, null, PersonA, Fence.Exclusive, Clear, LearnerMembershipA, MembershipParentRefusal, + "with the subject's User fence held shared instead of exclusively", userFenceShared: true); + await RefusedAsync(database, SchemaFixture.TenantA, null, PersonA, Fence.Shared, Clear, LearnerMembershipA, FenceRefusal, + "with the tenant key held shared instead of exclusively"); + await RefusedAsync(database, SchemaFixture.TenantA, null, PersonA, Fence.None, Clear, LearnerMembershipA, FenceRefusal, + "without the tenant key"); + await RefusedAsync(database, SchemaFixture.TenantA, null, PersonA, Fence.Exclusive, Clear, LearnerMembershipA, MembershipParentRefusal, + "once the erasure is no longer fulfilling", (app, transaction) => StepAsync(app, transaction, erasure, "status='awaiting_privileged_step'")); + await RefusedAsync(database, SchemaFixture.TenantB, SchemaFixture.OrgB1, PersonB, Fence.Exclusive, Clear, BranchMembershipB, + MembershipParentRefusal, "while the person's erasure of the group is only scheduled"); + await RefusedAsync(database, SchemaFixture.TenantA, SchemaFixture.OrgA1, PersonA, Fence.Exclusive, Clear, BranchMembershipA1, + MembershipParentRefusal, "in another group of the same person, whose erasure is the tenant-wide group's"); + await RefusedAsync(database, SchemaFixture.TenantA, SchemaFixture.OrgA1, PersonA, Fence.Exclusive, Clear, BranchMembershipA1, + MembershipParentRefusal, "with a fulfilling request of another kind for the person and group", async (app, transaction) => + { + var export = Guid.CreateVersion7(); + await InsertRequestAsync(app, transaction, export, SchemaFixture.TenantA, SchemaFixture.OrgA1, PersonA, [BranchMembershipA1]); + await StepAsync(app, transaction, export, "status='fulfilling'"); + }); + await RefusedAsync(database, SchemaFixture.TenantA, null, AdminA, Fence.Exclusive, Clear, AdminMembershipA, MembershipParentRefusal, + "for another person of the group, whose own User fence is held but who has no erasure", (app, transaction) => ExecuteAsync(app, + transaction, RevokeSql, ("member", AdminMembershipA), ("system", SystemActor))); + + // Only a clearing UPDATE: a value left or set, or any other column, is not one. + await RefusedAsync(database, SchemaFixture.TenantA, null, PersonA, Fence.Exclusive, + "UPDATE public.membership_profiles SET display_name='kept', preferred_locale=NULL, custom_fields='[]'::jsonb WHERE membership_id=@member", + LearnerMembershipA, MembershipParentRefusal, "with a display name that is not cleared"); + await RefusedAsync(database, SchemaFixture.TenantA, null, PersonA, Fence.Exclusive, + "UPDATE public.membership_profiles SET display_name=NULL, custom_fields='[]'::jsonb WHERE membership_id=@member", + LearnerMembershipA, MembershipParentRefusal, "with the locale left in place"); + await RefusedAsync(database, SchemaFixture.TenantA, null, PersonA, Fence.Exclusive, + "UPDATE public.membership_profiles SET display_name=NULL, preferred_locale=NULL, custom_fields='[{}]'::jsonb WHERE membership_id=@member", + LearnerMembershipA, MembershipParentRefusal, "with custom values that are not the empty list"); + await RefusedAsync(database, SchemaFixture.TenantA, null, PersonA, Fence.Exclusive, + "UPDATE public.membership_profiles SET display_name=NULL, preferred_locale=NULL, custom_fields=NULL WHERE membership_id=@member", + LearnerMembershipA, MembershipParentRefusal, "with NULL custom values, which compare as neither equal nor different"); + await RefusedAsync(database, SchemaFixture.TenantA, null, PersonA, Fence.Exclusive, """ + UPDATE public.membership_profiles SET display_name=NULL, preferred_locale=NULL, custom_fields='[]'::jsonb, + membership_id=@other WHERE membership_id=@member + """, LearnerMembershipA, MembershipParentRefusal, "with another column in the same UPDATE", + other: BranchMembershipA1); + + // Every other refusal stands: the Revoked row itself, an assignment added to it, and the profile's DELETE. + await RefusedAsync(database, SchemaFixture.TenantA, null, PersonA, Fence.Exclusive, + "UPDATE public.memberships SET updated_at=clock_timestamp(), row_version=row_version+1 WHERE id=@member", + LearnerMembershipA, MembershipParentRefusal, "on the Revoked Membership's own row"); + await RefusedAsync(database, SchemaFixture.TenantA, null, PersonA, Fence.Exclusive, """ + INSERT INTO public.membership_role_assignments(tenant_id,membership_id,role_id,organization_id) + VALUES(@tenant,@member,@role,NULL) + """, LearnerMembershipA, MembershipParentRefusal, "for a role assignment added to the Revoked parent", + role: RoleId(SchemaFixture.TenantA, LearnStack.SharedKernel.Permissions.BuiltInRoleKey.Learner, + LearnStack.SharedKernel.Permissions.PermissionScope.Tenant)); + await RefusedAsync(database, SchemaFixture.TenantA, null, PersonA, Fence.Exclusive, + "DELETE FROM public.membership_profiles WHERE membership_id=@member", LearnerMembershipA, PrivilegeRefusal, + "for the profile's DELETE, which the application role holds no grant for"); + } + + /// + /// The witness is bound to the request's frozen snapshot: a Revoked Membership of the same person and group that the + /// request does not name (one admitted and revoked again after it was filed) is not cleared by it. + /// + [Fact] + public async Task A_revoked_Membership_outside_the_request_s_snapshot_is_not_cleared_by_its_witness() + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(fixture.Postgres); + var erasure = await ArrangeAsync(database); + await CorruptSnapshotAsync(database, erasure, Guid.CreateVersion7()); + + await RefusedAsync(database, SchemaFixture.TenantA, null, PersonA, Fence.Exclusive, Clear, LearnerMembershipA, MembershipParentRefusal, + "for a Revoked Membership the fulfilling request's snapshot does not name"); + } + + /// + /// The organization and subject predicates of the witness are each enough alone: a fulfilling tenant-wide erasure of + /// person A whose frozen snapshot is corrupted to also name a Revoked Membership of person A in another group, or a + /// Revoked Membership of another person of the group, still clears neither. The snapshot contains each target, so the + /// snapshot predicate is satisfied and cannot be what refuses; the probe holds the target person's User fence and the + /// tenant key exclusively, so no fence is what refuses either. + /// + [Fact] + public async Task A_snapshot_widened_to_another_group_or_another_person_is_refused_by_the_organization_and_subject_predicates() + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(fixture.Postgres); + var erasure = await ArrangeAsync(database); + await CorruptSnapshotAsync(database, erasure, LearnerMembershipA, BranchMembershipA1, AdminMembershipA); + const string named = "SELECT membership_snapshot @> jsonb_build_array(@member::text) FROM public.data_subject_requests WHERE id=@erasure"; + + // Person A's other group: the erasure is the tenant-wide one, whose group is not the Membership's. + await ProbeAsync(database, SchemaFixture.TenantA, SchemaFixture.OrgA1, PersonA, Fence.Exclusive, async (app, transaction) => + { + (await ScalarAsync(app, transaction, named, ("member", BranchMembershipA1), ("erasure", erasure))).Should().BeTrue(); + (await DataExportTestKit.RefuseAsync(transaction, () => CountAsync(app, transaction, Clear, BranchMembershipA1))) + .SqlState.Should().Be(MembershipParentRefusal, "the erasure names the Membership but is not of its group"); + }); + + // Another person of the same group: the erasure is person A's, not the Membership's person's. + await ProbeAsync(database, SchemaFixture.TenantA, null, AdminA, Fence.Exclusive, async (app, transaction) => + { + // Revoked inside the rolled-back probe: committing it would strand the tenant without an administrator. + await ExecuteAsync(app, transaction, RevokeSql, ("member", AdminMembershipA), ("system", SystemActor)); + (await ScalarAsync(app, transaction, named, ("member", AdminMembershipA), ("erasure", erasure))).Should().BeTrue(); + (await DataExportTestKit.RefuseAsync(transaction, () => CountAsync(app, transaction, Clear, AdminMembershipA))) + .SqlState.Should().Be(MembershipParentRefusal, "the erasure names the Membership but is not of its person"); + }); + + // The control: the Membership of the erasure's own person and group is still admitted from the same arrangement. + await ProbeAsync(database, SchemaFixture.TenantA, null, PersonA, Fence.Exclusive, async (app, transaction) => + (await CountAsync(app, transaction, Clear, LearnerMembershipA)).Should().Be(1)); + } + + /// Replaces a request's frozen snapshot as the table owner with the request guard paused, in one committed transaction. + private static async Task CorruptSnapshotAsync(DisposableSchemaDatabase database, Guid erasure, params Guid[] memberships) + { + 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, null); + await ExecuteAsync(owner, transaction, "UPDATE public.data_subject_requests SET membership_snapshot=@snapshot::jsonb WHERE id=@id", + ("id", erasure), ("snapshot", Snapshot(memberships))); + await ExecuteAsync(owner, transaction, "ALTER TABLE public.data_subject_requests ENABLE TRIGGER tg_data_subject_requests_mutation_guard"); + await transaction.CommitAsync(); + } + + private enum Fence { None, Shared, Exclusive } + + private const string RevokeSql = """ + UPDATE public.memberships SET status='Revoked', deleted_at=clock_timestamp(), deleted_by=@system, + updated_at=clock_timestamp(), updated_by=@system, row_version=row_version+1 + WHERE id=@member + """; + + /// The three Revoked Memberships and the two erasures the probes read, committed by the application role. + private static async Task ArrangeAsync(DisposableSchemaDatabase database) + { + var erasure = Guid.CreateVersion7(); + await using var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString); + await using (var transaction = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, transaction, SchemaFixture.TenantA, null); + await LockAsync(app, transaction, SchemaFixture.TenantA, PersonA, false); + await ExecuteAsync(app, transaction, RevokeSql, ("member", LearnerMembershipA), ("system", SystemActor)); + await InsertRequestAsync(app, transaction, erasure, SchemaFixture.TenantA, null, PersonA, [LearnerMembershipA], "erasure"); + await transaction.CommitAsync(); + } + + await using (var transaction = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, transaction, SchemaFixture.TenantA, SchemaFixture.OrgA1); + await LockAsync(app, transaction, SchemaFixture.TenantA, PersonA, false); + await ExecuteAsync(app, transaction, RevokeSql, ("member", BranchMembershipA1), ("system", SystemActor)); + await transaction.CommitAsync(); + } + + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, SchemaFixture.TenantB, SchemaFixture.OrgB1, PersonB); + await ExecuteAsync(app, transaction, RevokeSql, ("member", BranchMembershipB), ("system", SystemActor)); + await InsertRequestAsync(app, transaction, Guid.CreateVersion7(), SchemaFixture.TenantB, SchemaFixture.OrgB1, PersonB, + [BranchMembershipB], "erasure"); + await transaction.CommitAsync(); + } + + await DataErasureTestKit.BackdateAsync(database.MigrationConnectionString, SchemaFixture.TenantA, null, erasure); + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, SchemaFixture.TenantA, null, PersonA); + await StepAsync(app, transaction, erasure, "status='fulfilling'"); + await transaction.CommitAsync(); + } + + return erasure; + } + + private static async Task RefusedAsync(DisposableSchemaDatabase database, Guid tenant, Guid? organization, Guid? user, Fence fence, + string sql, Guid member, string sqlState, string because, Func? arrange = null, + Guid? other = null, Guid? role = null, bool userFenceShared = false) => + await ProbeAsync(database, tenant, organization, user, fence, async (app, transaction) => + { + if (arrange is not null) await arrange(app, transaction); + var refusal = await DataExportTestKit.RefuseAsync(transaction, () => CountAsync(app, transaction, sql, member, tenant, other, role)); + refusal.SqlState.Should().Be(sqlState, because); + }, userFenceShared); + + /// One rolled-back application-role transaction announced for the group, with the fences asked for. + private static async Task ProbeAsync(DisposableSchemaDatabase database, Guid tenant, Guid? organization, Guid? user, Fence fence, + Func probe, bool userFenceShared = false) + { + await using var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant, organization); + if (user is { } person) + await ExecuteAsync(app, transaction, userFenceShared ? "SELECT pg_advisory_xact_lock_shared(@key)" : "SELECT pg_advisory_xact_lock(@key)", + ("key", LearnStack.SharedKernel.Identity.IdentityAdvisoryLockKey.ForUser(LearnStack.SharedKernel.Identifiers.UserId.From(person)))); + if (fence != Fence.None) + await ExecuteAsync(app, transaction, fence == Fence.Exclusive ? "SELECT pg_advisory_xact_lock(@key)" : "SELECT pg_advisory_xact_lock_shared(@key)", + ("key", LearnStack.SharedKernel.Identity.IdentityAdvisoryLockKey.ForTenant(LearnStack.SharedKernel.Identifiers.TenantId.From(tenant)))); + await probe(app, transaction); + await transaction.RollbackAsync(); + } + + private static async Task CountAsync(NpgsqlConnection app, NpgsqlTransaction transaction, string sql, Guid member, + Guid? tenant = null, Guid? other = null, Guid? role = null) + { + await using var command = new NpgsqlCommand(sql, app, transaction); + command.Parameters.AddWithValue("member", member); + if (tenant is { } value) command.Parameters.AddWithValue("tenant", value); + if (other is { } replacement) command.Parameters.AddWithValue("other", replacement); + if (role is { } assigned) command.Parameters.AddWithValue("role", assigned); + return await command.ExecuteNonQueryAsync(); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataErasureReplayFloorTests.Closure.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataErasureReplayFloorTests.Closure.cs new file mode 100644 index 000000000..6402f6b6f --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataErasureReplayFloorTests.Closure.cs @@ -0,0 +1,184 @@ +using FluentAssertions; +using LearnStack.Application.Messaging; +using LearnStack.Infrastructure.Messaging; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Platform; +using Microsoft.Extensions.DependencyInjection; +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 §§ 7 and 9 and ADR-0103 Amendment 2, the closure half of the replay floor, through the actual provider-event +/// path and the actual operator recovery owner: a subject-linked delivery dead-lettered while the person was Active, then +/// replayed after the person's User became Closing, or Closed by the person's real Finalize, re-runs the real handler, whose subject rule now refuses +/// the person. The delivery completes as a recorded no-op: no audit row names the person, nothing fails or is retried, the +/// replay counter advanced once, and the transport trail is otherwise untouched. +/// +public sealed partial class DataErasureReplayFloorTests +{ + [Theory] + [InlineData("Closing")] + [InlineData("Closed")] + public async Task A_replay_after_the_persons_account_began_closing_runs_the_handler_which_refuses_and_writes_nothing(string status) + { + await using var world = await ArrangeDeliveriesAsync(); + world.Host = CreateHost(world.Database); + await CloseAsync(world.Database, status); + await ReplayIsRefusedAsync(world, status); + } + + /// + /// The same floor after the person's real closure: Begin fans it out to person A's three groups with the actual fan-out + /// act, each group's actual erasure job runs, and the actual Finalize redacts, removes the account at the stand-in + /// provider and closes the person. The observation accepted while the person was Active is retained, by entity and + /// provider metadata, with nothing of the person in its redacted columns; the replay of the dead-lettered fact writes + /// nothing and resets nothing. + /// + [Fact] + public async Task A_replay_after_the_persons_closure_was_finalized_runs_the_handler_which_refuses_and_writes_nothing() + { + await using var world = await ArrangeDeliveriesAsync(); + var removal = new RecordingAccountRemoval(); + world.Host = AccountClosureFlow.Host(world.Database, removal); + var closure = Guid.CreateVersion7(); + await using (var app = await DataExportTestKit.OpenAppAsync(world.Database.AppConnectionString)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, SchemaFixture.TenantA, null, PersonA); + await InsertRequestAsync(app, transaction, closure, SchemaFixture.TenantA, null, PersonA, [LearnerMembershipA], "closure"); + await transaction.CommitAsync(); + } + + await DataErasureTestKit.BackdateAsync(world.Database.MigrationConnectionString, SchemaFixture.TenantA, null, closure); + var begun = await AccountClosureFlow.BeginAsync(world.Host, closure); + begun.Groups.Should().Be(new ClosureBeginTally(Served: 3, Started: 3, Adopted: 0, Waiting: 0, Failed: 0, Unserved: 0)); + foreach (var group in new ClosureParticipantGroup[] + { + new(TenantId.From(SchemaFixture.TenantA), null), + new(TenantId.From(SchemaFixture.TenantA), OrganizationId.From(SchemaFixture.OrgA1)), + new(TenantId.From(SchemaFixture.TenantA), OrganizationId.From(SchemaFixture.OrgA2)), + }) + { + await AccountClosureFlow.RunErasureJobAsync(world.Host, world.Database, group, + await AccountClosureFlow.FanOutRequestAsync(world.Database, group, PersonA)); + } + + var finalized = await AccountClosureFlow.FinalizeAsync(world.Host, + AccountClosureFlow.Admission(PlatformOperations.ClosureFinalize, "INC-REPLAY-CLOSURE"), closure); + finalized.Outcome.Should().Be(ClosureFinalizeOutcome.Finalized); + removal.Subjects.Should().ContainSingle(); + (await ObservationAsync(world, world.CompletedFact)).Should().NotBeNull("the earlier observation is retained, redacted, never deleted"); + + await ReplayIsRefusedAsync(world, "Closed"); + } + + /// The floor itself, once the person's User is : the replay re-runs the handler, which refuses. + private static async Task ReplayIsRefusedAsync(World world, string status) + { + world.Before = await TrailAsync(world); + world.Before["inbox_messages"].Should().StartWith("1:", "only the completed delivery left an inbox row"); + (await ObservationsAsync(world, world.CompletedFact)).Should().Be(1, "the fact accepted and delivered while the person was Active"); + (await ObservationsAsync(world, world.FailedFact)).Should().Be(0); + (await DeliveryAsync(world)).Should().Be(new DeliveryState(0, "retry_exhausted", true)); + // The definer the fact reader asks: the status, for this tenant's enqueued target only, under the person's User key + // held shared until the asking transaction ends; nothing for another tenant or an unknown target. + (await SubjectStatusAsync(world, SchemaFixture.TenantA, world.FailedTarget)).Should().Be((status, true)); + (await SubjectStatusAsync(world, SchemaFixture.TenantB, world.FailedTarget)).Should().Be(((string?)null, false), + "another tenant's announcement names no target of tenant A"); + (await SubjectStatusAsync(world, SchemaFixture.TenantA, Guid.CreateVersion7())).Should().Be(((string?)null, false)); + var fence = await InspectedFenceAsync(world); + + var replay = await world.Host.Services.GetRequiredService().ReplayDeliveryAsync( + Admission(PlatformOperations.DeliveryReplay), new DeliveryReplayRequest(SchemaFixture.TenantA, Subscription, + world.FailedEvent, fence.ReplayCount, fence.DeadLetteredAt!.Value, fence.TerminalReason!)); + replay.Should().Be(new OperatorRecoveryResult(OperatorRecoveryOutcome.Applied, 1), + "a closure does not reset replay, and the Active tenant admits it"); + + var claim = await world.Host.Services.GetRequiredService().TryClaimAsync([]); + claim.Should().NotBeNull("the reset row is due at once"); + claim!.EventId.Should().Be(world.FailedEvent); + var gate = new DeliveryCommitGate(); + var execution = await world.Host.Services.GetRequiredService().ExecuteAsync(claim, gate); + + execution.Should().Be(new DeliveryExecutionResult(DeliveryExecutionOutcome.Completed, true, false), + "the handler ran, refused the person and completed as a recorded no-op rather than a failure"); + gate.CommitAcknowledged.Should().BeTrue(); + (await ObservationsAsync(world, world.FailedFact)).Should().Be(0, "the refused observation is withheld: no row names the person"); + (await HandlerRowsAsync(world)).Should().Be(0, "the replayed delivery wrote no audit row at all"); + (await ObservationsAsync(world, world.CompletedFact)).Should().Be(1, + "the earlier observation is not the replay's to touch; the closure's Finalize redacts it"); + (await DeliveryAsync(world)).Should().Be(new DeliveryState(1, null, false), + "replay advanced once; nothing is dead-lettered or failed, so nothing is retried"); + var after = await TrailAsync(world); + after["outbox_messages"].Should().Be(world.Before["outbox_messages"]); + after["background_jobs"].Should().Be(world.Before["background_jobs"]); + after["provider_targets"].Should().Be(world.Before["provider_targets"]); + after["inbox_messages"].Should().StartWith("2:", "the inbox row records that the refused delivery ran; it is the only addition"); + (await UserStatusAsync(world)).Should().Be(status, "a delivery never moves a User"); + } + + /// + /// Person A's User moved by the platform role under the closure's fences as Begin's and Finalize's acquirer takes them: + /// the User key, then the key of the one tenant person A holds Memberships in, both transaction-scoped and exclusive. + /// + private static async Task CloseAsync(DisposableSchemaDatabase database, string status) + { + foreach (var sql in status == "Closed" + ? new[] { "UPDATE public.users SET status='Closing' WHERE id=@user", + "UPDATE public.users SET status='Closed', provider_subject=NULL WHERE id=@user" } + : ["UPDATE public.users SET status='Closing' WHERE id=@user"]) + { + await using var platform = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.PlatformConnectionString); + await using var transaction = await platform.BeginTransactionAsync(); + await ExecuteAsync(platform, transaction, "SELECT pg_catalog.pg_advisory_xact_lock(@key)", + ("key", IdentityAdvisoryLockKey.ForUser(UserId.From(PersonA)))); + await ExecuteAsync(platform, transaction, "SELECT pg_catalog.pg_advisory_xact_lock(@key)", + ("key", IdentityAdvisoryLockKey.ForTenant(TenantId.From(SchemaFixture.TenantA)))); + await ExecuteAsync(platform, transaction, sql, ("user", PersonA)); + await transaction.CommitAsync(); + } + } + + /// Every audit row the replayed delivery's handler could have caused: those whose causation is its event. + private static async Task HandlerRowsAsync(World world) + { + await using var app = await DataExportTestKit.OpenAppAsync(world.Database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + return await ScalarAsync(app, transaction, "SELECT count(*) FROM public.audit_log WHERE metadata->>'causation_id' = @event", + ("event", world.FailedEvent.ToString("D"))); + } + + /// + /// What the subject status definer answers on an application transaction announced for , and + /// whether that transaction then holds the affected person's User key shared. + /// + private static async Task<(string? Status, bool SharedFence)> SubjectStatusAsync(World world, Guid tenant, Guid target) + { + await using var app = await DataExportTestKit.OpenAppAsync(world.Database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant); + await using var command = new NpgsqlCommand("SELECT public.fn_identity_provider_event_subject_status(@target)", app, transaction); + command.Parameters.AddWithValue("target", target); + var status = await command.ExecuteScalarAsync() as string; + var shared = await ScalarAsync(app, transaction, """ + SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_locks AS held + WHERE held.pid = pg_catalog.pg_backend_pid() AND held.locktype = 'advisory' AND held.granted + AND held.mode = 'ShareLock' AND held.objsubid = 1 + AND ((held.classid::bigint << 32) | held.objid::bigint) = @key) + """, ("key", IdentityAdvisoryLockKey.ForUser(UserId.From(PersonA)))); + await transaction.RollbackAsync(); + return (status, shared); + } + + private static async Task UserStatusAsync(World world) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(world.Database.MigrationConnectionString); + return await ScalarAsync(owner, null, "SELECT status FROM public.users WHERE id = @id", ("id", PersonA)); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataErasureReplayFloorTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataErasureReplayFloorTests.cs new file mode 100644 index 000000000..38d0aa0ba --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataErasureReplayFloorTests.cs @@ -0,0 +1,572 @@ +using System.Diagnostics; +using FluentAssertions; +using LearnStack.Application.Jobs; +using LearnStack.Application.Messaging; +using LearnStack.Infrastructure.Identity.ProviderEvents; +using LearnStack.Infrastructure.Jobs; +using LearnStack.Infrastructure.Messaging; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Platform; +using LearnStack.Tests.Fixtures; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Hosting; +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 § 9 and ADR-0103 Amendment 2 for a tenant-erased person, through the actual provider-event path, the actual +/// erasure job and the actual operator recovery owner: an erasure never rewrites or deletes an outbox, delivery, inbox or +/// job row, and a replay of a delivery the handler never completed re-runs the real handler, whose own subject rule does +/// not refuse the person because their User stays Active, so it writes the person's audit observation again. Those rows +/// are retained transport evidence, not undone. +/// +/// +/// The subject-linked delivery is the Identity provider-event mirror, audit.provider-event-mirror.v1: it is the one +/// subscription in the composition root whose event names a person (its retained target carries +/// affected_user_id), and the whole production chain from a provider fact to the Audit observation runs against a +/// plain database with no hand-built transport row. Two facts about person A are mirrored: the first completes (outbox +/// row processed, delivery processed, inbox row, observation), the second is made to fail durably at the audit write and +/// is then dead-lettered, so a replay is possible. The Closing and Closed User half of the floor is in the class's closure +/// part. +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed partial class DataErasureReplayFloorTests(SchemaFixture fixture) +{ + private const string Subscription = "audit.provider-event-mirror.v1"; + private static readonly string[] Tables = ["outbox_messages", "event_deliveries", "inbox_messages", "background_jobs", "provider_targets"]; + + [Fact] + public async Task A_tenant_erasure_leaves_the_transport_trail_untouched_and_a_replay_writes_for_the_erased_person_as_retained_transport_evidence() + { + await using var world = await ArrangeAsync(); + + world.Before["outbox_messages"].Should().StartWith("2:", "both provider facts about the person were produced"); + world.Before["event_deliveries"].Should().StartWith("2:"); + world.Before["inbox_messages"].Should().StartWith("1:", "only the completed delivery left an inbox row"); + world.Before["background_jobs"].Should().StartWith("1:", "the person's export job, not the erasure job"); + world.Before["provider_targets"].Should().StartWith("2:"); + world.After.Should().BeEquivalentTo(world.Before, "an erasure never rewrites or deletes an outbox, delivery, inbox or job row"); + (await ObservationsAsync(world, world.CompletedFact)).Should().Be(1); + (await ObservationsAsync(world, world.FailedFact)).Should().Be(0, "its handler never completed"); + (await DeliveryAsync(world)).Should().Be(new DeliveryState(0, "retry_exhausted", true)); + (await PersonStateAsync(world)).Should().Be(("Active", "Revoked", "Active", "Active"), + "the person's User stays Active and only the tenant-wide Membership of the request's group was erased"); + + // The operator's completion, through the real platform scope of the API composition, redacts the audit log and + // completes the request; it is the last act before a replay, and it too rewrites no transport row. + (await RequestStatusAsync(world)).Should().Be("awaiting_privileged_step"); + var retained = await ObservationAsync(world, world.CompletedFact); + retained.Should().NotBeNull("the completed delivery's observation exists before the redaction"); + await using (var scope = world.Host.Services.CreateAsyncScope()) + { + var completion = await scope.ServiceProvider.GetRequiredService().CompleteErasureAsync( + TestPlatformAdmissions.Admission(PlatformOperations.ErasureComplete, "INC-REPLAY-FLOOR", + correlationId: "00-replay-floor-complete-" + Guid.NewGuid().ToString("N")), world.ErasureRequest); + completion.Outcome.Should().Be(ErasureCompletionOutcome.Completed); + completion.Report!.RowsSelected.Should().BeGreaterThan(0, "the redaction ran over the person's audit rows"); + } + + (await RequestStatusAsync(world)).Should().Be("completed", "the privileged step finished before the replay"); + var completed = await TrailAsync(world); + completed.Should().BeEquivalentTo(world.Before, + "the operator's completion redacts audit payloads and rewrites no outbox, delivery, inbox or job row"); + (await ObservationsAsync(world, world.CompletedFact)).Should().Be(1, "the completion does not delete the retained observation"); + (await ObservationsAsync(world, world.FailedFact)).Should().Be(0, "no observation was written by the redaction"); + (await DeliveryAsync(world)).Should().Be(new DeliveryState(0, "retry_exhausted", true)); + + var fence = await InspectedFenceAsync(world); + var replay = await world.Host.Services.GetRequiredService().ReplayDeliveryAsync( + Admission(PlatformOperations.DeliveryReplay), new DeliveryReplayRequest(SchemaFixture.TenantA, Subscription, + world.FailedEvent, fence.ReplayCount, fence.DeadLetteredAt!.Value, fence.TerminalReason!)); + replay.Should().Be(new OperatorRecoveryResult(OperatorRecoveryOutcome.Applied, 1), + "the erasure did not reset replay and the Active tenant admits it"); + + var store = world.Host.Services.GetRequiredService(); + var claim = await store.TryClaimAsync([]); + claim.Should().NotBeNull("the reset row is due at once"); + claim!.EventId.Should().Be(world.FailedEvent); + var gate = new DeliveryCommitGate(); + var execution = await world.Host.Services.GetRequiredService().ExecuteAsync(claim, gate); + + execution.Should().Be(new DeliveryExecutionResult(DeliveryExecutionOutcome.Completed, true, false), + "the handler re-ran for the erased person and its subject rule did not refuse"); + gate.CommitAcknowledged.Should().BeTrue(); + (await ObservationsAsync(world, world.FailedFact)).Should().Be(1, + "the replay wrote the erased person's audit observation again; it is retained transport evidence"); + (await ObservationsAsync(world, world.CompletedFact)).Should().Be(1, "the completed delivery is not re-run"); + var written = await ObservationAsync(world, world.FailedFact); + written.Should().NotBeNull(); + written!.EntityType.Should().Be("User"); + written.EntityId.Should().Be(PersonA.ToString("D")); + written.AffectedUser.Should().Be(PersonA.ToString("D"), + "the replayed handler writes the person's identifier into its metadata as it always does; the floor is not undone"); + written.ProviderEvent.Should().Be(world.FailedFact.ToString("D")); + written.Kind.Should().Be("Logout"); + written.TargetId.Should().Be(world.FailedTarget.ToString("D")); + written.Operation.Should().Be("audit.provider_event.observe"); + (await ObservationAsync(world, world.CompletedFact)).Should().Be(retained, + "the replay neither rewrites nor re-redacts the observation that was already there"); + (await RequestStatusAsync(world)).Should().Be("completed", "the replay does not reopen the completed request"); + (await DeliveryAsync(world)).Should().Be(new DeliveryState(1, null, false), "replay advanced once; nothing is dead-lettered or failed"); + var after = await TrailAsync(world); + after["outbox_messages"].Should().Be(world.Before["outbox_messages"]); + after["background_jobs"].Should().Be(world.Before["background_jobs"]); + after["provider_targets"].Should().Be(world.Before["provider_targets"]); + after["inbox_messages"].Should().StartWith("2:", "the replayed handler's inbox row is the only addition"); + (await PersonStateAsync(world)).Should().Be(("Active", "Revoked", "Active", "Active")); + } + + [Fact] + public async Task A_replay_after_a_tenant_erasure_is_still_refused_while_the_tenant_is_not_serving() + { + await using var world = await ArrangeAsync(); + await SetTenantStatusAsync(world.Database, "Suspended"); + var fence = await InspectedFenceAsync(world); + var before = await TrailAsync(world); + + var refused = await world.Host.Services.GetRequiredService().ReplayDeliveryAsync( + Admission(PlatformOperations.DeliveryReplay), new DeliveryReplayRequest(SchemaFixture.TenantA, Subscription, + world.FailedEvent, fence.ReplayCount, fence.DeadLetteredAt!.Value, fence.TerminalReason!)); + + (refused.Outcome, refused.Refusal).Should().Be((OperatorRecoveryOutcome.NotRecoverable, "tenant_not_serving"), + "the replay floor does not weaken ADR-0103's Active-tenant guard"); + (await TrailAsync(world)).Should().BeEquivalentTo(before); + (await DeliveryAsync(world)).Should().Be(new DeliveryState(0, "retry_exhausted", true)); + } + + /// + /// Two provider facts about person A run through the real intake, producer, outbox, dispatcher, inbox and Audit + /// handler; the second fails durably, is dead-lettered and kept; the person's export job row is stored; and the real + /// tenant-wide erasure job then runs, with the transport trail captured before and after it. + /// + private async Task ArrangeAsync() + { + var world = await ArrangeDeliveriesAsync(); + var database = world.Database; + try + { + await BackgroundJobRuntimeRows.InsertAsync(database.AppConnectionString, "identity.data_export_tenant.v1", + tenant: SchemaFixture.TenantA, parameters: BackgroundJobPayloadContract.Serialize( + new DataExportJobParameters(TenantWideA.Request), typeof(DataExportJobParameters), + BackgroundJobPayloadKind.Parameters)); + var erasure = await FileDueErasureAsync(database); + world.ErasureRequest = erasure; + world.ErasureJob = await DataErasureTestKit.SubmitAsync(database, SchemaFixture.TenantA, null, erasure); + world.Host = CreateHost(database); + world.Before = await TrailAsync(world); + + var executor = world.Host.Services.GetRequiredService(); + var start = await executor.ExecuteAsync( + await DataExportTestKit.RoutingClaim.ClaimAsync(database.OutboxConnectionString, world.ErasureJob), + BackgroundJobTestRun.Create()); + start.Outcome.Should().Be(JobStartExecutionOutcome.Started); + (await executor.ExecuteBusinessAsync(start.Receipt!, start.Receipt!.Run.OpenBoundary(BackgroundJobCheckpointKind.Transactional))) + .Committed(); + + world.After = await TrailAsync(world); + return world; + } + catch + { + await world.DisposeAsync(); + throw; + } + } + + /// + /// The two provider facts about person A through the real intake, producer, outbox, dispatcher, inbox and Audit handler: + /// the first completes and the second is dead-lettered as exhausted with its handler never completed. Tenant A is + /// left Active, so a replay of the second is admitted. + /// + private async Task ArrangeDeliveriesAsync() + { + var database = await DataExportTestKit.CreateSeededDatabaseAsync(fixture.Postgres); + var at = DateTimeOffset.FromUnixTimeMilliseconds(DateTimeOffset.UtcNow.AddMinutes(-1).ToUnixTimeMilliseconds()); + var key = IdentitySubjectKey.Compute(Authority.AuthorityId, "fixture-subject-" + PersonA.ToString("N")); + var completed = new IdentityProviderEvent(Guid.NewGuid(), at, IdentityProviderEventKind.Login, key); + var failed = new IdentityProviderEvent(Guid.NewGuid(), at.AddMilliseconds(1), IdentityProviderEventKind.Logout, key); + var world = new World(database, completed.SourceEventId, failed.SourceEventId); + try + { + const string refusal = "refuse_replay_floor_observation"; + await using (var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString)) + { + await ExecuteAsync(owner, null, $""" + ALTER TABLE public.audit_log ADD CONSTRAINT {refusal} + CHECK (NOT (operation = 'audit.provider_event.observe' + AND metadata->'provider_event'->>'provider_event_id' = '{failed.SourceEventId:D}')) NOT VALID + """); + await using (var api = new ProviderApi(fixture.Postgres, database, new Provider(completed, failed))) + { + _ = api.Services; + await WaitAsync(async () => await ObservationsAsync(world, completed.SourceEventId) == 1 + && await FailedDeliveryAttemptedAsync(world)); + } + + world.FailedEvent = await EventOfAsync(world, failed.SourceEventId); + world.FailedTarget = await TargetOfAsync(world, failed.SourceEventId); + // The real dispatcher stopped with the host above, but it may have exhausted the failing delivery in the moment + // between the first failed attempt the wait saw and that stop. So the arrangement asserts the state it needs, + // not the transition into it: this UPDATE dead-letters the delivery as the dispatcher would when it is still + // retrying (one row) and finds nothing to do when the dispatcher already did (no row); either way the delivery + // ends dead-lettered as exhausted with its handler never completed. + await using (var dispatcher = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.OutboxConnectionString)) + { + (await ScalarAsync(dispatcher, null, """ + WITH moved AS (UPDATE public.event_deliveries SET terminal_reason = 'retry_exhausted', + dead_lettered_at = clock_timestamp(), locked_by = NULL, locked_until = NULL + WHERE tenant_id = @tenant AND subscription_id = @subscription AND event_id = @event + AND processed_at IS NULL AND dead_lettered_at IS NULL RETURNING 1) + SELECT count(*) FROM moved + """, ("tenant", SchemaFixture.TenantA), ("subscription", Subscription), ("event", world.FailedEvent))) + .Should().BeLessThanOrEqualTo(1); + (await ScalarAsync(dispatcher, null, """ + SELECT count(*) FROM public.event_deliveries + WHERE tenant_id = @tenant AND subscription_id = @subscription AND event_id = @event + AND processed_at IS NULL AND dead_lettered_at IS NOT NULL AND terminal_reason = 'retry_exhausted' + AND locked_by IS NULL + """, ("tenant", SchemaFixture.TenantA), ("subscription", Subscription), ("event", world.FailedEvent))) + .Should().Be(1, "the failed delivery is dead-lettered as exhausted, with its handler never completed"); + } + + await ExecuteAsync(owner, null, $"ALTER TABLE public.audit_log DROP CONSTRAINT {refusal}"); + } + + await SetTenantStatusAsync(database, "Active"); + return world; + } + catch + { + await world.DisposeAsync(); + throw; + } + } + + private static WebApplicationFactory CreateHost(DisposableSchemaDatabase database) => + new ConstructionOnlyApiFactory().WithWebHostBuilder(builder => + { + builder.UseEnvironment(Environments.Development); + builder.UseSetting("ConnectionStrings:Default", database.AppConnectionString); + builder.UseSetting("ConnectionStrings:OutboxDispatcher", database.OutboxConnectionString); + builder.UseSetting("ConnectionStrings:PlatformAdmin", database.PlatformConnectionString); + }); + + /// A self-filed tenant-wide erasure of person A whose cancellable window has already ended. + private static async Task FileDueErasureAsync(DisposableSchemaDatabase database) + { + var id = Guid.CreateVersion7(); + await using (var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, SchemaFixture.TenantA, null, PersonA); + await InsertRequestAsync(app, transaction, id, SchemaFixture.TenantA, null, PersonA, [LearnerMembershipA], "erasure"); + await transaction.CommitAsync(); + } + + await DataErasureTestKit.BackdateAsync(database.MigrationConnectionString, SchemaFixture.TenantA, null, id); + return id; + } + + private static PlatformAdmission Admission(PlatformOperation operation) => + TestPlatformAdmissions.Admission(operation, null, correlationId: "00-replay-floor-" + Guid.NewGuid().ToString("N")); + + /// The fence an operator reads from the inspection of dead-lettered deliveries. + private static async Task InspectedFenceAsync(World world) + { + await using var scope = world.Host.Services.CreateAsyncScope(); + var page = await scope.ServiceProvider.GetRequiredService().InspectDeliveriesAsync( + Admission(PlatformOperations.DeliveryInspect), DeliveryInspectionState.DeadLettered, null, 20); + return page!.Items.Should().ContainSingle(item => item.EventId == world.FailedEvent && item.SubscriptionId == Subscription) + .Which; + } + + /// The count and a digest of every row of each transport store the erasure must not touch. + private static async Task> TrailAsync(World world) + { + var trail = new Dictionary(); + // The erasure job's own row is the runtime's to advance; every other job row, the person's export job included, is not. + var statements = new[] + { + ("outbox_messages", "public.outbox_messages", "t.id", "true"), + ("event_deliveries", "public.event_deliveries", "t.tenant_id, t.subscription_id, t.event_id", "true"), + ("inbox_messages", "public.inbox_messages", "t.tenant_id, t.subscription_id, t.event_id", "true"), + ("background_jobs", "public.background_jobs", "t.id", "t.id <> @erasureJob"), + }; + // The table owner reads every column but is subject to the forced row policy, so it announces the tenant, once for + // its tenant-wide rows and once for each organization's (a closure's fan-out writes rows in both); the dispatcher + // role bypasses the policy and can only count, which proves the announcements together hid no row. + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(world.Database.MigrationConnectionString); + await using var dispatcher = (NpgsqlConnection)await PostgresFixture.OpenAsync(world.Database.OutboxConnectionString); + foreach (var (name, table, order, filter) in statements) + { + var count = 0L; + var digests = new List(); + var scoped = await ScalarAsync(owner, null, """ + SELECT EXISTS (SELECT 1 FROM information_schema.columns + WHERE table_schema = 'public' AND table_name = @table AND column_name = 'organization_id') + """, ("table", name)); + foreach (var organization in scoped ? new Guid?[] { null, SchemaFixture.OrgA1, SchemaFixture.OrgA2 } : [null]) + { + await using var announced = await owner.BeginTransactionAsync(); + await ScopeAsync(owner, announced, SchemaFixture.TenantA, organization); + await using var command = new NpgsqlCommand($""" + SELECT count(*), coalesce(md5(string_agg(row_to_json(t)::text, '|' ORDER BY {order})), '') + FROM {table} t WHERE {filter}{(scoped ? " AND t.organization_id IS NOT DISTINCT FROM @organization::uuid" : string.Empty)} + """, owner, announced); + command.Parameters.AddWithValue("organization", (object?)organization ?? DBNull.Value); + if (filter.Contains("@erasureJob", StringComparison.Ordinal)) + command.Parameters.AddWithValue("erasureJob", ErasureJobOf(world)); + await using (var row = await command.ExecuteReaderAsync()) + { + (await row.ReadAsync()).Should().BeTrue(); + count += row.GetInt64(0); + digests.Add(row.GetString(1)); + } + + await announced.CommitAsync(); + } + + trail[name] = count + ":" + string.Join('/', digests); + + // The dispatcher role has no grant on the inbox, which only the application role reads. + if (name != "inbox_messages") + (await ScalarAsync(dispatcher, null, $"SELECT count(*) FROM {table} t WHERE {filter}", + ("erasureJob", ErasureJobOf(world)))) + .Should().Be(count, $"the tenant's announcements hide no {name} row"); + } + + await using var transaction = await owner.BeginTransactionAsync(); + await ScopeAsync(owner, transaction, SchemaFixture.TenantA); + await using var targets = new NpgsqlCommand(""" + SELECT count(*), coalesce(md5(string_agg(row_to_json(t)::text, '|' ORDER BY t.id)), '') + FROM public.identity_provider_event_targets t WHERE t.affected_user_id = @person + """, owner, transaction); + targets.Parameters.AddWithValue("person", PersonA); + await using (var result = await targets.ExecuteReaderAsync()) + { + (await result.ReadAsync()).Should().BeTrue(); + trail["provider_targets"] = result.GetInt64(0) + ":" + result.GetString(1); + } + + await transaction.CommitAsync(); + trail.Keys.Should().BeEquivalentTo(Tables); + return trail; + } + + /// The erasure job the trail leaves out, or none when the arrangement ran no erasure. + private static Guid ErasureJobOf(World world) => world.ErasureJob.IsInitialized() ? world.ErasureJob.Value : Guid.Empty; + + /// The audit observations the mirror handler wrote about person A for one provider fact. + private static async Task ObservationsAsync(World world, Guid providerEvent) + { + await using var app = await DataExportTestKit.OpenAppAsync(world.Database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + return await ScalarAsync(app, transaction, """ + SELECT count(*) FROM public.audit_log + WHERE operation = 'audit.provider_event.observe' AND entity_type = 'User' AND entity_id = @person + AND metadata->'provider_event'->>'provider_event_id' = @id + """, ("person", PersonA.ToString("D")), ("id", providerEvent.ToString("D"))); + } + + private sealed record Observation(string Operation, string EntityType, string EntityId, string? AffectedUser, string? ProviderEvent, + string? Kind, string? TargetId, string Metadata); + + /// The one audit observation the mirror handler wrote about person A for a provider fact, or none. + private static async Task ObservationAsync(World world, Guid providerEvent) + { + await using var app = await DataExportTestKit.OpenAppAsync(world.Database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + await using var command = new NpgsqlCommand(""" + SELECT operation, entity_type, entity_id, metadata->'provider_event'->>'affected_user_id', + metadata->'provider_event'->>'provider_event_id', metadata->'provider_event'->>'kind', + metadata->'provider_event'->>'target_id', metadata::text + FROM public.audit_log + WHERE operation = 'audit.provider_event.observe' AND entity_type = 'User' AND entity_id = @person + AND metadata->'provider_event'->>'provider_event_id' = @id + """, app, transaction); + command.Parameters.AddWithValue("person", PersonA.ToString("D")); + command.Parameters.AddWithValue("id", providerEvent.ToString("D")); + await using var row = await command.ExecuteReaderAsync(); + if (!await row.ReadAsync()) return null; + string? Text(int ordinal) => row.IsDBNull(ordinal) ? null : row.GetString(ordinal); + var observation = new Observation(row.GetString(0), row.GetString(1), row.GetString(2), Text(3), Text(4), Text(5), Text(6), + row.GetString(7)); + (await row.ReadAsync()).Should().BeFalse("one fact leaves one observation"); + return observation; + } + + /// The erasure request's stored status. + private static async Task RequestStatusAsync(World world) + { + await using var app = await DataExportTestKit.OpenAppAsync(world.Database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + return await ScalarAsync(app, transaction, "SELECT status FROM public.data_subject_requests WHERE id = @id", + ("id", world.ErasureRequest)); + } + + private sealed record DeliveryState(int ReplayCount, string? TerminalReason, bool DeadLettered); + + private static async Task DeliveryAsync(World world) + { + await using var dispatcher = (NpgsqlConnection)await PostgresFixture.OpenAsync(world.Database.OutboxConnectionString); + await using var command = new NpgsqlCommand(""" + SELECT replay_count, terminal_reason, dead_lettered_at IS NOT NULL + FROM public.event_deliveries WHERE tenant_id = @tenant AND subscription_id = @subscription AND event_id = @event + """, dispatcher); + command.Parameters.AddWithValue("tenant", SchemaFixture.TenantA); + command.Parameters.AddWithValue("subscription", Subscription); + command.Parameters.AddWithValue("event", world.FailedEvent); + await using var row = await command.ExecuteReaderAsync(); + (await row.ReadAsync()).Should().BeTrue(); + return new DeliveryState(row.GetInt32(0), row.IsDBNull(1) ? null : row.GetString(1), row.GetBoolean(2)); + } + + /// The failed fact's delivery has been tried and has failed, so the dispatcher can be stopped. + private static async Task FailedDeliveryAttemptedAsync(World world) + { + Guid? eventId; + try { eventId = await EventOfAsync(world, world.FailedFact); } + catch (InvalidOperationException) { return false; } + await using var dispatcher = (NpgsqlConnection)await PostgresFixture.OpenAsync(world.Database.OutboxConnectionString); + return await ScalarAsync(dispatcher, null, """ + SELECT count(*) FROM public.event_deliveries WHERE subscription_id = @subscription AND event_id = @event + AND last_error IS NOT NULL AND processed_at IS NULL + """, ("subscription", Subscription), ("event", eventId!.Value)) == 1; + } + + private static async Task TargetOfAsync(World world, Guid providerEvent) + { + await using var app = await DataExportTestKit.OpenAppAsync(world.Database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + return await ScalarAsync(app, transaction, "SELECT id FROM public.identity_provider_event_targets WHERE provider_event_id = @id", + ("id", providerEvent)); + } + + private static async Task EventOfAsync(World world, Guid providerEvent) + { + await using var app = await DataExportTestKit.OpenAppAsync(world.Database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + await using var command = new NpgsqlCommand( + "SELECT event_id FROM public.identity_provider_event_targets WHERE provider_event_id = @id", app, transaction); + command.Parameters.AddWithValue("id", providerEvent); + return await command.ExecuteScalarAsync() as Guid? ?? throw new InvalidOperationException("The fact has no target yet."); + } + + /// The person's User, their tenant-wide Membership and their two branch Memberships. + private static async Task<(string User, string Tenant, string Branch1, string Branch2)> PersonStateAsync(World world) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(world.Database.MigrationConnectionString); + var user = await ScalarAsync(owner, null, "SELECT status FROM public.users WHERE id = @id", ("id", PersonA)); + await using var app = await DataExportTestKit.OpenAppAsync(world.Database.AppConnectionString); + var statuses = new List(); + foreach (var (organization, membership) in new[] { ((Guid?)null, LearnerMembershipA), + (SchemaFixture.OrgA1, BranchMembershipA1), (SchemaFixture.OrgA2, BranchMembershipA2) }) + { + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA, organization); + statuses.Add(await ScalarAsync(app, transaction, "SELECT status FROM public.memberships WHERE id = @id", + ("id", membership))); + } + + return (user, statuses[0], statuses[1], statuses[2]); + } + + /// + /// Sets tenant A's lifecycle status. The seeded tenant has no default organization, which a serving tenant has, so the + /// recovery guard would refuse it before the status mattered. + /// + private static async Task SetTenantStatusAsync(DisposableSchemaDatabase database, string status) + { + await using var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await EducationSchemaSeed.AnnounceAsync(app, transaction, SchemaFixture.TenantA, null); + await TenancyLifecycleFixture.LockAsync(app, transaction, SchemaFixture.TenantA); + await ExecuteAsync(app, transaction, """ + UPDATE tenants SET status = @status, default_organization_id = coalesce(default_organization_id, @organization) + WHERE id = @tenant + """, ("status", status), ("organization", SchemaFixture.OrgA1), ("tenant", SchemaFixture.TenantA)); + await transaction.CommitAsync(); + } + + private static async Task WaitAsync(Func> condition) + { + var started = Stopwatch.GetTimestamp(); + while (!await condition()) + { + if (Stopwatch.GetElapsedTime(started) > TimeSpan.FromSeconds(60)) + throw new TimeoutException("The provider facts did not reach their expected durable boundary."); + await Task.Delay(50); + } + } + + /// The database, the host that runs the erasure and the recovery, and the ids the proofs read. + private sealed class World(DisposableSchemaDatabase database, Guid completedFact, Guid failedFact) : IAsyncDisposable + { + public DisposableSchemaDatabase Database => database; + public Guid CompletedFact => completedFact; + public Guid FailedFact => failedFact; + public Guid FailedEvent { get; set; } + public BackgroundJobId ErasureJob { get; set; } + public Guid ErasureRequest { get; set; } + public Guid FailedTarget { get; set; } + public WebApplicationFactory Host { get; set; } = null!; + public Dictionary Before { get; set; } = null!; + public Dictionary After { get; set; } = null!; + + public async ValueTask DisposeAsync() + { + if (Host is not null) await Host.DisposeAsync(); + await database.DisposeAsync(); + } + } + + /// The real Program with its dispatcher and mirror running over the disposable database, as the provider-event flow proof builds it. + private sealed class ProviderApi(PostgresFixture postgres, DisposableSchemaDatabase database, IIdentityEventProvider provider) + : WebApplicationFactory + { + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.UseEnvironment("Development"); + InvitationEmailFixtureConfiguration.AddTo(builder); + builder.UseSetting("ConnectionStrings:Default", database.AppConnectionString); + builder.UseSetting("ConnectionStrings:OutboxDispatcher", database.OutboxConnectionString); + builder.UseSetting("ConnectionStrings:IdentityIngress", new NpgsqlConnectionStringBuilder(postgres.IdentityIngressConnectionString) + { Database = new NpgsqlConnectionStringBuilder(database.AppConnectionString).Database }.ConnectionString); + builder.UseSetting("Identity:AuthorityId", Authority.AuthorityId.Value.ToString("D")); + builder.UseSetting("Authentication:Tenant:Issuer", Authority.Issuer); + builder.UseSetting("IdentityEvents:RealmId", "learnstack"); + builder.UseSetting("Telemetry:OtlpEndpoint", ""); + builder.ConfigureTestServices(services => + { + services.RemoveAll(); + services.AddSingleton(provider); + }); + } + } + + private sealed class Provider(params IdentityProviderEvent[] facts) : IIdentityEventProvider + { + public Task ReadPolicyAsync(CancellationToken cancellationToken = default) => + Task.FromResult(new IdentityEventSourcePolicy(604800)); + + public Task ReadAsync(IdentityEventRead request, CancellationToken cancellationToken = default) => + Task.FromResult(IdentityEventPage.Read(facts.Where(item => item.OccurredAt >= request.From && item.OccurredAt <= request.To) + .Skip(request.Offset).Take(request.Maximum).Select(IdentityEventReadItem.Observed))); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataErasureTestKit.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataErasureTestKit.cs new file mode 100644 index 000000000..de308c30f --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataErasureTestKit.cs @@ -0,0 +1,45 @@ +using FluentAssertions; +using LearnStack.Infrastructure.Jobs; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.SharedKernel.Jobs; +using Npgsql; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The pieces an ADR-0107 § 5 erasure proof needs beside : the clock seam that moves a +/// scheduled request's window into the past, and the erasure job row the runtime claims. +/// +internal static class DataErasureTestKit +{ + /// + /// Moves a scheduled request's creation and execution time 25 hours into the past as the owner, with its guard paused + /// and restored, so its window has ended by the database clock; the 24-hour window constraint still holds. + /// + /// The owner is subject to the forced row policy, so it announces the request's own group. + internal static async Task BackdateAsync(string migrationConnectionString, Guid tenant, Guid? organization, Guid request) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(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, tenant, organization); + (await ScalarAsync(owner, transaction, """ + WITH moved AS ( + UPDATE public.data_subject_requests SET created_at=created_at - interval '25 hours', execute_at=execute_at - interval '25 hours' + WHERE id=@id AND status='scheduled' RETURNING 1) + SELECT count(*) FROM moved + """, ("id", request))).Should().Be(1, "exactly the scheduled request's window moves"); + await ExecuteAsync(owner, transaction, "ALTER TABLE public.data_subject_requests ENABLE TRIGGER tg_data_subject_requests_mutation_guard"); + await transaction.CommitAsync(); + } + + /// The request's erasure job, as the scheduler would have stored it, due now. + internal static Task SubmitAsync(DisposableSchemaDatabase database, Guid tenant, Guid? organization, Guid request) => + BackgroundJobRuntimeRows.InsertAsync(database.AppConnectionString, + organization is null ? "identity.data_erasure_tenant.v1" : "identity.data_erasure_organization.v1", + organization: organization, tenant: tenant, parameters: Parameters(request)); + + internal static string Parameters(Guid request) => BackgroundJobPayloadContract.Serialize(new DataErasureJobParameters(request), + typeof(DataErasureJobParameters), BackgroundJobPayloadKind.Parameters); +} 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 000000000..50b5f9159 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataExportArtifactStoreTests.cs @@ -0,0 +1,309 @@ +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 Microsoft.Extensions.Logging; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.DataExportTestKit; +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 ScalarAsync(scope.Connection, scope.Transaction, + "SELECT abs(extract(epoch FROM created_at - clock_timestamp())) < 60 FROM public.data_export_artifacts WHERE id=@id", + ("id", artifactId))).Should().BeTrue("the artifact is stamped by the database clock"); + await CompleteAsync(scope, request); + 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 DataExportTestKit.CreateSeededDatabaseAsync(schema.Postgres); + 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); + await CompleteAsync(scope, request); + 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(); + } + } + + /// + /// ADR-0107 § 4's associated data binds each chunk to its index and artifact: a chunk spliced into another position or + /// another artifact, and a chunk whose key left the ring, fail closed as an absence and are logged with identifiers + /// only, never a key, the ciphertext or the plaintext: critical the first time an artifact is refused under a key + /// label in the process, a warning for every repeat, so one lost key does not page once per chunk. + /// + [Fact] + public async Task A_spliced_or_unopenable_chunk_fails_closed_as_an_absence_and_is_logged_critical_once_with_identifiers_only() + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(schema.Postgres); + var bundle = Bundle(Size); + var artifactId = Guid.CreateVersion7(); + await using (var scope = await DataExportTestKit.OpenAsync(database.AppConnectionString, SchemaFixture.TenantA, null, [AdminA])) + { + using var cipher = DataExportTestKit.Cipher(); + var request = await FulfillingRequestAsync(scope, AdminA, AdminMembershipA); + await Store(scope, cipher).PutAsync(new DataExportArtifactPut(artifactId, request.Id.Value, request.SubjectUserId, request.Group, + Size), Chunks(bundle), CancellationToken.None); + await CompleteAsync(scope, request); + await scope.Frame.CompleteAsync(); + } + + // As the owner with the chunk guard paused: chunk 0's sealed bytes into index 1, and into another artifact's chunk 0. + var other = TenantWideA.Artifact!.Value; + 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_chunks DISABLE TRIGGER tg_data_export_chunks_mutation_guard"); + await ScopeAsync(owner, transaction, SchemaFixture.TenantA); + await ExecuteAsync(owner, transaction, """ + UPDATE public.data_export_chunks AS target SET nonce=source.nonce, ciphertext=source.ciphertext, tag=source.tag + FROM public.data_export_chunks AS source + WHERE source.artifact_id=@artifact AND source.chunk_index=0 + AND ((target.artifact_id=@artifact AND target.chunk_index=1) OR (target.artifact_id=@other AND target.chunk_index=0)) + """, ("artifact", artifactId), ("other", other)); + await ExecuteAsync(owner, transaction, "ALTER TABLE public.data_export_chunks ENABLE TRIGGER tg_data_export_chunks_mutation_guard"); + await transaction.CommitAsync(); + } + + await using (var scope = await DataExportTestKit.OpenAsync(database.AppConnectionString, SchemaFixture.TenantA, null)) + { + using var cipher = DataExportTestKit.Cipher(); + var logs = new CapturingLogger(); + var refusals = new DataExportCustodyRefusals(); + var store = Store(scope, cipher, logs, refusals); + var group = new DataRequestScopeGroup(TenantId.From(SchemaFixture.TenantA), null); + var first = (await store.ReadChunkAsync(new DataExportArtifactLocator(artifactId, group), 0, CancellationToken.None))!; + first.Bytes.ToArray().Should().Equal(bundle[..DataRequestLimits.ChunkPlaintextBytes], "the untouched chunk still opens"); + (await store.ReadChunkAsync(new DataExportArtifactLocator(artifactId, group), 1, CancellationToken.None)) + .Should().BeNull("a chunk moved to another index fails authentication"); + (await store.ReadChunkAsync(new DataExportArtifactLocator(other, group), 0, CancellationToken.None)) + .Should().BeNull("a chunk moved into another artifact fails authentication"); + (await store.ReadChunkAsync(new DataExportArtifactLocator(artifactId, group), 2, CancellationToken.None)) + .Should().NotBeNull("the refusals left the transaction usable"); + + // A ring that no longer holds the artifact's key: no mint is offered and a read is the same absence. + using var rotated = DataExportTestKit.Cipher("{\"active\":\"next\",\"keys\":{\"next\":\"" + + Convert.ToBase64String(Enumerable.Repeat((byte)7, 32).ToArray()) + "\"}}"); + var retired = Store(scope, rotated, logs, refusals); + retired.CanOpen(cipher.ActiveKeyVersion).Should().BeFalse(); + store.CanOpen(cipher.ActiveKeyVersion).Should().BeTrue(); + (await retired.ReadChunkAsync(new DataExportArtifactLocator(artifactId, group), 0, CancellationToken.None)).Should().BeNull(); + (await retired.ReadChunkAsync(new DataExportArtifactLocator(artifactId, group), 2, CancellationToken.None)).Should().BeNull(); + scope.Unit.IsRollbackOnly.Should().BeFalse("a custody refusal is not a storage failure"); + await scope.Frame.FailAsync(); + + logs.Entries.Should().HaveCount(4).And.OnlyContain(entry => entry.EventId.Id == 3193 + && entry.EventId.Name == "DataExportChunkCustodyRefused" && entry.Exception == null); + logs.Entries.Select(entry => entry.Level).Should().Equal([LogLevel.Critical, LogLevel.Critical, LogLevel.Warning, LogLevel.Warning], + "the first refusal of each artifact under its key label is critical; the same pair again, by another chunk or " + + "another store of the process, is a warning"); + var rendered = string.Join('\n', logs.Entries.Select(entry => entry.Message)); + rendered.Should().Contain(artifactId.ToString("D")).And.Contain(other.ToString("D")); + rendered.Should().NotContain(Convert.ToBase64String(bundle.AsSpan(0, 48))) + .And.NotContain(System.Text.Encoding.ASCII.GetString(bundle, 0, 48)); + DataExportTestKit.KeyRing.Should().NotBeNullOrEmpty(); + foreach (var key in System.Text.Json.JsonDocument.Parse(DataExportTestKit.KeyRing).RootElement.GetProperty("keys").EnumerateObject()) + rendered.Should().NotContain(key.Value.GetString()!, "no key material reaches a log"); + } + } + + internal static PostgresDataExportArtifactStore Store(DataExportTestKit.GroupScope scope, DataExportCipher cipher, + ILogger? logger = null, DataExportCustodyRefusals? refusals = null) => + new(scope.Db, scope.Unit, scope.Context, cipher, new DataExportTestKit.NoAuditSubject(), refusals ?? new DataExportCustodyRefusals(), + logger ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance); + + /// Completes a fulfilling export on the scope's transaction, as the job does before it commits. + internal static async Task CompleteAsync(DataExportTestKit.GroupScope scope, DataSubjectRequest request) + { + request.Complete([new(RetainedReferenceKind.RequestReceipt, 1)], DateTimeOffset.UtcNow, UserId.SystemActor).IsSuccess.Should().BeTrue(); + await scope.Db.SaveChangesAsync(); + } + + /// A fresh export of the subject in the scope's group, saved through the aggregate and fulfilling. + internal 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; + } + + internal 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(); + + internal 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 sealed record LogEntry(LogLevel Level, EventId EventId, string Message, Exception? Exception); + + private sealed class CapturingLogger : ILogger + { + public List Entries { get; } = []; + + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, + Func formatter) => Entries.Add(new(logLevel, eventId, formatter(state, exception), exception)); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataExportExecutionTests.Fence.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataExportExecutionTests.Fence.cs new file mode 100644 index 000000000..e7db021da --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataExportExecutionTests.Fence.cs @@ -0,0 +1,239 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Diagnostics.Metrics; +using FluentAssertions; +using LearnStack.Application.Jobs; +using LearnStack.Infrastructure.Jobs; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Time; +using Microsoft.Extensions.DependencyInjection; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.DataRequestSchemaSeed; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The export job's order of work (ADR-0107 § 2, § 5): the bundle is built and the retained references counted with +/// no fence held, and only then is the shared tenant fence taken and the request re-read before anything is written. +/// +public sealed partial class DataExportExecutionTests +{ + /// + /// While a participant is still building the bundle, another transaction takes the Identity tenant fence + /// exclusively within the two-second lock timeout every fenced operation runs under: the job holds no fence yet. + /// The export then completes. + /// + [Fact] + public async Task The_bundle_is_built_with_no_tenant_fence_held_so_an_exclusive_fence_is_granted_meanwhile() + { + await using var database = await OpenDatabaseAsync(); + var gate = new GateParticipant(); + await using var host = Host(services => services.AddSingleton(gate)); + var request = await FileExportAsync(SchemaFixture.TenantA, null, PersonA, LearnerMembershipA); + var job = await SubmitAsync(SchemaFixture.TenantA, null, request); + + var run = RunAsync(host.Services, job); + try + { + await gate.Entered.Task.WaitAsync(TimeSpan.FromSeconds(60)); + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + await ExecuteAsync(app, transaction, "SET LOCAL lock_timeout = '2s'"); + var waited = Stopwatch.StartNew(); + await LockAsync(app, transaction, SchemaFixture.TenantA, null, exclusive: true); + waited.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(2), "the job holds no tenant fence while it builds"); + run.IsCompleted.Should().BeFalse("the export is still building its bundle"); + (await ScalarAsync(app, transaction, "SELECT status FROM public.data_subject_requests WHERE id=@id", ("id", request))) + .Should().Be("requested", "nothing is written before the fence"); + await transaction.RollbackAsync(); + } + finally + { + gate.Release.TrySetResult(); + } + + var result = await run; + result.CommitAcknowledged.Should().BeTrue("disposition {0}, code {1}", result.Decision.Disposition, result.Decision.ErrorCode); + (await RequestAsync(SchemaFixture.TenantA, null, request)).Status.Should().Be("completed"); + } + + /// + /// A request cancelled while its bundle is being built is re-read under the fence and found cancelled: the run is a + /// recorded no-op, the built bundle is discarded, nothing is stored and the earlier artifact stays available. + /// + [Fact] + public async Task A_request_cancelled_while_its_bundle_is_built_is_a_recorded_no_op_and_the_bundle_is_discarded() + { + await using var database = await OpenDatabaseAsync(); + var gate = new GateParticipant(); + await using var host = Host(services => services.AddSingleton(gate)); + var request = await FileExportAsync(SchemaFixture.TenantA, null, PersonA, LearnerMembershipA); + var job = await SubmitAsync(SchemaFixture.TenantA, null, request); + var before = await ArtifactsAsync(SchemaFixture.TenantA, null, PersonA); + + var run = RunAsync(host.Services, job); + try + { + await gate.Entered.Task.WaitAsync(TimeSpan.FromSeconds(60)); + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, SchemaFixture.TenantA, null, null); + await StepAsync(app, transaction, request, "status='cancelled'"); + await transaction.CommitAsync(); + } + finally + { + gate.Release.TrySetResult(); + } + + var result = await run; + result.CommitAcknowledged.Should().BeTrue("disposition {0}, code {1}", result.Decision.Disposition, result.Decision.ErrorCode); + (await RequestAsync(SchemaFixture.TenantA, null, request)).Status.Should().Be("cancelled"); + var after = await ArtifactsAsync(SchemaFixture.TenantA, null, PersonA); + after.Should().BeEquivalentTo(before, "the built bundle is discarded: no artifact, no chunk, and no earlier artifact withdrawn"); + after.Single(artifact => artifact.Id == TenantWideA.Artifact!.Value).Status.Should().Be("available"); + (await AuditAsync(SchemaFixture.TenantA, null, "identity.data_request.fulfill_export", request.ToString("D"))) + .Should().Be(1, "the no-op still writes its MUST row"); + } + + /// + /// A worker whose clock lags the host that filed the request still completes the export: its transitions are + /// stamped no earlier than the request's own creation, which the aggregate and the request guard both require. + /// + [Fact] + public async Task A_worker_clock_behind_the_request_still_completes_the_export() + { + await using var database = await OpenDatabaseAsync(); + await using var host = Host(services => services.AddSingleton(new LaggingClock(TimeSpan.FromMinutes(3)))); + 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("disposition {0}, code {1}", result.Decision.Disposition, result.Decision.ErrorCode); + (await RequestAsync(SchemaFixture.TenantA, null, request)).Status.Should().Be("completed"); + } + + /// + /// A participant read that fails in the database is the retryable dependency_unavailable the job runtime + /// records, not an unexplained fault; the retry then completes. + /// + [Fact] + public async Task A_participant_database_failure_is_retried_as_dependency_unavailable() + { + await using var database = await OpenDatabaseAsync(); + await using var host = Host(services => services.AddSingleton(new UnavailableParticipant())); + 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.Decision.ErrorCode.Should().Be("dependency_unavailable"); + (await RunAsync(host.Services, await SubmitAsync(SchemaFixture.TenantA, null, request))).CommitAcknowledged.Should().BeTrue(); + (await RequestAsync(SchemaFixture.TenantA, null, request)).Status.Should().Be("completed"); + } + + /// + /// Standard 10: a purge attempt that throws is counted failed on the purge counter before its transaction + /// rolls back for the runtime's retry. + /// + [Fact] + public async Task A_purge_attempt_that_throws_is_counted_failed() + { + await using var database = await OpenDatabaseAsync(); + var measurements = new ConcurrentQueue(); + using var listener = new MeterListener + { + InstrumentPublished = (instrument, meter) => + { + if (instrument.Meter.Name == DataExportTelemetry.MeterName && instrument.Name == DataExportTelemetry.PurgeCounterName) + { + meter.EnableMeasurementEvents(instrument); + } + }, + }; + listener.SetMeasurementEventCallback((_, _, tags, _) => + { + foreach (var tag in tags) + { + measurements.Enqueue(tag.Key + "=" + tag.Value); + } + }); + listener.Start(); + await using var host = Host(services => services.AddScoped()); + var purge = await BackgroundJobRuntimeRows.InsertAsync(database.AppConnectionString, + "identity.data_export_purge_tenant.v1", tenant: SchemaFixture.TenantA, parameters: BackgroundJobPayloadContract.Serialize( + new DataExportPurgeParameters(TenantWideA.Artifact!.Value), typeof(DataExportPurgeParameters), BackgroundJobPayloadKind.Parameters)); + + var result = await RunAsync(host.Services, purge); + + result.CommitAcknowledged.Should().BeFalse(); + result.Decision.ErrorCode.Should().Be("dependency_unavailable"); + measurements.Should().Contain("outcome=failed"); + } + + /// Blocks inside the bundle build until the test releases it. + private sealed class GateParticipant : IUserDataParticipant + { + public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public string Key => "gate"; + + public async Task ExportAsync(UserDataSubject subject, IUserDataExportWriter writer, CancellationToken cancellationToken) + { + Entered.TrySetResult(); + await Release.Task.WaitAsync(TimeSpan.FromSeconds(60), cancellationToken); + } + + public Task> DescribeRetainedAsync(UserDataSubject subject, + CancellationToken cancellationToken) => Task.FromResult>([]); + } + + /// Fails its first export in the database driver, as a dropped connection or a statement timeout does. + private sealed class UnavailableParticipant : IUserDataParticipant + { + private int _calls; + + public string Key => "unavailable"; + + public Task ExportAsync(UserDataSubject subject, IUserDataExportWriter writer, CancellationToken cancellationToken) => + Interlocked.Increment(ref _calls) == 1 + ? throw new NpgsqlException("Synthetic participant read failure.") + : Task.CompletedTask; + + public Task> DescribeRetainedAsync(UserDataSubject subject, + CancellationToken cancellationToken) => Task.FromResult>([]); + } + + /// An artifact store whose every call is a storage failure. + private sealed class UnavailableArtifactStore : IDataExportArtifactStore + { + public bool CanOpen(string keyVersion) => false; + + public Task PutAsync(DataExportArtifactPut put, IAsyncEnumerable> plaintextChunks, + CancellationToken cancellationToken) => throw Unavailable(); + + public Task ReadMetadataAsync(DataExportArtifactLocator artifact, CancellationToken cancellationToken) => + throw Unavailable(); + + public Task ReadChunkAsync(DataExportArtifactLocator artifact, int index, CancellationToken cancellationToken) => + throw Unavailable(); + + public Task PurgeAsync(DataExportArtifactLocator artifact, DataExportArtifactStatus outcome, + CancellationToken cancellationToken) => throw Unavailable(); + + private static LearnStack.SharedKernel.Errors.InfrastructureException Unavailable() => new("Synthetic artifact storage outage."); + } + + private sealed class LaggingClock(TimeSpan lag) : IClock + { + public DateTimeOffset UtcNow => DateTimeOffset.UtcNow - lag; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataExportExecutionTests.Sections.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataExportExecutionTests.Sections.cs new file mode 100644 index 000000000..f11c7c139 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataExportExecutionTests.Sections.cs @@ -0,0 +1,257 @@ +using System.Collections.Concurrent; +using System.Diagnostics.Metrics; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// ADR-0107 § 3, § 6 and ADR-0106 § 5 with real seeds through the actual job: what the Identity and Tenancy sections +/// hold for a person who issued, accepted and consented, the retained counts of each kind, and the job's signals. +/// +public sealed partial class DataExportExecutionTests +{ + [Fact] + public async Task The_identity_and_tenancy_sections_and_the_retained_report_follow_the_subject_predicate() + { + await using var database = await OpenDatabaseAsync(); + var seeded = await SeedPersonAsync(); + var logs = new ExportLogs(); + await using var host = Host(services => services.AddSingleton>(logs.Logger())); + var request = await FileExportAsync(SchemaFixture.TenantA, null, PersonA, LearnerMembershipA); + var measurements = new ConcurrentBag<(string Instrument, double Value, string? Outcome)>(); + using var listener = new MeterListener + { + InstrumentPublished = (instrument, meter) => + { + if (instrument.Meter.Name == DataExportTelemetry.MeterName) + { + meter.EnableMeasurementEvents(instrument); + } + }, + }; + listener.SetMeasurementEventCallback((instrument, value, tags, _) => measurements.Add((instrument.Name, value, Outcome(tags)))); + listener.SetMeasurementEventCallback((instrument, value, tags, _) => measurements.Add((instrument.Name, value, Outcome(tags)))); + listener.Start(); + + var result = await RunAsync(host.Services, await SubmitAsync(SchemaFixture.TenantA, null, request)); + + result.CommitAcknowledged.Should().BeTrue("disposition {0}, code {1}, {2}", result.Decision.Disposition, result.Decision.ErrorCode, + string.Join(" | ", logs.Entries.Select(entry => entry.Message))); + var stored = (await ArtifactsAsync(SchemaFixture.TenantA, null, PersonA)).Single(artifact => artifact.Request == request); + var bytes = await ByteCountAsync(stored.Id); + using var bundle = await DecryptAsync(host.Services, SchemaFixture.TenantA, null, stored.Id); + var text = bundle.RootElement.GetRawText(); + var identity = bundle.RootElement.GetProperty("sections").GetProperty("identity"); + + // Issued: the invitee's address is another person's data and never leaves; the acceptor is a party. + var issued = identity.GetProperty("invitations_issued").EnumerateArray().ToList(); + issued.Should().HaveCount(3); + issued.Where(record => record.TryGetProperty("recipient_email", out var _)).Should().BeEmpty(); + issued.Select(record => record.GetProperty("accepted_by").ValueKind == JsonValueKind.Null ? null : record.GetProperty("accepted_by").GetString()) + .Should().BeEquivalentTo(new string?[] { "third_party", "self", null }); + text.Should().NotContain(seeded.InviteeAccepted).And.NotContain(seeded.InviteePending); + + // Accepted: the person's own address, and who issued it as a party. + var accepted = identity.GetProperty("invitations_accepted").EnumerateArray() + .ToDictionary(record => record.GetProperty("recipient_email").GetString()!); + accepted.Keys.Should().BeEquivalentTo([seeded.OfferAddress, seeded.SelfAddress]); + accepted[seeded.OfferAddress].GetProperty("issued_by").GetString().Should().Be("third_party"); + accepted[seeded.SelfAddress].GetProperty("issued_by").GetString().Should().Be("self"); + + // Custom fields: the stored value with its revision, labels and classification, although its consent was withdrawn. + var field = identity.GetProperty("memberships").EnumerateArray().Single().GetProperty("profile").GetProperty("custom_fields") + .EnumerateArray().Single(); + field.GetProperty("field").GetString().Should().Be("export-field"); + field.GetProperty("revision").GetInt32().Should().Be(1); + field.GetProperty("labels").GetProperty("en").GetString().Should().Be("Export field"); + field.GetProperty("classification").GetString().Should().Be("sensitive"); + field.GetProperty("consent_recorded").GetBoolean().Should().BeTrue(); + field.GetProperty("value").GetProperty("value").GetBoolean().Should().BeTrue("a withdrawn consent withholds ordinary disclosure, not the person's own export"); + + // Consents: the subject's, in this group, through their snapshot Membership; another person's and another + // organization's rows stay out, and the actor is a closed word. + var consents = bundle.RootElement.GetProperty("sections").GetProperty("tenancy").GetProperty("field_consents").EnumerateArray().ToList(); + consents.Select(record => record.GetProperty("state").GetString()).Should().Equal("granted", "withdrawn"); + consents.Should().OnlyContain(record => record.GetProperty("recorded_by").GetString() == "self" + && record.GetProperty("purpose").GetString() == "export-purpose"); + consents.Select(record => record.GetProperty("sequence").GetInt64()).Should().Equal(1, 2); + + var retained = JsonDocument.Parse((await RequestAsync(SchemaFixture.TenantA, null, request)).Result).RootElement; + long Count(string kind) => retained.GetProperty(kind).GetInt64(); + Count("consent_evidence").Should().Be(2, "the granted and the withdrawn act of the snapshot Membership"); + Count("invitation_record").Should().Be(4, "three issued (one also accepted by the subject) and one accepted from an administrator"); + Count("request_receipt").Should().Be(5, "two requests, their two artifacts and the seeded ticket"); + Count("attribution_reference").Should().BeGreaterThanOrEqualTo(4, "the three invitations the subject created and the offer they accepted"); + retained.TryGetProperty("federation_actor_reference", out _).Should().BeTrue("the tenant-wide group reports the tenant's federation rows"); + retained.TryGetProperty("provider_event_record", out _).Should().BeTrue(); + + // Signals: one completed run with the stored size; a log line with the request, kind, sizes and duration and no person. + measurements.Should().Contain((DataExportTelemetry.ExportCounterName, 1d, "completed")); + measurements.Should().Contain((DataExportTelemetry.BundleBytesHistogramName, (double)bytes, null)); + measurements.Should().Contain(measurement => measurement.Instrument == DataExportTelemetry.DurationHistogramName + && measurement.Outcome == "completed"); + var line = logs.Entries.Single(entry => entry.Id == 7501 && entry.Message.Contains(request.ToString(), StringComparison.Ordinal)); + line.Level.Should().Be(LogLevel.Information); + line.Message.Should().Contain("(export)").And.Contain(bytes + " bytes").And.Contain(stored.ChunkCount + " chunks"); + logs.Entries.Should().OnlyContain(entry => !entry.Message.Contains(PersonA.ToString(), StringComparison.OrdinalIgnoreCase) + && !entry.Message.Contains(AdminA.ToString(), StringComparison.OrdinalIgnoreCase) + && !entry.Message.Contains("@example.invalid", StringComparison.Ordinal)); + } + + private async Task ByteCountAsync(Guid artifact) + { + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + return await ScalarAsync(app, transaction, "SELECT byte_count FROM public.data_export_artifacts WHERE id=@id", ("id", artifact)); + } + + private static string? Outcome(ReadOnlySpan> tags) + { + foreach (var tag in tags) + { + if (tag.Key == "outcome") + { + return tag.Value as string; + } + } + + return null; + } + + private sealed record SeededPerson(string OfferAddress, string SelfAddress, string InviteeAccepted, string InviteePending); + + /// + /// In tenant A's tenant-wide group: three invitations PersonA issued (one accepted by AdminA, one by PersonA, one + /// pending), the seeded administrator offer accepted by PersonA, a custom-field value on PersonA's Membership whose + /// consent was then withdrawn, and AdminA's own consent. + /// + private async Task SeedPersonAsync() + { + var acceptedByAdmin = Guid.CreateVersion7(); + var acceptedBySelf = Guid.CreateVersion7(); + var pending = Guid.CreateVersion7(); + var seeded = new SeededPerson("invitation-" + InvitationSchemaSeed.TenantOfferA.ToString("N") + "@example.invalid", + "self-" + acceptedBySelf.ToString("N") + "@example.invalid", "admin-" + acceptedByAdmin.ToString("N") + "@example.invalid", + "pending-" + pending.ToString("N") + "@example.invalid"); + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + foreach (var key in new[] { AdminA, PersonA }.Select(user => IdentityAdvisoryLockKey.ForUser(UserId.From(user))).Order()) + { + await ExecuteAsync(app, transaction, "SELECT pg_advisory_xact_lock(@key)", ("key", key)); + } + + // Exclusive: the consent appends take the tenant fence exclusively, and the invitation and profile writes accept it. + await LockAsync(app, transaction, SchemaFixture.TenantA, null, true); + foreach (var (id, email) in new[] { (acceptedByAdmin, seeded.InviteeAccepted), (acceptedBySelf, seeded.SelfAddress), (pending, seeded.InviteePending) }) + { + await ExecuteAsync(app, transaction, """ + INSERT INTO public.invitations(id,tenant_id,organization_id,recipient_email,inviter_user_id,role_id, + pinned_role_version,status,generation_id,generation,generation_created_at,expires_at, + verifier_digest,entry_origin,entry_locale,current_delivery_job_id,submission_status,created_at,created_by) + VALUES(@id,@tenant,NULL,@email,@inviter,@role,0,'Pending',@generation,1, + now(),now()+interval '14 days',@digest, + 'https://manage.invitation.invalid','en',@job,'Queued',now(),@inviter) + """, ("id", id), ("tenant", SchemaFixture.TenantA), ("email", email), ("inviter", PersonA), + ("role", RoleId(SchemaFixture.TenantA, LearnStack.SharedKernel.Permissions.BuiltInRoleKey.Learner, + LearnStack.SharedKernel.Permissions.PermissionScope.Tenant)), + ("generation", Guid.CreateVersion7()), ("job", Guid.CreateVersion7()), ("digest", InvitationSchemaSeed.Digest(id))); + } + + foreach (var (id, acceptor, membership) in new[] + { + (acceptedByAdmin, AdminA, AdminMembershipA), (acceptedBySelf, PersonA, LearnerMembershipA), + (InvitationSchemaSeed.TenantOfferA, PersonA, LearnerMembershipA), + }) + { + await ExecuteAsync(app, transaction, """ + UPDATE public.invitations SET status='Accepted',consumed_verifier_digest=verifier_digest,verifier_digest=NULL, + accepted_by=@acceptor,result_membership_id=@member,acceptance_disposition='AlreadyMember',accepted_at=clock_timestamp(), + row_version=row_version+1,updated_at=clock_timestamp(),updated_by=@acceptor WHERE id=@id + """, ("acceptor", acceptor), ("member", membership), ("id", id)); + } + + // A Sensitive revision with its consent: granted, the value stored under it, then withdrawn; AdminA's own grant, + // and PersonA's grant in an organization, which a tenant-wide export must not show. + var definition = Guid.CreateVersion7(); + await ExecuteAsync(app, transaction, "SELECT pg_advisory_xact_lock(public.fn_identity_contextual_lock_key('tenant', @tenant))", + ("tenant", SchemaFixture.TenantA)); + await ExecuteAsync(app, transaction, """ + INSERT INTO public.tenant_custom_field_defs + (id,tenant_id,target_entity,key,schema_version,status,json_schema,labels_json,pii_category, + is_required,sort,maximum_value_bytes,purpose_key,notices_json,created_at,created_by,row_version) + VALUES(@definition,@tenant,'Membership','export-field',1,'Draft', + '{"$schema":"https://json-schema.org/draft/2020-12/schema","type":"object","properties":{"value":{"type":"boolean"}},"required":["value"],"additionalProperties":false}', + '{"en":"Export field"}','Sensitive',false,0,64,'export-purpose','{"en":"Export notice"}',clock_timestamp(),@actor,0); + UPDATE public.tenant_custom_field_defs SET status='Active',row_version=1 WHERE id=@definition; + """, ("definition", definition), ("tenant", SchemaFixture.TenantA), ("actor", SchemaFixture.Actor)); + var grant = Guid.CreateVersion7(); + foreach (var (id, organization, subject, membership, state, sequence, predecessor) in new (Guid, Guid?, Guid, Guid, string, int, Guid?)[] + { + (grant, null, PersonA, LearnerMembershipA, "Granted", 1, null), + (Guid.CreateVersion7(), SchemaFixture.OrgA1, PersonA, BranchMembershipA1, "Granted", 1, null), + (Guid.CreateVersion7(), null, AdminA, AdminMembershipA, "Granted", 1, null), + }) + { + await AppendConsentAsync(app, transaction, id, organization, subject, membership, definition, state, sequence, predecessor); + } + + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + await ExecuteAsync(app, transaction, """ + UPDATE public.membership_profiles SET custom_fields=jsonb_build_array(jsonb_build_object('conceptKey','export-field', + 'definitionId',@definition::text,'schemaVersion',1,'envelope',jsonb_build_object('value',true),'consentEvidenceId',@grant::text)) + WHERE membership_id=@member + """, ("definition", definition), ("grant", grant), ("member", LearnerMembershipA)); + await AppendConsentAsync(app, transaction, Guid.CreateVersion7(), null, PersonA, LearnerMembershipA, definition, "Withdrawn", 2, grant); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await transaction.CommitAsync(); + return seeded; + } + + private static async Task AppendConsentAsync(NpgsqlConnection app, NpgsqlTransaction transaction, Guid id, Guid? organization, + Guid subject, Guid membership, Guid definition, string state, int sequence, Guid? predecessor) + { + await ScopeAsync(app, transaction, SchemaFixture.TenantA, organization); + await ExecuteAsync(app, transaction, """ + INSERT INTO public.membership_field_consents + (id,tenant_id,organization_id,membership_id,subject_user_id,actor_user_id,definition_id, + definition_version,purpose_key,notice_locale,notice_hash,sequence,state,predecessor_id,predecessor_sequence, + created_at,created_by,row_version) + VALUES(@id,@tenant,@organization,@membership,@subject,@subject,@definition,1,'export-purpose', + 'en',encode(sha256(convert_to('Export notice','UTF8')),'hex'),@sequence,@state,@predecessor,@sequence - 1, + clock_timestamp(),@subject,0) + """, ("id", id), ("tenant", SchemaFixture.TenantA), ("organization", organization), ("membership", membership), + ("subject", subject), ("definition", definition), ("sequence", sequence), ("state", state), + ("predecessor", (object?)predecessor ?? DBNull.Value)); + } + + /// The export job's formatted lines, by event identifier and level. + private sealed class ExportLogs + { + private readonly ConcurrentQueue<(int Id, LogLevel Level, string Message)> _entries = new(); + + public IReadOnlyCollection<(int Id, LogLevel Level, string Message)> Entries => [.. _entries]; + + public ILogger Logger() => new Capture(_entries); + + private sealed class Capture(ConcurrentQueue<(int Id, LogLevel Level, string Message)> entries) : ILogger + { + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, + Func formatter) => entries.Enqueue((eventId.Id, logLevel, formatter(state, exception))); + } + } +} 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 000000000..dfd7c53fc --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataExportExecutionTests.cs @@ -0,0 +1,558 @@ +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"]); + // The retained references are counted before the artifact exists; the artifact this run stored is its own + // request receipt, so the stored count is every receipt row of the subject in the group after the commit. + JsonDocument.Parse(state.Result).RootElement.GetProperty("request_receipt").GetInt64() + .Should().Be(await ReceiptRowsAsync(SchemaFixture.TenantA, organization, PersonA)); + 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(); + failed.Decision.ErrorCode.Should().Be("unexpected_fault", "a participant's own refusal is not a dependency outage"); + (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.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(); + } + + 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.Id, loaded.Kind, 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 DataExportTestKit.CreateSeededDatabaseAsync(fixture.Postgres); + + 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 DataExportTestKit.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; + } + + /// The subject's request, artifact and ticket rows in exactly the group. + private async Task ReceiptRowsAsync(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); + return await ScalarAsync(app, transaction, """ + SELECT (SELECT count(*) FROM public.data_subject_requests + WHERE subject_user_id=@subject AND organization_id IS NOT DISTINCT FROM @organization::uuid) + + (SELECT count(*) FROM public.data_export_artifacts + WHERE subject_user_id=@subject AND organization_id IS NOT DISTINCT FROM @organization::uuid) + + (SELECT count(*) FROM public.data_export_tickets + WHERE created_by=@subject AND organization_id IS NOT DISTINCT FROM @organization::uuid) + """, ("subject", subject), ("organization", (object?)organization ?? DBNull.Value)); + } + + 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 Task OpenAppAsync() => DataExportTestKit.OpenAppAsync(_database!.AppConnectionString); + + [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>([]); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataExportParticipantTests.Attribution.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataExportParticipantTests.Attribution.cs new file mode 100644 index 000000000..e37d37048 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataExportParticipantTests.Attribution.cs @@ -0,0 +1,126 @@ +using FluentAssertions; +using LearnStack.Modules.Customization.Infrastructure.DataRequests; +using LearnStack.Modules.Customization.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.Modules.Identity.Infrastructure.DataRequests; +using LearnStack.Modules.Tenancy.Infrastructure.DataRequests; +using LearnStack.Modules.Tenancy.Infrastructure.Persistence; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.EntityFrameworkCore; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// ADR-0107 § 6 against the database: attribution_reference counts rows, any UserId attribution column +/// included, exactly in the group. +/// +public sealed partial class DataExportParticipantTests +{ + [Fact] + public async Task Attribution_counts_a_row_once_whatever_columns_name_the_subject_and_counts_a_non_auditable_updater() + { + await using var scope = await DataExportTestKit.OpenAsync(schema.Postgres.AppConnectionString, SchemaFixture.TenantA, null); + await using var customization = new CustomizationDbContext(new DbContextOptionsBuilder() + .UseNpgsql(scope.Connection).Options, new StaticTenantContextAccessor(scope.Context)); + await customization.Database.UseTransactionAsync(scope.Transaction); + await using var tenancy = new TenancyDbContext(new DbContextOptionsBuilder() + .UseNpgsql(scope.Connection).Options, new StaticTenantContextAccessor(scope.Context)); + await tenancy.Database.UseTransactionAsync(scope.Transaction); + var subject = new UserDataSubject(Guid.CreateVersion7(), DataRequestKind.Export, DataRequestOrigin.Self, UserId.From(PersonA), + new DataRequestScopeGroup(TenantId.From(SchemaFixture.TenantA), null), [LearnerMembershipA]); + var definitions = new CustomizationUserDataParticipant(customization, scope.Context); + var settings = new TenancyUserDataParticipant(tenancy, scope.Context); + var other = new UserDataSubject(Guid.CreateVersion7(), DataRequestKind.Export, DataRequestOrigin.Self, UserId.From(AdminA), + new DataRequestScopeGroup(TenantId.From(SchemaFixture.TenantA), null), [AdminMembershipA]); + var otherBefore = Attribution(await definitions.DescribeRetainedAsync(other, CancellationToken.None)) + + Attribution(await settings.DescribeRetainedAsync(other, CancellationToken.None)); + var definitionsBefore = Attribution(await definitions.DescribeRetainedAsync(subject, CancellationToken.None)); + var settingsBefore = Attribution(await settings.DescribeRetainedAsync(subject, CancellationToken.None)); + + // A definition the subject created and later updated: two attribution columns, one retained row. + var definition = Guid.CreateVersion7(); + await ExecuteAsync(scope.Connection, scope.Transaction, + "SELECT pg_advisory_xact_lock(public.fn_identity_contextual_lock_key('tenant', @tenant))", ("tenant", SchemaFixture.TenantA)); + await ExecuteAsync(scope.Connection, scope.Transaction, """ + INSERT INTO public.tenant_custom_field_defs + (id,tenant_id,target_entity,key,schema_version,status,json_schema,labels_json,pii_category, + is_required,sort,maximum_value_bytes,purpose_key,notices_json,created_at,created_by,row_version) + VALUES(@definition,@tenant,'Membership','attribution-proof',1,'Draft', + '{"type":"object","properties":{"value":{"type":"boolean"}},"required":["value"],"additionalProperties":false}', + '{"tr-TR":"Attribution proof"}','None',false,0,64,NULL,NULL,clock_timestamp(),@person,0); + UPDATE public.tenant_custom_field_defs SET status='Active',row_version=1,updated_at=clock_timestamp(),updated_by=@person + WHERE id=@definition; + """, ("definition", definition), ("tenant", SchemaFixture.TenantA), ("person", PersonA)); + + // A feature flag the subject last changed: an UpdatedBy outside the AuditableEntity set. + await ExecuteAsync(scope.Connection, scope.Transaction, """ + INSERT INTO public.tenant_feature_flags (tenant_id, key, value, updated_by) + VALUES (@tenant, 'attribution.proof', 'true', @person) + """, ("tenant", SchemaFixture.TenantA), ("person", PersonA)); + + Attribution(await definitions.DescribeRetainedAsync(subject, CancellationToken.None)).Should().Be(definitionsBefore + 1, + "the unit is the row: created and updated by the subject is one retained row"); + Attribution(await settings.DescribeRetainedAsync(subject, CancellationToken.None)).Should().Be(settingsBefore + 1, + "a UserId attribution column counts whether or not the entity is an AuditableEntity"); + (Attribution(await definitions.DescribeRetainedAsync(other, CancellationToken.None)) + + Attribution(await settings.DescribeRetainedAsync(other, CancellationToken.None))).Should().Be(otherBefore, + "another person's count is untouched by the subject's rows"); + await scope.Frame.FailAsync(); + } + + [Fact] + public async Task A_request_receipt_counts_for_whoever_filed_or_cancelled_it_once_per_row() + { + await using var scope = await DataExportTestKit.OpenAsync(schema.Postgres.AppConnectionString, SchemaFixture.TenantA, + SchemaFixture.OrgA1, [PersonA]); + // The retained report reads only; the erasure service is never reached here. + var participant = new IdentityUserDataParticipant(scope.Db, scope.Context, new MembershipFieldRevisionReader(null!), null!); + var group = new DataRequestScopeGroup(TenantId.From(SchemaFixture.TenantA), OrganizationId.From(SchemaFixture.OrgA1)); + var person = new UserDataSubject(Guid.CreateVersion7(), DataRequestKind.Export, DataRequestOrigin.Self, UserId.From(PersonA), + group, [BranchMembershipA1]); + var administrator = new UserDataSubject(Guid.CreateVersion7(), DataRequestKind.Export, DataRequestOrigin.Self, + UserId.From(AdminA), group, [Guid.CreateVersion7()]); + var personBefore = Receipts(await participant.DescribeRetainedAsync(person, CancellationToken.None)); + var administratorBefore = await participant.DescribeRetainedAsync(administrator, CancellationToken.None); + + // The person's own request, cancelled by the administrator: the administrator is only its updater. + var own = Guid.CreateVersion7(); + await DataRequestSchemaSeed.InsertRequestAsync(scope.Connection, scope.Transaction, own, SchemaFixture.TenantA, SchemaFixture.OrgA1, + PersonA, [BranchMembershipA1]); + await ExecuteAsync(scope.Connection, scope.Transaction, """ + UPDATE public.data_subject_requests SET status='cancelled',row_version=row_version+1,updated_at=now(),updated_by=@admin + WHERE id=@id + """, ("id", own), ("admin", AdminA)); + + // The administrator's request about the person, which the administrator then cancels: requester, creator and + // updater all name the administrator, and it is still one row. + var filed = Guid.CreateVersion7(); + await ExecuteAsync(scope.Connection, scope.Transaction, """ + INSERT INTO public.data_subject_requests(id,tenant_id,organization_id,kind,origin,subject_user_id,requester_user_id, + status,membership_snapshot,created_at,created_by) + VALUES(@id,@tenant,@organization,'export','administrator',@subject,@admin,'requested',@snapshot::jsonb,now(),@admin); + UPDATE public.data_subject_requests SET status='cancelled',row_version=row_version+1,updated_at=now(),updated_by=@admin + WHERE id=@id; + """, ("id", filed), ("tenant", SchemaFixture.TenantA), ("organization", SchemaFixture.OrgA1), ("subject", PersonA), + ("admin", AdminA), ("snapshot", DataRequestSchemaSeed.Snapshot(BranchMembershipA1))); + + var administratorAfter = await participant.DescribeRetainedAsync(administrator, CancellationToken.None); + Receipts(administratorAfter).Should().Be(Receipts(administratorBefore) + 2, + "a request the administrator filed or cancelled survives naming them, once per row"); + Attribution(administratorAfter).Should().Be(Attribution(administratorBefore), + "the receipts are reported as request_receipt and never as attribution too"); + Receipts(await participant.DescribeRetainedAsync(person, CancellationToken.None)).Should().Be(personBefore + 2, + "both requests are about the person"); + await scope.Frame.FailAsync(); + } + + private static long Receipts(IReadOnlyCollection retained) => + retained.Single(item => item.Kind == RetainedReferenceKind.RequestReceipt).Count; + + private static long Attribution(IReadOnlyCollection retained) => + retained.Single(item => item.Kind == RetainedReferenceKind.AttributionReference).Count; +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataExportParticipantTests.AuditStatements.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataExportParticipantTests.AuditStatements.cs new file mode 100644 index 000000000..5c88c9355 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataExportParticipantTests.AuditStatements.cs @@ -0,0 +1,312 @@ +using System.Reflection; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Modules.Audit.Infrastructure.DataRequests; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using Npgsql; +using NpgsqlTypes; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The audit section's reach as the row policy really draws it, and its index-served statements against the single +/// predicate they replaced (ADR-0107 § 3, § 6; ADR-0108 § 4). +/// +public sealed partial class DataExportParticipantTests +{ + // The statements as they were before the union rewrite: the oracle the rewrite must agree with. + private const string OracleSelection = """ + 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 OracleCount = "SELECT count(*) FROM public.audit_log WHERE " + OracleSelection; + + private const string OraclePage = """ + SELECT id FROM public.audit_log + WHERE (@first OR ("timestamp", id) < (@after_timestamp, @after_id)) + """ + " AND " + OracleSelection + """ + + ORDER BY "timestamp" DESC, id DESC LIMIT @page + """; + + private const string OracleRetained = """ + 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 + """ + " " + OracleSelection; + + private const string OracleMetadata = """ + 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) + """; + + [Theory] + [InlineData("tenant_wide_self")] + [InlineData("other_organization_self")] + [InlineData("organization_administrator")] + public async Task The_audit_section_states_its_reach_and_shows_no_other_organizations_rows( + string group) + { + var (organization, origin, membership, reach, expected) = group switch + { + "tenant_wide_self" => ((Guid?)null, DataRequestOrigin.Self, LearnerMembershipA, + AuditUserDataParticipant.ReachTenantLevelOnly, new[] { "tenant_level" }), + "other_organization_self" => (SchemaFixture.OrgA2, DataRequestOrigin.Self, BranchMembershipA2, + AuditUserDataParticipant.ReachOrganizationAndTenantLevel, new[] { "tenant_level", "organization_b" }), + _ => (SchemaFixture.OrgA1, DataRequestOrigin.Administrator, BranchMembershipA1, + AuditUserDataParticipant.ReachOrganizationOnly, new[] { "organization_a" }), + }; + await using var scope = await DataExportTestKit.OpenAsync(schema.Postgres.AppConnectionString, SchemaFixture.TenantA, organization); + foreach (var (name, rowOrganization) in new (string, Guid?)[] + { + ("tenant_level", null), ("organization_a", SchemaFixture.OrgA1), ("organization_b", SchemaFixture.OrgA2), + }) + { + await InsertAuditAsync(scope, rowOrganization, PersonA, "fixture.reach." + name, "Invitation", Guid.CreateVersion7().ToString("D")); + } + + await ScopeAsync(scope.Connection, scope.Transaction, SchemaFixture.TenantA, organization); + var participant = new AuditUserDataParticipant(scope.Unit, scope.Context); + var subject = new UserDataSubject(Guid.CreateVersion7(), DataRequestKind.Export, origin, UserId.From(PersonA), + new DataRequestScopeGroup(TenantId.From(SchemaFixture.TenantA), organization is { } org ? OrganizationId.From(org) : null), + [membership]); + var writer = new CollectingWriter(); + + await participant.ExportAsync(subject, writer, CancellationToken.None); + + AuditUserDataParticipant.ReachOf(subject).Should().Be(reach); + writer.All[0].Collection.Should().Be(AuditUserDataParticipant.ScopeCollection); + writer.All[0].Record.Should().Be("{\"reach\":\"" + reach + "\",\"complete\":false}", + "the reach is one closed word and a closed flag, and no current reach is the person's whole audit trail"); + writer.All.Count(record => record.Collection == AuditUserDataParticipant.ScopeCollection).Should().Be(1); + writer.Records.Select(record => JsonDocument.Parse(record).RootElement.GetProperty("operation").GetString()!) + .Where(operation => operation.StartsWith("fixture.reach.", StringComparison.Ordinal)) + .Select(operation => operation["fixture.reach.".Length..]) + .Should().BeEquivalentTo(expected, + "the job's transaction holds no tenant-wide read witness, so a self export does not reach the person's rows " + + "recorded in another organization; only an export filed in that organization's group, which needs a " + + "Membership there, does"); + await scope.Frame.FailAsync(); + } + + [Theory] + [InlineData("self", "organization")] + [InlineData("administrator", "organization")] + [InlineData("self", "tenant_wide")] + [InlineData("administrator", "tenant_wide")] + public async Task The_index_served_audit_statements_select_exactly_what_the_single_predicate_selected(string origin, string group) + { + var tenantWide = group == "tenant_wide"; + Guid? organization = tenantWide ? null : SchemaFixture.OrgA1; + // The subject's Membership of the group, and one of another group the metadata may name without matching. + var membership = tenantWide ? LearnerMembershipA : BranchMembershipA1; + var foreign = tenantWide ? BranchMembershipA1 : LearnerMembershipA; + await using var scope = await DataExportTestKit.OpenAsync(schema.Postgres.AppConnectionString, SchemaFixture.TenantA, organization); + var other = Guid.CreateVersion7().ToString("D"); + var subjectText = PersonA.ToString("D"); + var memberships = $$$"""{"authorization":{"memberships":["{{{membership}}}"]}}"""; + var tie = DateTime.UtcNow.AddMinutes(-5); + var rows = new (Guid? Organization, Guid Actor, string Type, string Entity, string? Metadata, DateTime? At)[] + { + (SchemaFixture.OrgA1, PersonA, "Invitation", Guid.CreateVersion7().ToString("D"), memberships, null), + (null, PersonA, "Membership", membership.ToString("D"), $$$"""{"authorization":{"memberships":["{{{foreign}}}"]}}""", null), + (SchemaFixture.OrgA1, AdminA, "Membership", membership.ToString("D"), null, null), + (SchemaFixture.OrgA2, AdminA, "Membership", membership.ToString("D"), null, null), + (null, AdminA, "Membership", other, null, null), + (null, AdminA, "Membership", membership.ToString("D"), null, null), + (null, UserId.SystemActor.Value, "User", subjectText, $$$"""{"causal_actor_user_id":"{{{PersonA}}}"}""", null), + (SchemaFixture.OrgA1, UserId.SystemActor.Value, "Course", other, $$$"""{"authorization":{"causal_actor_user_id":"{{{PersonA}}}"}}""", null), + (null, UserId.SystemActor.Value, "Course", other, $$$"""{"provider_event":{"affected_user_id":"{{{PersonA}}}"}}""", null), + (SchemaFixture.OrgA1, UserId.SystemActor.Value, "Course", other, $$$"""{"causal_actor_user_id":"{{{PersonB}}}"}""", null), + (SchemaFixture.OrgA1, PersonA, "Course", other, $$$"""{"causal_actor_user_id":"{{{PersonA}}}"}""", null), + (SchemaFixture.OrgA2, UserId.SystemActor.Value, "Course", other, $$$"""{"causal_actor_user_id":"{{{PersonA}}}"}""", null), + (SchemaFixture.OrgA1, PersonA, "Invitation", other, null, tie), + (null, PersonA, "Invitation", other, null, tie), + (SchemaFixture.OrgA1, AdminA, "Membership", membership.ToString("D"), null, tie), + (null, AdminB, "User", subjectText, null, tie), + // Newest: another organization's keyed row naming the subject, which no reach of this group shows. + (SchemaFixture.OrgA2, UserId.SystemActor.Value, "Course", other, $$$"""{"provider_event":{"affected_user_id":"{{{PersonA}}}"}}""", null), + }; + foreach (var (rowOrganization, actor, type, entity, json, at) in rows) + { + await InsertAuditAsync(scope, rowOrganization, actor, "fixture.statements", type, entity, json, at); + } + + await ScopeAsync(scope.Connection, scope.Transaction, SchemaFixture.TenantA, organization); + var subject = new UserDataSubject(Guid.CreateVersion7(), DataRequestKind.Export, + origin == "self" ? DataRequestOrigin.Self : DataRequestOrigin.Administrator, UserId.From(PersonA), + new DataRequestScopeGroup(TenantId.From(SchemaFixture.TenantA), organization is { } org ? OrganizationId.From(org) : null), + [membership]); + + var count = await ScalarAsync(scope, Statement("CountSql"), subject); + count.Should().Be(await ScalarAsync(scope, OracleCount, subject)).And.BeGreaterThanOrEqualTo(5); + (await RetainedAsync(scope, Statement("RetainedSql"), subject)).Should().Be(await RetainedAsync(scope, OracleRetained, subject)); + var metadata = await ScalarAsync(scope, Statement("MetadataSql"), subject, AuditUserDataParticipant.MetadataScanWindow); + metadata.Should().Be(await ScalarAsync(scope, OracleMetadata, subject)).And.BeGreaterThan(1); + var paged = await PagesAsync(scope, Statement("PageSql"), subject, rewritten: true); + paged.Should().Equal(await PagesAsync(scope, OraclePage, subject, rewritten: false), + "the union pages in the same order with the same keyset ties, a row two branches select once"); + paged.Should().OnlyHaveUniqueItems().And.HaveCount((int)count); + + // The window bounds the causal and affected references; a smaller window only ever undercounts. The newest + // keyed row of the tenant is another organization's, so a window of one still reaches the reach's newest + // keyed row: the window is counted inside the reach, never across the tenant. + var bounded = await ScalarAsync(scope, Statement("MetadataSql"), subject, 1); + bounded.Should().BeLessThan(metadata).And.BeGreaterThanOrEqualTo(1); + + // Every branch has an index path. Which index the planner takes on a table this small depends on the + // statistics other tests leave behind, so only the absence of a sequential scan is asserted; the indexes + // themselves are pinned against the migration by AuditUserDataParticipantTests. + await ExecuteAsync(scope.Connection, scope.Transaction, "SET LOCAL enable_seqscan = off"); + foreach (var statement in new[] { "CountSql", "PageSql", "RetainedSql", "MetadataSql" }) + { + var nodes = await PlanAsync(scope, Statement(statement), subject); + nodes.Where(node => node.Relation == "audit_log").Should().NotBeEmpty(statement) + .And.NotContain(node => node.Type == "Seq Scan", "{0} has an index path for every branch", statement); + } + + await scope.Frame.FailAsync(); + } + + private static string Statement(string name) => (string)typeof(AuditUserDataParticipant) + .GetField(name, BindingFlags.Static | BindingFlags.NonPublic)!.GetRawConstantValue()!; + + private static async Task InsertAuditAsync(DataExportTestKit.GroupScope scope, Guid? organization, Guid actor, string operation, + string type, string entity, string? metadata = null, DateTime? at = null) + { + await ScopeAsync(scope.Connection, scope.Transaction, SchemaFixture.TenantA, 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,metadata) + VALUES(@id,COALESCE(@at::timestamptz,clock_timestamp()),@tenant,@organization,@actor,'identity',@operation,'SecurityEvent', + 'Must',@type,@entity,'success',@metadata::jsonb) + """, ("id", Guid.CreateVersion7()), ("at", (object?)at ?? DBNull.Value), ("tenant", SchemaFixture.TenantA), + ("organization", (object?)organization ?? DBNull.Value), ("actor", actor), ("operation", operation), ("type", type), + ("entity", entity), ("metadata", (object?)metadata ?? DBNull.Value)); + } + + private static NpgsqlCommand Command(DataExportTestKit.GroupScope scope, string sql, UserDataSubject subject) + { + var command = new NpgsqlCommand(sql, scope.Connection, scope.Transaction); + command.Parameters.AddWithValue("tenant", SchemaFixture.TenantA); + 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 static async Task ScalarAsync(DataExportTestKit.GroupScope scope, string sql, UserDataSubject subject, int? window = null) + { + await using var command = Command(scope, sql, subject); + if (window is { } rows) + { + command.Parameters.AddWithValue("window", rows); + } + + return (long)(await command.ExecuteScalarAsync())!; + } + + private static async Task<(long Actor, long Entity)> RetainedAsync(DataExportTestKit.GroupScope scope, string sql, UserDataSubject subject) + { + await using var command = Command(scope, sql, subject); + await using var row = await command.ExecuteReaderAsync(); + (await row.ReadAsync()).Should().BeTrue(); + return (row.GetInt64(0), row.GetInt64(1)); + } + + /// Every page of two rows, the keyset carried from each page's last row. + private static async Task> PagesAsync(DataExportTestKit.GroupScope scope, string sql, UserDataSubject subject, bool rewritten) + { + var ids = new List(); + (DateTime Timestamp, Guid Id)? cursor = null; + while (true) + { + var page = new List(); + await using (var command = Command(scope, sql, subject)) + { + command.Parameters.AddWithValue("page", 2); + if (!rewritten) + { + command.Parameters.AddWithValue("first", cursor is null); + } + + command.Parameters.AddWithValue("after_timestamp", NpgsqlDbType.TimestampTz, + cursor?.Timestamp ?? (rewritten ? new DateTime(9999, 12, 31, 0, 0, 0, DateTimeKind.Utc) : DateTime.UnixEpoch)); + command.Parameters.AddWithValue("after_id", cursor?.Id ?? (rewritten ? Guid.Parse("ffffffff-ffff-ffff-ffff-ffffffffffff") : Guid.Empty)); + await using var reader = await command.ExecuteReaderAsync(); + while (await reader.ReadAsync()) + { + page.Add(reader.GetGuid(0)); + } + } + + if (page.Count == 0) + { + return ids; + } + + ids.AddRange(page); + var last = page[^1]; + var timestamp = await ScalarTimestampAsync(scope, last); + cursor = (timestamp, last); + if (page.Count < 2) + { + return ids; + } + } + } + + private static async Task ScalarTimestampAsync(DataExportTestKit.GroupScope scope, Guid id) + { + await using var command = new NpgsqlCommand("SELECT \"timestamp\" FROM public.audit_log WHERE id=@id", scope.Connection, scope.Transaction); + command.Parameters.AddWithValue("id", id); + return DateTime.SpecifyKind((DateTime)(await command.ExecuteScalarAsync())!, DateTimeKind.Utc); + } + + private sealed record PlanNode(string Type, string? Relation, string? Index); + + private static async Task> PlanAsync(DataExportTestKit.GroupScope scope, string sql, UserDataSubject subject) + { + await using var command = Command(scope, "EXPLAIN (FORMAT JSON) " + sql, subject); + command.Parameters.AddWithValue("window", AuditUserDataParticipant.MetadataScanWindow); + command.Parameters.AddWithValue("page", 200); + command.Parameters.AddWithValue("after_timestamp", NpgsqlDbType.TimestampTz, new DateTime(9999, 12, 31, 0, 0, 0, DateTimeKind.Utc)); + command.Parameters.AddWithValue("after_id", Guid.Parse("ffffffff-ffff-ffff-ffff-ffffffffffff")); + using var plan = JsonDocument.Parse((string)(await command.ExecuteScalarAsync())!); + var nodes = new List(); + Walk(plan.RootElement[0].GetProperty("Plan")); + return nodes; + + void Walk(JsonElement node) + { + nodes.Add(new PlanNode(node.GetProperty("Node Type").GetString()!, + node.TryGetProperty("Relation Name", out var relation) ? relation.GetString() : null, + node.TryGetProperty("Index Name", out var index) ? index.GetString() : null)); + if (node.TryGetProperty("Plans", out var children)) + { + foreach (var child in children.EnumerateArray()) + { + Walk(child); + } + } + } + } +} 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 000000000..9f60b9a04 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataExportParticipantTests.cs @@ -0,0 +1,152 @@ +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 partial 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); + + writer.All[0].Collection.Should().Be(AuditUserDataParticipant.ScopeCollection); + JsonDocument.Parse(writer.All[0].Record).RootElement.GetProperty("reach").GetString().Should().Be(origin == "self" + ? AuditUserDataParticipant.ReachOrganizationAndTenantLevel : AuditUserDataParticipant.ReachOrganizationOnly); + 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.All[0].Collection.Should().Be(AuditUserDataParticipant.ScopeCollection, "the reach is stated before the entries"); + 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 the audit entries, and reports the section cap after admit of them. + private sealed class CollectingWriter(int admit = int.MaxValue) : IUserDataExportWriter + { + /// The entries records. + public List Records { get; } = []; + + /// Every record of every collection, in order. + public List<(string Collection, string Record)> All { 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) + { + var text = System.Text.Encoding.UTF8.GetString(utf8JsonRecord.Span); + if (collection != AuditUserDataParticipant.Collection) + { + All.Add((collection, text)); + return ValueTask.FromResult(UserDataExportAppend.Appended); + } + + if (Records.Count >= admit) + { + return ValueTask.FromResult(UserDataExportAppend.SectionCapReached); + } + + Records.Add(text); + All.Add((collection, text)); + 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 000000000..de880508a --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataExportTestKit.cs @@ -0,0 +1,136 @@ +using FluentAssertions; +using LearnStack.Application.Jobs; +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.Jobs; +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-0106/0107 data-request proof needs outside a request pipeline: an announced application-role unit of +/// work over one group, the Identity context on it, the fixture's export key ring, and the connections, disposable +/// databases and job claims the proofs share. +/// +internal static class DataExportTestKit +{ + internal static string KeyRing => InvitationEmailFixtureConfiguration.Values[DataExportCipher.KeyRingSecret]!; + + internal static DataExportCipher Cipher() => new(new FixedSecrets(KeyRing)); + + /// A cipher over another key ring, such as one a key has left. + internal static DataExportCipher Cipher(string ring) => new(new FixedSecrets(ring)); + + /// A connection as learnstack_app: a proof that runs as any other role proves nothing about the policies. + internal static async Task OpenAppAsync(string appConnectionString) + { + var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(appConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + return app; + } + + /// A disposable copy of the seeded schema with both seeded tenants and the Identity fixture rows. + internal static async Task CreateSeededDatabaseAsync(PostgresFixture postgres) + { + var database = await DisposableSchemaDatabase.CreateAsync(postgres); + await BackgroundJobSchemaSeed.SeedTenantsAsync(database.AppConnectionString); + await IdentityMembershipFixture.SeedSchemaAsync(database.MigrationConnectionString, database.AppConnectionString); + return database; + } + + /// + /// Runs behind a savepoint, expects the database to refuse it, and rolls the savepoint back so + /// the transaction can carry on. + /// + internal 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; + } + + /// + /// An application-role transaction announced for one group, with the group's Identity context; unless + /// is false, holding the given User fences and the shared tenant fence as its one lock plan. + /// + internal static async Task OpenAsync(string appConnectionString, Guid tenant, Guid? organization, + IEnumerable? userFences = null, bool fenced = true) + { + 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); + if (fenced) + 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 + { + } + } + + /// The routing claim the job runtime hands a worker, read back from the stored job by the dispatcher role. + internal 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 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/DataRequestHttpTests.Administration.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Administration.cs new file mode 100644 index 000000000..ef161d664 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Administration.cs @@ -0,0 +1,228 @@ +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(); + + // While the subject holds a readable artifact, a new administrator export would withdraw it: refused. + using (var refused = await SendAsync(client, admin, AdminPath + "/exports", "POST", body, key: Key())) + (await ProblemAsync(refused, HttpStatusCode.Conflict, "business_rule_violation")).GetProperty("errors").GetProperty("$")[0] + .GetProperty("key").GetString().Should().Be("lockey_subject_export_available"); + + // 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"); + + // With no readable artifact left, the administrator may file again. + var (again, _) = await FileExportAsync(client, admin, path: AdminPath + "/exports", body: body); + again.Should().NotBe(id); + } + + [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.Closure.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Closure.cs new file mode 100644 index 000000000..ad98459c9 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Closure.cs @@ -0,0 +1,350 @@ +using System.Globalization; +using System.Net; +using System.Text.Json; +using FluentAssertions; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.Tools.Seeder; +using Microsoft.Extensions.DependencyInjection; +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 § 3, § 7, § 10, § 11 and ADR-0107 § 7 through the actual Program: the person alone files an account closure +/// from their originating group, on its own routes, answered 202 scheduled with its execution time and no job; +/// it is cancellable until its Begin commits, even after its execution time; an administrator neither files, lists, +/// reads nor cancels one; and a Suspended person files, reads and cancels one through the retained entry. +/// +public sealed partial class DataRequestHttpTests +{ + [Fact] + public async Task A_person_files_a_closure_scheduled_with_no_job_and_may_cancel_it_even_after_its_execution_time() + { + await using var proof = await CreatePreparedAsync(); + using var client = proof.Client(); + var learner = proof.Token(EnglishLearner, English); + var tenant = English.TenantId.Value; + + const string Jobs = "SELECT count(*) FROM public.background_jobs"; + var jobsBefore = await CountAsync(proof, tenant, null, Jobs); + var (id, version) = await FileClosureAsync(client, learner); + var receipt = await ReceiptAsync(client, learner, id); + receipt.GetProperty("kind").GetString().Should().Be("closure"); + receipt.GetProperty("origin").GetString().Should().Be("self"); + receipt.GetProperty("status").GetString().Should().Be("scheduled"); + receipt.GetProperty("lastRefusal").ValueKind.Should().Be(JsonValueKind.Null); + Instant(receipt, "executeAt").Should().Be(Instant(receipt, "createdAt") + TimeSpan.FromHours(24), "a closure waits 24 hours"); + (await AuditCountAsync(proof, tenant, null, "identity.data_request.create_closure", id.ToString("D"))).Should().Be(1); + (await CountAsync(proof, tenant, null, "SELECT count(*) FROM public.background_jobs WHERE parameters::text LIKE '%' || @request || '%'", + ("request", id.ToString("D")))).Should().Be(0, "a closure is executed by the operator's Begin, never by a job"); + (await CountAsync(proof, tenant, null, Jobs)).Should().Be(jobsBefore, "filing queued nothing at all"); + + using (var second = await SendAsync(client, learner, OwnPath + "/closures", "POST", "{}", key: Key())) + (await ProblemAsync(second, HttpStatusCode.Conflict, "business_rule_violation")).GetProperty("errors").GetProperty("$")[0] + .GetProperty("key").GetString().Should().Be("lockey_request_already_active", "one active closure per subject and group"); + var (erasure, _) = await FileErasureAsync(client, learner, OwnPath + "/erasures", "{}"); + erasure.Should().NotBe(id, "a closure and an erasure of the group are different kinds"); + + // ADR-0106 § 11: the execution time ends no closure's cancellation; only its Begin does. + await DataErasureTestKit.BackdateAsync(proof.Database.MigrationConnectionString, tenant, null, id); + var due = await ReceiptAsync(client, learner, id); + Instant(due, "executeAt").Should().BeBefore(DateTimeOffset.UtcNow, "the closure is past its execution time"); + due.GetProperty("status").GetString().Should().Be("scheduled", "no job moves a due closure"); + using (var cancelled = await SendAsync(client, learner, OwnPath + "/" + id.ToString("D") + "/cancellations", "POST", "{}", + version: version, key: Key())) + await JsonAsync(cancelled); + (await ReceiptAsync(client, learner, id)).GetProperty("status").GetString().Should().Be("cancelled"); + (await AuditCountAsync(proof, tenant, null, "identity.data_request.cancel", id.ToString("D"))).Should().Be(1); + var cancelledVersion = Version(await ReceiptAsync(client, learner, id)); + using (var again = await SendAsync(client, learner, OwnPath + "/" + id.ToString("D") + "/cancellations", "POST", "{}", + version: cancelledVersion, key: Key())) + (await ProblemAsync(again, HttpStatusCode.Conflict, "business_rule_violation")).GetProperty("errors").GetProperty("$")[0] + .GetProperty("key").GetString().Should().Be("lockey_data_request_not_cancellable"); + + var (refiled, _) = await FileClosureAsync(client, learner); + refiled.Should().NotBe(id, "a cancelled closure frees its slot"); + } + + /// + /// ADR-0106 § 10: a repeated closure filing with the same key answers the stored receipt and files nothing again; the + /// same key on the erasure route is a key reuse, not a replay, and files no erasure. + /// + [Fact] + public async Task A_closure_filing_replays_exactly_and_the_same_key_on_an_erasure_is_a_key_reuse() + { + await using var proof = await CreatePreparedAsync(); + using var client = proof.Client(); + var tenant = English.TenantId.Value; + var learner = proof.Token(EnglishLearner, English); + var key = Key(); + + Guid id; + string location; + string etag; + using (var first = await SendAsync(client, learner, OwnPath + "/closures", "POST", "{}", key: key)) + { + id = Guid.Parse((await JsonAsync(first, HttpStatusCode.Accepted)).GetProperty("id").GetString()!); + location = first.Headers.Location!.OriginalString; + etag = first.Headers.ETag!.Tag; + first.Headers.Contains("Idempotency-Replayed").Should().BeFalse(); + } + + using (var replay = await SendAsync(client, learner, OwnPath + "/closures", "POST", "{}", key: key)) + { + var replayed = await JsonAsync(replay, HttpStatusCode.Accepted); + replayed.EnumerateObject().Select(property => (property.Name, property.Value.GetString())).Should() + .Equal(("id", id.ToString("D")), ("kind", "closure"), ("status", "scheduled"), ("version", "0")); + replay.Headers.GetValues("Idempotency-Replayed").Should().Equal("true"); + replay.Headers.Location!.OriginalString.Should().Be(location); + replay.Headers.ETag!.Tag.Should().Be(etag); + } + + using (var reused = await SendAsync(client, learner, OwnPath + "/erasures", "POST", "{}", key: key)) + await ProblemAsync(reused, HttpStatusCode.Conflict, "idempotency_key_reuse"); + using (var changed = await SendAsync(client, learner, OwnPath + "/closures", "POST", "{\"reason\":\"x\"}", key: Key())) + await ProblemAsync(changed, HttpStatusCode.BadRequest, "validation_failed"); + (await CountAsync(proof, tenant, null, "SELECT count(*) FROM public.data_subject_requests WHERE kind='closure'")).Should().Be(1); + (await CountAsync(proof, tenant, null, "SELECT count(*) FROM public.data_subject_requests WHERE kind='erasure'")).Should().Be(0); + (await AuditCountAsync(proof, tenant, null, "identity.data_request.create_closure")).Should().Be(1, "a replay audits nothing"); + } + + /// + /// ADR-0106 § 7, ADR-0107 § 7: a hold refuses a closure with its closed code and files nothing; the tenant's only + /// eligible administrator still files one (that check is the Begin's); and a person with no Membership in a group has + /// no closure route there, live or retained. + /// + [Fact] + public async Task A_hold_refuses_a_closure_the_sole_administrator_files_one_and_a_group_without_a_membership_is_absent() + { + await using var proof = await CreatePreparedAsync(); + var tenant = English.TenantId.Value; + var branch = English.DefaultOrganization.OrganizationId; + using (var held = proof.Client(services => services.AddSingleton(new AlwaysHold()))) + using (var own = await SendAsync(held, proof.Token(EnglishLearner, English), OwnPath + "/closures", "POST", "{}", key: Key())) + (await ProblemAsync(own, HttpStatusCode.Conflict, "business_rule_violation")).GetProperty("errors").GetProperty("$")[0] + .GetProperty("key").GetString().Should().Be("lockey_blocked_hold"); + (await CountAsync(proof, tenant, null, "SELECT count(*) FROM public.data_subject_requests")).Should().Be(0); + (await AuditCountAsync(proof, tenant, null, "identity.data_request.create_closure")).Should().Be(0); + + using var client = RetainedClient(proof); + var (sole, _) = await FileClosureAsync(client, proof.Token(EnglishAdmin, English)); + (await AuditCountAsync(proof, tenant, null, "identity.data_request.create_closure", sole.ToString("D"))).Should().Be(1, + "the last-administrator check is the Begin's, across every participant tenant"); + + using (var live = await SendAsync(client, proof.Token(EnglishLearner, English, organization: true, claimedOrganization: branch), + OwnPath + "/closures", "POST", "{}", key: Key())) + await ProblemAsync(live, HttpStatusCode.NotFound, "not_found"); + using (var retained = await EntrySendAsync(client, NativeToken(proof, EnglishLearner), "/closures?group=" + branch.Value.ToString("D"), + "{}", Key())) + await ProblemAsync(retained, HttpStatusCode.NotFound, "not_found"); + // An organization context also sees the tenant-wide group's rows (the canonical policy), so the branch is named. + (await CountAsync(proof, tenant, branch.Value, "SELECT count(*) FROM public.data_subject_requests WHERE organization_id=@branch", + ("branch", branch.Value))).Should().Be(0, "the refused filings wrote no request in the branch"); + } + + /// + /// ADR-0106 § 3, ADR-0107 § 7: no administrator creates or reads a closure. The person's closure is absent from the + /// administrator's list, its read and its cancellation, its receipt is never disclosed to them, and the administrator's + /// surface has no closure route. + /// + [Fact] + public async Task The_administrator_neither_files_lists_reads_nor_cancels_a_closure() + { + await using var proof = await CreatePreparedAsync(); + using var client = proof.Client(); + var admin = proof.Token(EnglishAdmin, English); + var learner = proof.Token(EnglishLearner, English); + var (id, version) = await FileClosureAsync(client, learner); + var (erasure, _) = await FileErasureAsync(client, learner, OwnPath + "/erasures", "{}"); + + using (var list = await SendAsync(client, admin, AdminPath)) + (await JsonAsync(list)).GetProperty("items").EnumerateArray().Select(item => item.GetProperty("id").GetString()) + .Should().Equal([erasure.ToString("D")], "the administrator sees the person's erasure and never their closure"); + using (var read = await SendAsync(client, admin, AdminPath + "/" + id.ToString("D"))) + await ProblemAsync(read, HttpStatusCode.NotFound, "not_found"); + using (var cancel = await SendAsync(client, admin, AdminPath + "/" + id.ToString("D") + "/cancellations", "POST", "{}", + version: version, key: Key())) + await ProblemAsync(cancel, HttpStatusCode.NotFound, "not_found"); + using (var file = await SendAsync(client, admin, AdminPath + "/closures", "POST", + JsonSerializer.Serialize(new { membershipId = LearnerMembership }), key: Key())) + file.StatusCode.Should().BeOneOf([HttpStatusCode.NotFound, HttpStatusCode.MethodNotAllowed], "no administrator closure route exists"); + using (var foreign = await SendAsync(client, admin, OwnPath + "/" + id.ToString("D"))) + await ProblemAsync(foreign, HttpStatusCode.NotFound, "not_found"); + (await ReceiptAsync(client, learner, id)).GetProperty("status").GetString().Should().Be("scheduled", "nothing changed it"); + (await CountAsync(proof, English.TenantId.Value, null, "SELECT count(*) FROM public.data_subject_requests WHERE kind='closure'")) + .Should().Be(1, "the administrator filed none"); + } + + /// + /// ADR-0106 § 2: a closure belongs to its originating group and tenant. A person with Memberships in two groups files one + /// per group; neither is visible, cancellable or readable from the other group, nor from another tenant's host. + /// + [Fact] + public async Task A_closure_is_confined_to_its_originating_group_and_tenant() + { + await using var proof = await CreatePreparedAsync(); + using var client = proof.Client(); + var tenant = English.TenantId.Value; + var branch = English.DefaultOrganization.OrganizationId; + await proof.Database.AddMembershipAsync(English, EnglishLearner, branch); + var wide = proof.Token(EnglishLearner, English); + var inBranch = proof.Token(EnglishLearner, English, organization: true, claimedOrganization: branch); + + var (tenantWide, version) = await FileClosureAsync(client, wide); + var (branchClosure, _) = await FileClosureAsync(client, inBranch); + (await AuditCountAsync(proof, tenant, branch.Value, "identity.data_request.create_closure", branchClosure.ToString("D"))).Should().Be(1); + + using (var list = await SendAsync(client, inBranch, OwnPath)) + (await JsonAsync(list)).GetProperty("items").EnumerateArray().Select(item => item.GetProperty("id").GetString()) + .Should().Equal(branchClosure.ToString("D")); + using (var read = await SendAsync(client, inBranch, OwnPath + "/" + tenantWide.ToString("D"))) + await ProblemAsync(read, HttpStatusCode.NotFound, "not_found"); + using (var cancel = await SendAsync(client, inBranch, OwnPath + "/" + tenantWide.ToString("D") + "/cancellations", "POST", "{}", + version: version, key: Key())) + await ProblemAsync(cancel, HttpStatusCode.NotFound, "not_found"); + using (var yoga = await SendAsync(client, wide, OwnPath + "/" + tenantWide.ToString("D"), host: SeedData.Yoga.Host)) + yoga.StatusCode.Should().BeOneOf([HttpStatusCode.NotFound, HttpStatusCode.Unauthorized], "another tenant's host never reaches it"); + (await ReceiptAsync(client, wide, tenantWide)).GetProperty("status").GetString().Should().Be("scheduled"); + (await CountAsync(proof, tenant, null, + "SELECT count(*) FROM public.data_subject_requests WHERE kind='closure' AND organization_id IS NULL")).Should().Be(1); + (await CountAsync(proof, tenant, branch.Value, + "SELECT count(*) FROM public.data_subject_requests WHERE kind='closure' AND organization_id=@branch", ("branch", branch.Value))) + .Should().Be(1, "one closure per group"); + } + + /// + /// ADR-0106 § 9, ADR-0107 § 7: a Suspended person has no live closure route and files, replays, reads and cancels a + /// closure through the retained entry, with no Location. + /// + [Fact] + public async Task A_suspended_person_files_reads_and_cancels_a_closure_through_the_retained_entry() + { + await using var proof = await CreatePreparedAsync(); + using var client = RetainedClient(proof); + var tenant = English.TenantId.Value; + var native = NativeToken(proof, EnglishLearner); + await ChangeStatusAsync(client, proof, LearnerMembershipId, "Suspended"); + using (var live = await SendAsync(client, proof.Token(EnglishLearner, English), OwnPath + "/closures", "POST", "{}", key: Key())) + await ProblemAsync(live, HttpStatusCode.NotFound, "not_found"); + + var key = Key(); + string id; + string version; + using (var filed = await EntrySendAsync(client, native, "/closures?group=tenant", "{}", key)) + { + var accepted = await JsonAsync(filed, HttpStatusCode.Accepted); + accepted.EnumerateObject().Select(property => property.Name).Should().Equal("id", "kind", "status", "version"); + accepted.GetProperty("kind").GetString().Should().Be("closure"); + accepted.GetProperty("status").GetString().Should().Be("scheduled"); + filed.Headers.Location.Should().BeNull("the retained entry has no per-request route"); + filed.Headers.ETag!.Tag.Should().Be("\"" + Version(accepted) + "\""); + id = accepted.GetProperty("id").GetString()!; + version = Version(accepted); + } + + using (var replay = await EntrySendAsync(client, native, "/closures?group=tenant", "{}", key)) + { + (await JsonAsync(replay, HttpStatusCode.Accepted)).GetProperty("id").GetString().Should().Be(id); + replay.Headers.GetValues("Idempotency-Replayed").Should().Equal("true"); + replay.Headers.Location.Should().BeNull(); + } + + (await AuditCountAsync(proof, tenant, null, "identity.data_request.create_closure", id)).Should().Be(1); + using (var page = await EntrySendAsync(client, native, "/requests?group=tenant")) + { + var item = (await JsonAsync(page)).GetProperty("items").EnumerateArray().Single(); + item.GetProperty("id").GetString().Should().Be(id); + item.GetProperty("kind").GetString().Should().Be("closure"); + item.GetProperty("status").GetString().Should().Be("scheduled"); + Instant(item, "executeAt").Should().Be(Instant(item, "createdAt") + TimeSpan.FromHours(24)); + } + + using (var cancelled = await EntrySendAsync(client, native, "/cancellations?group=tenant", + JsonSerializer.Serialize(new { requestId = id }), Key(), "\"" + version + "\"")) + await JsonAsync(cancelled); + using (var page = await EntrySendAsync(client, native, "/requests?group=tenant")) + (await JsonAsync(page)).GetProperty("items").EnumerateArray().Single().GetProperty("status").GetString().Should().Be("cancelled"); + (await AuditCountAsync(proof, tenant, null, "identity.data_request.cancel", id)).Should().Be(1); + } + + /// + /// ADR-0106 § 7, § 8, ADR-0107 § 7: the receipt of a closure as an operator's acts leave it, written here by the owner with + /// the request guard paused: a refused Begin's lastRefusal on a still scheduled and cancellable closure, a begun + /// closure fulfilling and no longer cancellable, and a finalized one completed with its retained report, + /// unserved_group included. None is ever shown failed. + /// + [Fact] + public async Task The_receipts_of_a_refused_a_begun_and_a_finalized_closure_render_as_stored() + { + await using var proof = await CreatePreparedAsync(); + using var client = proof.Client(); + var learner = proof.Token(EnglishLearner, English); + var tenant = English.TenantId.Value; + var (id, _) = await FileClosureAsync(client, learner); + + await ClosureAsOwnerAsync(proof, tenant, id, "last_refusal='blocked_last_administrator'"); + var refused = await ReceiptAsync(client, learner, id); + refused.GetProperty("status").GetString().Should().Be("scheduled"); + refused.GetProperty("lastRefusal").GetString().Should().Be("blocked_last_administrator"); + + await ClosureAsOwnerAsync(proof, tenant, id, "status='fulfilling', last_refusal=NULL"); + var begun = await ReceiptAsync(client, learner, id); + begun.GetProperty("status").GetString().Should().Be("fulfilling"); + begun.GetProperty("failureReason").ValueKind.Should().Be(JsonValueKind.Null); + using (var late = await SendAsync(client, learner, OwnPath + "/" + id.ToString("D") + "/cancellations", "POST", "{}", + version: Version(begun), key: Key())) + (await ProblemAsync(late, HttpStatusCode.Conflict, "business_rule_violation")).GetProperty("errors").GetProperty("$")[0] + .GetProperty("key").GetString().Should().Be("lockey_data_request_not_cancellable", "a begun closure is irreversible"); + + await ClosureAsOwnerAsync(proof, tenant, id, + "status='completed', completed_at=now(), result='{\"audit_entity_reference\":4,\"unserved_group\":1}'::jsonb"); + var completed = await ReceiptAsync(client, learner, id); + completed.GetProperty("status").GetString().Should().Be("completed"); + completed.GetProperty("completedAt").ValueKind.Should().Be(JsonValueKind.String); + completed.GetProperty("retained").EnumerateArray().Select(item => (item.GetProperty("kind").GetString(), item.GetProperty("count").GetInt64())) + .Should().Equal(("audit_entity_reference", 4L), ("unserved_group", 1L)); + completed.TryGetProperty("membershipIds", out _).Should().BeFalse("the person's receipt names no internal identifier"); + } + + /// Files a closure on the live route and returns its id, after checking the 202 contract. + private static async Task<(Guid Id, string Version)> FileClosureAsync(HttpClient client, string token) + { + using var response = await SendAsync(client, token, OwnPath + "/closures", "POST", "{}", 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("closure"); + accepted.GetProperty("status").GetString().Should().Be("scheduled"); + var id = Guid.Parse(accepted.GetProperty("id").GetString()!); + id.Version.Should().Be(7); + response.Headers.Location!.OriginalString.Should().Be(OwnPath + "/" + id.ToString("D")); + response.Headers.ETag!.Tag.Should().Be("\"" + Version(accepted) + "\""); + return (id, Version(accepted)); + } + + /// + /// Stands in for an operator's closure act (ADR-0107 § 7), which is not this test's subject: the owner applies + /// to the tenant-wide closure with the request guard paused and restored, stepping its + /// version as the guard would. + /// + private static async Task ClosureAsOwnerAsync(IdentityAuthorizationHttpProof proof, Guid tenant, Guid request, string assignments) + { + 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_subject_requests DISABLE TRIGGER tg_data_subject_requests_mutation_guard"); + await ScopeAsync(owner, transaction, tenant, null); + (await ScalarAsync(owner, transaction, $""" + WITH moved AS ( + UPDATE public.data_subject_requests SET {assignments}, updated_at=now(), row_version=row_version+1 + WHERE id=@id AND kind='closure' RETURNING 1) + SELECT count(*) FROM moved + """, ("id", request))).Should().Be(1); + await ExecuteAsync(owner, transaction, "ALTER TABLE public.data_subject_requests ENABLE TRIGGER tg_data_subject_requests_mutation_guard"); + await transaction.CommitAsync(); + } + + private static DateTimeOffset Instant(JsonElement element, string property) => + DateTimeOffset.Parse(element.GetProperty(property).GetString()!, CultureInfo.InvariantCulture); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Erasure.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Erasure.cs new file mode 100644 index 000000000..57871ceca --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Erasure.cs @@ -0,0 +1,161 @@ +using System.Net; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Tools.Seeder; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityAuthorizationHttpProof; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// ADR-0106 § 3, § 7, § 10, § 11 and ADR-0107 § 4, § 5 through the actual Program: an erasure is filed on its own routes, +/// answered 202 scheduled with its execution time, cancellable until then and not after, refused for the sole +/// administrator, filed by an administrator only for a Revoked Membership, and filed, cancelled and an artifact revoked +/// through the retained entry by a person whose Membership is Suspended. +/// +public sealed partial class DataRequestHttpTests +{ + [Fact] + public async Task A_person_files_an_erasure_scheduled_for_its_window_and_may_cancel_it_only_before_its_execution_time() + { + await using var proof = await CreatePreparedAsync(); + using var client = proof.Client(); + var learner = proof.Token(EnglishLearner, English); + var tenant = English.TenantId.Value; + + var (id, version) = await FileErasureAsync(client, learner, OwnPath + "/erasures", "{}"); + var receipt = await ReceiptAsync(client, learner, id); + receipt.GetProperty("kind").GetString().Should().Be("erasure"); + receipt.GetProperty("status").GetString().Should().Be("scheduled"); + DateTimeOffset.Parse(receipt.GetProperty("executeAt").GetString()!, System.Globalization.CultureInfo.InvariantCulture) + .Should().Be(DateTimeOffset.Parse(receipt.GetProperty("createdAt").GetString()!, System.Globalization.CultureInfo.InvariantCulture) + + TimeSpan.FromHours(24), "the cancellable window is 24 hours"); + (await AuditCountAsync(proof, tenant, null, "identity.data_request.create_erasure", id.ToString("D"))).Should().Be(1); + using (var second = await SendAsync(client, learner, OwnPath + "/erasures", "POST", "{}", key: Key())) + (await ProblemAsync(second, HttpStatusCode.Conflict, "business_rule_violation")).GetProperty("errors").GetProperty("$")[0] + .GetProperty("key").GetString().Should().Be("lockey_request_already_active"); + + using (var cancelled = await SendAsync(client, learner, OwnPath + "/" + id.ToString("D") + "/cancellations", "POST", "{}", + version: version, key: Key())) + await JsonAsync(cancelled); + (await ReceiptAsync(client, learner, id)).GetProperty("status").GetString().Should().Be("cancelled"); + (await AuditCountAsync(proof, tenant, null, "identity.data_request.cancel", id.ToString("D"))).Should().Be(1); + + // Once the window has ended the erasure is no longer the person's to withdraw (ADR-0106 § 11). + var (due, dueVersion) = await FileErasureAsync(client, learner, OwnPath + "/erasures", "{}"); + await DataErasureTestKit.BackdateAsync(proof.Database.MigrationConnectionString, tenant, null, due); + using (var late = await SendAsync(client, learner, OwnPath + "/" + due.ToString("D") + "/cancellations", "POST", "{}", + version: dueVersion, key: Key())) + (await ProblemAsync(late, HttpStatusCode.Conflict, "business_rule_violation")).GetProperty("errors").GetProperty("$")[0] + .GetProperty("key").GetString().Should().Be("lockey_data_request_window_ended", "the person can tell the window ended"); + (await ReceiptAsync(client, learner, due)).GetProperty("status").GetString().Should().Be("scheduled"); + var cancelledVersion = (await ReceiptAsync(client, learner, id)).GetProperty("version").GetString()!; + using (var again = await SendAsync(client, learner, OwnPath + "/" + id.ToString("D") + "/cancellations", "POST", "{}", + version: cancelledVersion, key: Key())) + (await ProblemAsync(again, HttpStatusCode.Conflict, "business_rule_violation")).GetProperty("errors").GetProperty("$")[0] + .GetProperty("key").GetString().Should().Be("lockey_data_request_not_cancellable", "an ended request admits no cancellation"); + } + + /// + /// ADR-0106 § 3, § 7: the tenant's only eligible administrator is refused with its closed code; an administrator files + /// for a working member only after revoking the Membership, which is the separately audited act; a person who is not + /// an administrator of the group is refused the administrator's route. + /// + [Fact] + public async Task The_sole_administrator_is_refused_and_an_administrator_erases_only_a_member_whose_Membership_is_revoked() + { + await using var proof = await CreatePreparedAsync(); + using var client = proof.Client(); + var admin = proof.Token(EnglishAdmin, English); + var learner = proof.Token(EnglishLearner, English); + var body = JsonSerializer.Serialize(new { membershipId = LearnerMembership }); + + using (var sole = await SendAsync(client, admin, OwnPath + "/erasures", "POST", "{}", key: Key())) + (await ProblemAsync(sole, HttpStatusCode.Conflict, "business_rule_violation")).GetProperty("errors").GetProperty("$")[0] + .GetProperty("key").GetString().Should().Be("lockey_blocked_last_administrator"); + using (var denied = await SendAsync(client, learner, AdminPath + "/erasures", "POST", body, key: Key())) + await ProblemAsync(denied, HttpStatusCode.Forbidden, "forbidden"); + using (var self = await SendAsync(client, admin, AdminPath + "/erasures", "POST", + JsonSerializer.Serialize(new { membershipId = SeedData.IdentityMemberships[0].MembershipId }), key: Key())) + (await ProblemAsync(self, HttpStatusCode.Conflict, "business_rule_violation")).GetProperty("errors").GetProperty("$")[0] + .GetProperty("key").GetString().Should().Be("lockey_subject_is_requester", "an administrator never files for themselves"); + using (var working = await SendAsync(client, admin, AdminPath + "/erasures", "POST", body, key: Key())) + (await ProblemAsync(working, HttpStatusCode.Conflict, "business_rule_violation")).GetProperty("errors").GetProperty("$")[0] + .GetProperty("key").GetString().Should().Be("lockey_subject_membership_current"); + + await ChangeStatusAsync(client, proof, LearnerMembership, "Revoked"); + var (id, version) = await FileErasureAsync(client, admin, AdminPath + "/erasures", body); + var detail = await ReceiptAsync(client, admin, id, AdminPath); + detail.GetProperty("origin").GetString().Should().Be("administrator"); + detail.GetProperty("kind").GetString().Should().Be("erasure"); + detail.GetProperty("membershipIds").EnumerateArray().Select(item => item.GetString()).Should().Equal(LearnerMembership.ToString("D")); + using (var cancelled = await SendAsync(client, admin, AdminPath + "/" + id.ToString("D") + "/cancellations", "POST", "{}", + version: version, key: Key())) + await JsonAsync(cancelled); + (await ReceiptAsync(client, admin, id, AdminPath)).GetProperty("status").GetString().Should().Be("cancelled"); + } + + /// + /// ADR-0106 § 9, ADR-0107 § 4: a Suspended person has no live route, and through the retained entry files and cancels an + /// erasure and revokes their own export artifact; the revocation binds the artifact's version and another person's + /// request is absent. + /// + [Fact] + public async Task A_suspended_person_files_and_cancels_an_erasure_and_revokes_an_artifact_through_the_retained_entry() + { + await using var proof = await CreatePreparedAsync(); + using var client = RetainedClient(proof); + var tenant = English.TenantId.Value; + var native = NativeToken(proof, EnglishLearner); + var (export, _) = await FileExportAsync(client, proof.Token(EnglishLearner, English)); + await RunExportAsync(proof, tenant, null, export); + await ChangeStatusAsync(client, proof, LearnerMembershipId, "Suspended"); + using (var live = await SendAsync(client, proof.Token(EnglishLearner, English), OwnPath + "/erasures", "POST", "{}", key: Key())) + await ProblemAsync(live, HttpStatusCode.NotFound, "not_found"); + + using (var filed = await EntrySendAsync(client, native, "/erasures?group=tenant", "{}", Key())) + { + var accepted = await JsonAsync(filed, HttpStatusCode.Accepted); + accepted.GetProperty("kind").GetString().Should().Be("erasure"); + accepted.GetProperty("status").GetString().Should().Be("scheduled"); + filed.Headers.Location.Should().BeNull("the retained entry has no per-request route"); + var erasure = accepted.GetProperty("id").GetString()!; + (await AuditCountAsync(proof, tenant, null, "identity.data_request.create_erasure", erasure)).Should().Be(1); + using var cancelled = await EntrySendAsync(client, native, "/cancellations?group=tenant", + JsonSerializer.Serialize(new { requestId = erasure }), Key(), "\"" + Version(accepted) + "\""); + await JsonAsync(cancelled); + } + + JsonElement artifact; + using (var page = await EntrySendAsync(client, native, "/requests?group=tenant")) + artifact = (await JsonAsync(page)).GetProperty("items").EnumerateArray() + .Single(item => item.GetProperty("id").GetString() == export.ToString("D")).GetProperty("artifact"); + var body = JsonSerializer.Serialize(new { requestId = export }); + using (var unconditional = await EntrySendAsync(client, native, "/revocations?group=tenant", body, Key())) + unconditional.StatusCode.Should().Be(HttpStatusCode.BadRequest, "a revocation takes the artifact's version"); + using (var foreign = await EntrySendAsync(client, native, "/revocations?group=tenant", + JsonSerializer.Serialize(new { requestId = Guid.CreateVersion7() }), Key(), "\"" + Version(artifact) + "\"")) + await ProblemAsync(foreign, HttpStatusCode.NotFound, "not_found"); + using (var revoked = await EntrySendAsync(client, native, "/revocations?group=tenant", body, Key(), "\"" + Version(artifact) + "\"")) + await JsonAsync(revoked); + using (var page = await EntrySendAsync(client, native, "/requests?group=tenant")) + (await JsonAsync(page)).GetProperty("items").EnumerateArray() + .Single(item => item.GetProperty("id").GetString() == export.ToString("D")).GetProperty("artifact") + .GetProperty("status").GetString().Should().Be("revoked"); + (await AuditCountAsync(proof, tenant, null, "identity.data_export.revoke")).Should().Be(1); + } + + /// Files an erasure through a creation route and returns its id, after checking the 202 contract. + private static async Task<(Guid Id, string Version)> FileErasureAsync(HttpClient client, string token, string path, string body) + { + using var response = await SendAsync(client, token, path, "POST", body, 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("erasure"); + accepted.GetProperty("status").GetString().Should().Be("scheduled"); + var id = Guid.Parse(accepted.GetProperty("id").GetString()!); + response.Headers.Location!.OriginalString.Should().EndWith("/" + id.ToString("D")); + response.Headers.ETag!.Tag.Should().Be("\"" + Version(accepted) + "\""); + return (id, Version(accepted)); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.ErasureCoverage.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.ErasureCoverage.cs new file mode 100644 index 000000000..8a7fcb42f --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.ErasureCoverage.cs @@ -0,0 +1,363 @@ +using System.Net; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Application.Jobs; +using LearnStack.Infrastructure.Jobs; +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Permissions; +using LearnStack.Tools.Seeder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityAuthorizationHttpProof; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class DataRequestHttpTests +{ + /// + /// ADR-0106 § 3: an organization administrator files an erasure only for a person of their own organization. A + /// Membership of another branch is as absent as it is for an export, files nothing and writes no row; the own branch's + /// is accepted, and the request it files is one job of the organization definition, due at the request's execution + /// time, carrying nothing but the request's identifier. + /// + [Fact] + public async Task An_organization_administrator_files_an_erasure_for_their_own_branch_only_and_the_job_is_stored_due_at_its_execution_time() + { + await using var proof = await CreatePreparedAsync(); + var branch = English.DefaultOrganization.OrganizationId; + var other = English.SecondOrganization.OrganizationId; + var tenant = English.TenantId.Value; + 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); + await proof.SetMembershipStatusAsync(English, EnglishAdmin, branchMember, "Revoked", branch); + await proof.SetMembershipStatusAsync(English, EnglishAdmin, otherMember, "Revoked", other); + using var client = proof.Client(); + var branchAdmin = proof.Token(YogaAdmin, English, organization: true, claimedOrganization: branch); + + using (var crossed = await SendAsync(client, branchAdmin, AdminPath + "/erasures", "POST", + JsonSerializer.Serialize(new { membershipId = otherMember }), key: Key())) + await ProblemAsync(crossed, HttpStatusCode.NotFound, "not_found"); + (await CountAsync(proof, tenant, other.Value, "SELECT count(*) FROM public.data_subject_requests")).Should().Be(0, + "the refused filing wrote no request in the other branch"); + (await CountAsync(proof, tenant, branch.Value, "SELECT count(*) FROM public.data_subject_requests")).Should().Be(0); + (await AuditCountAsync(proof, tenant, other.Value, "identity.data_request.create_erasure")).Should().Be(0); + (await AuditCountAsync(proof, tenant, branch.Value, "identity.data_request.create_erasure")).Should().Be(0); + (await CountAsync(proof, tenant, other.Value, "SELECT count(*) FROM public.background_jobs")).Should().Be(0, "and scheduled no job"); + + var (id, _) = await FileErasureAsync(client, branchAdmin, AdminPath + "/erasures", + JsonSerializer.Serialize(new { membershipId = branchMember })); + (await AuditCountAsync(proof, tenant, branch.Value, "identity.data_request.create_erasure", id.ToString("D"))).Should().Be(1); + var receipt = await ReceiptAsync(client, branchAdmin, id, AdminPath); + receipt.GetProperty("origin").GetString().Should().Be("administrator"); + await AssertErasureJobAsync(proof, tenant, branch.Value, id, receipt); + (await CountAsync(proof, tenant, other.Value, "SELECT count(*) FROM public.data_subject_requests")).Should().Be(0); + } + + /// + /// ADR-0107 § 5 and § 9 through the API: a person's own erasure is one tenant-wide job due at its execution time; once the + /// job has run, the person still has an Active users row (tenant erasure never touches it) but no Active Membership + /// in the group, so they have no live route there, exactly as for a Suspended person, while the retained entry still + /// answers with the request, which waits for the operator's privileged step. + /// + [Fact] + public async Task A_person_erased_by_the_job_keeps_their_user_but_has_no_live_route_and_the_retained_entry_still_answers() + { + await using var proof = await CreatePreparedAsync(); + using var client = RetainedClient(proof); + var tenant = English.TenantId.Value; + var live = proof.Token(EnglishLearner, English); + var native = NativeToken(proof, EnglishLearner); + (await SendAsync(client, live, OwnPath)).StatusCode.Should().Be(HttpStatusCode.OK, "before the erasure the person's live route answers"); + + var (id, _) = await FileErasureAsync(client, live, OwnPath + "/erasures", "{}"); + await AssertErasureJobAsync(proof, tenant, null, id, await ReceiptAsync(client, live, id)); + await DataErasureTestKit.BackdateAsync(proof.Database.MigrationConnectionString, tenant, null, id); + await RunErasureAsync(proof, tenant, null, id); + + // The Membership is now the Revoked tombstone; the User row, which only the operator's closure ends, is Active. + await using (var owner = (Npgsql.NpgsqlConnection)await PostgresFixture.OpenAsync(proof.Database.MigrationConnectionString)) + (await IdentityMembershipFixture.ScalarAsync(owner, null, "SELECT status FROM public.users WHERE id=@id", + ("id", EnglishLearner.Value))).Should().Be("Active"); + (await CountAsync(proof, tenant, null, "SELECT count(*) FROM public.memberships WHERE id=@id AND status='Revoked'", + ("id", LearnerMembershipId))).Should().Be(1); + using (var list = await SendAsync(client, live, OwnPath)) + await ProblemAsync(list, HttpStatusCode.NotFound, "not_found"); + using (var again = await SendAsync(client, live, OwnPath + "/erasures", "POST", "{}", key: Key())) + await ProblemAsync(again, HttpStatusCode.NotFound, "not_found"); + using (var exports = await SendAsync(client, live, OwnPath + "/exports", "POST", "{}", key: Key())) + await ProblemAsync(exports, HttpStatusCode.NotFound, "not_found"); + + using (var scopes = await EntrySendAsync(client, native, "/scopes")) + (await JsonAsync(scopes)).GetProperty("items").GetArrayLength().Should().Be(1, "the group is still the person's to reach"); + using (var requests = await EntrySendAsync(client, native, "/requests?group=tenant")) + { + var items = (await JsonAsync(requests)).GetProperty("items").EnumerateArray().ToArray(); + items.Select(item => item.GetProperty("id").GetString()).Should().Equal(id.ToString("D")); + items[0].GetProperty("status").GetString().Should().Be("awaiting_privileged_step"); + } + } + + /// + /// ADR-0106 § 7: a hold the platform reports refuses creation, on the person's own route and on the administrator's, with + /// its closed code, and files nothing. + /// + [Fact] + public async Task A_hold_refuses_an_erasure_on_the_own_and_the_administrator_routes_and_files_nothing() + { + await using var proof = await CreatePreparedAsync(); + using var client = proof.Client(services => services.AddSingleton(new AlwaysHold())); + var tenant = English.TenantId.Value; + var learner = proof.Token(EnglishLearner, English); + var admin = proof.Token(EnglishAdmin, English); + + using (var own = await SendAsync(client, learner, OwnPath + "/erasures", "POST", "{}", key: Key())) + (await ProblemAsync(own, HttpStatusCode.Conflict, "business_rule_violation")).GetProperty("errors").GetProperty("$")[0] + .GetProperty("key").GetString().Should().Be("lockey_blocked_hold"); + await ChangeStatusAsync(client, proof, LearnerMembership, "Revoked"); + using (var byAdmin = await SendAsync(client, admin, AdminPath + "/erasures", "POST", + JsonSerializer.Serialize(new { membershipId = LearnerMembership }), key: Key())) + (await ProblemAsync(byAdmin, HttpStatusCode.Conflict, "business_rule_violation")).GetProperty("errors").GetProperty("$")[0] + .GetProperty("key").GetString().Should().Be("lockey_blocked_hold"); + (await CountAsync(proof, tenant, null, "SELECT count(*) FROM public.data_subject_requests")).Should().Be(0); + (await AuditCountAsync(proof, tenant, null, "identity.data_request.create_erasure")).Should().Be(0); + } + + /// + /// ADR-0106 § 10: a repeated own erasure creation with the same key and body answers the stored receipt and files + /// nothing again; the same key on another operation is a key reuse, not a replay. + /// + [Fact] + public async Task An_own_erasure_creation_replays_exactly_and_the_same_key_on_an_export_is_a_key_reuse() + { + await using var proof = await CreatePreparedAsync(); + using var client = proof.Client(); + var tenant = English.TenantId.Value; + var learner = proof.Token(EnglishLearner, English); + var key = Key(); + + string location; + string etag; + Guid id; + using (var first = await SendAsync(client, learner, OwnPath + "/erasures", "POST", "{}", key: key)) + { + var accepted = await JsonAsync(first, HttpStatusCode.Accepted); + id = Guid.Parse(accepted.GetProperty("id").GetString()!); + location = first.Headers.Location!.OriginalString; + etag = first.Headers.ETag!.Tag; + first.Headers.Contains("Idempotency-Replayed").Should().BeFalse(); + } + + using (var replay = await SendAsync(client, learner, OwnPath + "/erasures", "POST", "{}", key: key)) + { + var replayed = await JsonAsync(replay, HttpStatusCode.Accepted); + replayed.GetProperty("id").GetString().Should().Be(id.ToString("D")); + replayed.GetProperty("kind").GetString().Should().Be("erasure"); + replayed.GetProperty("status").GetString().Should().Be("scheduled"); + replay.Headers.GetValues("Idempotency-Replayed").Should().Equal("true"); + replay.Headers.Location!.OriginalString.Should().Be(location); + replay.Headers.ETag!.Tag.Should().Be(etag); + } + + (await CountAsync(proof, tenant, null, "SELECT count(*) FROM public.data_subject_requests WHERE kind='erasure'")).Should().Be(1); + (await AuditCountAsync(proof, tenant, null, "identity.data_request.create_erasure")).Should().Be(1, "a replay audits nothing"); + + // The same key on /exports: the fingerprint carries the operation, so this is a different request under a used key. + var exportKey = Key(); + await using (var other = await CreatePreparedAsync()) + { + using var otherClient = other.Client(); + var otherLearner = other.Token(EnglishLearner, English); + await FileExportAsync(otherClient, otherLearner, exportKey); + using var reused = await SendAsync(otherClient, otherLearner, OwnPath + "/erasures", "POST", "{}", key: exportKey); + await ProblemAsync(reused, HttpStatusCode.Conflict, "idempotency_key_reuse"); + (await CountAsync(other, tenant, null, "SELECT count(*) FROM public.data_subject_requests WHERE kind='erasure'")).Should().Be(0); + } + } + + /// + /// The administrator's erasure creation replays exactly, and the same key with another membershipId is a key reuse + /// that files nothing. + /// + [Fact] + public async Task An_administrator_erasure_creation_replays_exactly_and_another_membership_under_the_key_is_a_key_reuse() + { + await using var proof = await CreatePreparedAsync(); + using var client = proof.Client(); + var tenant = English.TenantId.Value; + var admin = proof.Token(EnglishAdmin, English); + await ChangeStatusAsync(client, proof, LearnerMembership, "Revoked"); + var body = JsonSerializer.Serialize(new { membershipId = LearnerMembership }); + var key = Key(); + + Guid id; + string location; + using (var first = await SendAsync(client, admin, AdminPath + "/erasures", "POST", body, key: key)) + { + id = Guid.Parse((await JsonAsync(first, HttpStatusCode.Accepted)).GetProperty("id").GetString()!); + location = first.Headers.Location!.OriginalString; + } + + using (var replay = await SendAsync(client, admin, AdminPath + "/erasures", "POST", body, key: key)) + { + (await JsonAsync(replay, HttpStatusCode.Accepted)).GetProperty("id").GetString().Should().Be(id.ToString("D")); + replay.Headers.GetValues("Idempotency-Replayed").Should().Equal("true"); + replay.Headers.Location!.OriginalString.Should().Be(location); + } + + using (var changed = await SendAsync(client, admin, AdminPath + "/erasures", "POST", + JsonSerializer.Serialize(new { membershipId = SeedData.IdentityMemberships[0].MembershipId }), key: key)) + await ProblemAsync(changed, HttpStatusCode.Conflict, "idempotency_key_reuse"); + (await CountAsync(proof, tenant, null, "SELECT count(*) FROM public.data_subject_requests WHERE kind='erasure'")).Should().Be(1); + (await AuditCountAsync(proof, tenant, null, "identity.data_request.create_erasure")).Should().Be(1); + } + + /// + /// The retained entry's erasure creation replays exactly with no Location, and its artifact revocation replays with + /// the same key and If-Match: the stored answer again, one audit row, the artifact revoked once. + /// + [Fact] + public async Task The_retained_entry_replays_an_erasure_creation_and_an_artifact_revocation_exactly() + { + await using var proof = await CreatePreparedAsync(); + using var client = RetainedClient(proof); + var tenant = English.TenantId.Value; + var native = NativeToken(proof, EnglishLearner); + var (export, _) = await FileExportAsync(client, proof.Token(EnglishLearner, English)); + await RunExportAsync(proof, tenant, null, export); + await ChangeStatusAsync(client, proof, LearnerMembershipId, "Suspended"); + + var key = Key(); + string id; + using (var first = await EntrySendAsync(client, native, "/erasures?group=tenant", "{}", key)) + { + id = (await JsonAsync(first, HttpStatusCode.Accepted)).GetProperty("id").GetString()!; + first.Headers.Location.Should().BeNull(); + } + + using (var replay = await EntrySendAsync(client, native, "/erasures?group=tenant", "{}", key)) + { + var replayed = await JsonAsync(replay, HttpStatusCode.Accepted); + replayed.GetProperty("id").GetString().Should().Be(id); + replayed.GetProperty("kind").GetString().Should().Be("erasure"); + replay.Headers.GetValues("Idempotency-Replayed").Should().Equal("true"); + replay.Headers.Location.Should().BeNull("the retained entry has no per-request route"); + } + + (await AuditCountAsync(proof, tenant, null, "identity.data_request.create_erasure", id)).Should().Be(1); + (await CountAsync(proof, tenant, null, "SELECT count(*) FROM public.data_subject_requests WHERE kind='erasure'")).Should().Be(1); + + JsonElement artifact; + using (var page = await EntrySendAsync(client, native, "/requests?group=tenant")) + artifact = (await JsonAsync(page)).GetProperty("items").EnumerateArray() + .Single(item => item.GetProperty("id").GetString() == export.ToString("D")).GetProperty("artifact"); + var body = JsonSerializer.Serialize(new { requestId = export }); + var revokeKey = Key(); + var ifMatch = "\"" + Version(artifact) + "\""; + string revokedVersion; + using (var revoked = await EntrySendAsync(client, native, "/revocations?group=tenant", body, revokeKey, ifMatch)) + revokedVersion = Version(await JsonAsync(revoked)); + using (var replay = await EntrySendAsync(client, native, "/revocations?group=tenant", body, revokeKey, ifMatch)) + { + Version(await JsonAsync(replay)).Should().Be(revokedVersion, "the stored answer, not a second revocation of a revoked artifact"); + replay.Headers.GetValues("Idempotency-Replayed").Should().Equal("true"); + replay.Headers.Location.Should().BeNull(); + } + + (await AuditCountAsync(proof, tenant, null, "identity.data_export.revoke")).Should().Be(1); + } + + /// + /// The retained revocation is the caller's own artifact only: a Suspended person naming another person's completed export + /// in the same group, with that artifact's real version, is answered exactly as an unknown request is, and the other + /// person's artifact is still available and unchanged. Dropping the subject check on the retained entry fails this. + /// + [Fact] + public async Task The_retained_revocation_of_another_persons_artifact_is_not_found_and_leaves_that_artifact_available() + { + await using var proof = await CreatePreparedAsync(); + using var client = RetainedClient(proof); + var tenant = English.TenantId.Value; + var admin = proof.Token(EnglishAdmin, English); + var native = NativeToken(proof, EnglishLearner); + var (foreignExport, _) = await FileExportAsync(client, admin); + await RunExportAsync(proof, tenant, null, foreignExport); + var before = (await ReceiptAsync(client, admin, foreignExport)).GetProperty("artifact"); + before.GetProperty("status").GetString().Should().Be("available", "the other person's artifact is arranged available"); + var (ownExport, _) = await FileExportAsync(client, proof.Token(EnglishLearner, English)); + await RunExportAsync(proof, tenant, null, ownExport); + await ChangeStatusAsync(client, proof, LearnerMembershipId, "Suspended"); + + var body = JsonSerializer.Serialize(new { requestId = foreignExport }); + using (var refused = await EntrySendAsync(client, native, "/revocations?group=tenant", body, Key(), "\"" + Version(before) + "\"")) + await ProblemAsync(refused, HttpStatusCode.NotFound, "not_found"); + + var after = (await ReceiptAsync(client, admin, foreignExport)).GetProperty("artifact"); + after.GetProperty("status").GetString().Should().Be("available", "a refused revocation deletes nothing"); + Version(after).Should().Be(Version(before)); + (await AuditCountAsync(proof, tenant, null, "identity.data_export.revoke")).Should().Be(0); + (await CountAsync(proof, tenant, null, "SELECT count(*) FROM public.data_export_artifacts WHERE status='available'")).Should() + .Be(2, "both persons' artifacts are intact"); + } + + /// The request's stored erasure job: its definition, group, identifier-only parameters and due time. + private static async Task AssertErasureJobAsync(IdentityAuthorizationHttpProof proof, Guid tenant, Guid? organization, Guid request, + JsonElement receipt) + { + var definition = organization is null ? "identity.data_erasure_tenant.v1" : "identity.data_erasure_organization.v1"; + var jobs = new List(); + await using (var app = await OpenAppAsync(proof)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await IdentityMembershipFixture.ScopeAsync(app, transaction, tenant, organization); + await using var command = new Npgsql.NpgsqlCommand( + "SELECT id FROM public.background_jobs WHERE definition_key LIKE 'identity.data_erasure%' AND parameters::text LIKE '%' || @request || '%'", + app, transaction); + command.Parameters.AddWithValue("request", request.ToString("D")); + await using var reader = await command.ExecuteReaderAsync(); + while (await reader.ReadAsync()) jobs.Add(reader.GetGuid(0)); + } + + jobs.Should().ContainSingle("filing schedules exactly one job for the request"); + var row = (await BackgroundJobRuntimeRows.ReadAsync(proof.Database.AppConnectionString, BackgroundJobId.From(jobs[0]), organization, tenant))!; + (row.Definition, row.TenantId, row.OrganizationId, row.Profile).Should().Be((definition, tenant, organization, "transactional")); + using var parameters = JsonDocument.Parse(row.Parameters); + parameters.RootElement.EnumerateObject().Select(property => (property.Name, property.Value.GetString())).Should() + .Equal([("RequestId", (string?)request.ToString("D"))], "identifiers only: no subject, no Membership"); + var executeAt = DateTimeOffset.Parse(receipt.GetProperty("executeAt").GetString()!, System.Globalization.CultureInfo.InvariantCulture); + row.OriginalDue.Should().BeCloseTo(executeAt, TimeSpan.FromMilliseconds(1), "the job waits for the window to end"); + } + + /// Runs the request's erasure job through the actual job runtime of a host on the same database. + private static async Task RunErasureAsync(IdentityAuthorizationHttpProof proof, Guid tenant, Guid? organization, Guid request) + { + // The runtime dispatches a job only once it is due, and the job the API stored waits for the window; the request's + // window is moved back by the caller, so the due job is the one a clock that had passed it would have claimed. + var job = await BackgroundJobRuntimeRows.InsertAsync(proof.Database.AppConnectionString, + organization is null ? "identity.data_erasure_tenant.v1" : "identity.data_erasure_organization.v1", + organization: organization, tenant: tenant, parameters: DataErasureTestKit.Parameters(request)); + 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 DataExportTestKit.RoutingClaim.ClaimAsync(proof.Database.OutboxConnectionString, + 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); + } + + private sealed class AlwaysHold : IDataRequestHoldSource + { + public Task HasHoldAsync(DataRequestHoldQuery query, CancellationToken cancellationToken) => Task.FromResult(true); + } +} 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 000000000..546627777 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Export.cs @@ -0,0 +1,202 @@ +using System.Collections.Concurrent; +using System.Net; +using System.Text; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Modules.Identity.Application.DataRequests; +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"); + + var jobLogs = new LogCapture(); + await RunExportAsync(proof, tenant, organization?.Value, id, jobLogs); + + 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 of the API or of the job's host, nor the state, before or change + // columns of the export's audit rows: no ticket, no ticket or session-binding digest, no ciphertext and no + // distinctive plaintext (the subject's profile name). The subject's UserId is checked in the logs only: the audit + // rows record the request and artifact aggregates, whose subject and requester references are the audit trail. + string canary; + using (var document = JsonDocument.Parse(bundle)) + canary = document.RootElement.GetProperty("sections").GetProperty("identity").GetProperty("memberships")[0] + .GetProperty("profile").GetProperty("display_name").GetString()!; + canary.Should().NotBeNullOrWhiteSpace("the subject's profile name is in the bundle, so its absence elsewhere means something"); + var secrets = await SecretsAsync(proof, tenant, organization?.Value, Guid.Parse(artifactId), ticket); + var rendered = Render(logs) + "\n" + Render(jobLogs); + jobLogs.Entries.Should().NotBeEmpty("the job host's own log is captured"); + var audit = await AuditPayloadsAsync(proof, tenant, organization?.Value, "identity.data_request.create_export", + "identity.data_request.fulfill_export", "identity.data_export.store", "identity.data_export.mint_ticket", + "identity.data_export.read_chunk"); + foreach (var (where, text) in new[] { ("a log", rendered), ("an export audit row's state or changes", audit) }) + { + text.Should().NotContain(ticket, where); + foreach (var secret in secrets) + text.Should().NotContainEquivalentOf(secret, where); + text.Should().NotContain(Convert.ToBase64String(bundle.AsSpan(0, Math.Min(bundle.Length, 48))), where); + text.Should().NotContain(canary, where); + } + + rendered.Should().NotContainEquivalentOf(EnglishLearner.Value.ToString("D"), + "no log names the subject beyond the actor enrichment every request carries"); + + // 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); + } + + /// + /// Every captured event, message, properties and exception. The actor enrichment (user.id and UserId) + /// is left out: it is stamped on every request's events by the observability pipeline (Observability Standards), not + /// written by the export, and the subject is the actor here. Every other property and every message is kept. + /// + private static string Render(LogCapture logs) => string.Join('\n', logs.Entries.Select(entry => + entry.RenderMessage(System.Globalization.CultureInfo.InvariantCulture) + " " + string.Join(' ', + entry.Properties.Where(property => property.Key is not ("user.id" or "UserId")) + .Select(property => property.Key + "=" + property.Value)) + + " " + entry.Exception)); + + /// The digests and ciphertext prefixes the database holds for the artifact, in hex and base64. + private static async Task SecretsAsync(IdentityAuthorizationHttpProof proof, Guid tenant, Guid? organization, Guid artifact, + string ticket) + { + await using var app = await OpenAppAsync(proof); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant, organization); + var stored = await StringsAsync(app, transaction, """ + SELECT encode(session_binding_digest, 'hex') FROM public.data_export_tickets WHERE artifact_id = @artifact + UNION ALL SELECT encode(digest, 'hex') FROM public.data_export_tickets WHERE artifact_id = @artifact + UNION ALL SELECT encode(substring(ciphertext FROM 1 FOR 24), 'hex') FROM public.data_export_chunks WHERE artifact_id = @artifact + UNION ALL SELECT encode(substring(ciphertext FROM 1 FOR 24), 'base64') FROM public.data_export_chunks WHERE artifact_id = @artifact + UNION ALL SELECT encode(nonce, 'hex') FROM public.data_export_chunks WHERE artifact_id = @artifact + """, ("artifact", artifact)); + stored.Should().Contain(DataExportTicketCodec.TryDigest(ticket)!, "the ticket's stored digest is among the values checked"); + return [.. stored]; + } + + /// The before, after and changes columns of the tenant's audit rows of the given operations, concatenated. + private static async Task AuditPayloadsAsync(IdentityAuthorizationHttpProof proof, Guid tenant, Guid? organization, + params string[] operations) + { + await using var app = await OpenAppAsync(proof); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant, organization); + var rows = await StringsAsync(app, transaction, """ + SELECT operation || ' ' || coalesce(before_state::text, '') || ' ' || coalesce(after_state::text, '') || ' ' + || coalesce(changes::text, '') + FROM public.audit_log WHERE operation = ANY(@operations) + """, ("operations", operations)); + rows.Select(row => row.Split(' ')[0]).Distinct().Should().Contain(operations, "every export operation wrote its row"); + return string.Join('\n', rows); + } + + private static async Task> StringsAsync(Npgsql.NpgsqlConnection connection, Npgsql.NpgsqlTransaction transaction, + string sql, params (string Name, object Value)[] values) + { + await using var command = new Npgsql.NpgsqlCommand(sql, connection, transaction); + foreach (var (name, value) in values) command.Parameters.AddWithValue(name, value); + var found = new List(); + await using var reader = await command.ExecuteReaderAsync(); + while (await reader.ReadAsync()) found.Add(reader.GetString(0)); + return found; + } + + 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 000000000..ab94a274c --- /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.RetainedEntry.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.RetainedEntry.cs new file mode 100644 index 000000000..ac21f9577 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.RetainedEntry.cs @@ -0,0 +1,402 @@ +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 User closure writer is the platform session under the closure's fences (ADR-0107 § 7): this + /// owner-only fixture accommodation moves the binding out of Active without them 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.Integration/Database/DataRequestHttpTests.Tickets.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Tickets.cs new file mode 100644 index 000000000..5e3380bca --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.Tickets.cs @@ -0,0 +1,161 @@ +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", "live")] + [InlineData("identity.data_export.read_chunk", "live")] + [InlineData("identity.data_request.read", "live")] + [InlineData("identity.data_request.list", "live")] + [InlineData("identity.data_export.mint_ticket", "retained")] + [InlineData("identity.data_export.read_chunk", "retained")] + public async Task A_disclosure_whose_MUST_audit_row_cannot_be_written_is_refused(string operation, string entry) + { + await using var proof = await CreatePreparedAsync(); + using var client = entry == "retained" ? RetainedClient(proof) : proof.Client(); + var token = proof.Token(EnglishLearner, English); + var native = NativeToken(proof, EnglishLearner); + var tenant = English.TenantId.Value; + var (id, _) = await FileExportAsync(client, token); + await RunExportAsync(proof, tenant, null, id); + if (entry == "retained") + await ChangeStatusAsync(client, proof, LearnerMembershipId, "Suspended"); + string? ticket = null; + if (operation == "identity.data_export.read_chunk") + { + using var minted = entry == "retained" + ? await EntrySendAsync(client, native, "/tickets?group=tenant", JsonSerializer.Serialize(new { requestId = id })) + : 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, entry) switch + { + ("identity.data_export.mint_ticket", "retained") => await EntrySendAsync(client, native, "/tickets?group=tenant", + JsonSerializer.Serialize(new { requestId = id })), + ("identity.data_export.read_chunk", "retained") => await EntryChunkAsync(client, native, id, ticket!, 0), + ("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), + ("identity.data_request.list", _) => await SendAsync(client, proof.Token(EnglishAdmin, English), AdminPath), + _ => 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\"") + .And.NotContain("\"items\""); + 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 000000000..9165c0c50 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestHttpTests.cs @@ -0,0 +1,200 @@ +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, Serilog.Core.ILogEventSink? logs = null) + { + 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); + if (logs is not null) + builder.ConfigureServices(services => services.AddSingleton(logs)); + }); + var executor = host.Services.GetRequiredService(); + var start = await executor.ExecuteAsync(await DataExportTestKit.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 Task OpenAppAsync(IdentityAuthorizationHttpProof proof) => + DataExportTestKit.OpenAppAsync(proof.Database.AppConnectionString); + + /// 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 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/DataRequestOperatorOperationsTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestOperatorOperationsTests.cs new file mode 100644 index 000000000..034afb3ec --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestOperatorOperationsTests.cs @@ -0,0 +1,835 @@ +using System.Text.Json; +using FluentAssertions; +using LearnStack.Api.Composition; +using LearnStack.Infrastructure.Audit; +using LearnStack.Infrastructure.MultiTenancy; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.Modules.Identity.Infrastructure.DataRequests; +using LearnStack.Modules.Tenancy.Application.Audit; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Secrets; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using LearnStack.Tests.Fixtures; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// The operator's data-request owner against a real database, the real platform scope and the request guard's platform +/// arm (ADR-0107 § 8, ADR-0108 § 8): the inspection's four lists, its cursors and plans, and the erasure completion's one +/// transaction, its refusals, its repeat and its failures. The Audit executor is a recording double here except in the one +/// test that runs the real one through the scope; its own SQL is proven by its own suite. Fixture rows are written by the superuser with the guards paused, in a disposable database; +/// every statement under test runs as learnstack_platform through the scope, and every read-back of a column the +/// platform role is not granted runs as learnstack_app announcing the row's group. +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed class DataRequestOperatorOperationsTests(SchemaFixture schema) +{ + private static readonly Guid Tenant = SchemaFixture.TenantA; + private static readonly Guid Branch = SchemaFixture.OrgA1; + + [Fact] + public async Task Each_list_shows_exactly_its_rows_oldest_due_first_and_metadata_only() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var awaitingFanout = await proof.RequestAsync("erasure", "closure_fanout", "awaiting_privileged_step", "now() - interval '1 day'"); + var awaitingSelf = await proof.RequestAsync("erasure", "self", "awaiting_privileged_step", "now() - interval '3 days'", Branch); + var overdueErasure = await proof.RequestAsync("erasure", "administrator", "scheduled", "now() - interval '30 hours'"); + var overdueClosure = await proof.RequestAsync("closure", "self", "scheduled", "now() - interval '2 days'"); + await proof.RequestAsync("erasure", "self", "scheduled", "now() - interval '1 hour'"); + var stuckFanout = await proof.RequestAsync("erasure", "closure_fanout", "fulfilling", "now() - interval '3 hours'"); + var stuckExport = await proof.RequestAsync("export", "self", "fulfilling", "now() - interval '5 hours'", Branch); + await proof.RequestAsync("erasure", "closure_fanout", "fulfilling", "now() - interval '90 minutes'"); + await proof.RequestAsync("erasure", "self", "completed", "now() - interval '4 days'"); + var expiredAvailable = await proof.ArtifactAsync("available", "now() - interval '8 days'"); + var expiredMarked = await proof.ArtifactAsync("expired", "now() - interval '9 days'", Branch); + await proof.ArtifactAsync("available", "now() - interval '1 day'"); + await proof.ArtifactAsync("purged", "now() - interval '10 days'"); + await proof.ArtifactAsync("revoked", "now() - interval '2 days'"); + var owner = proof.Owner(); + + var awaiting = await owner.InspectAsync(Proof.Admission(), Query(DataRequestInspectionState.AwaitingPrivilegedStep)); + var overdue = await owner.InspectAsync(Proof.Admission(), Query(DataRequestInspectionState.OverdueScheduled)); + var stuck = await owner.InspectAsync(Proof.Admission(), Query(DataRequestInspectionState.StuckFulfilling)); + var expired = await owner.InspectAsync(Proof.Admission(), Query(DataRequestInspectionState.ExpiredArtifact)); + + awaiting!.Items.Select(item => item.RequestId).Should().Equal([awaitingSelf.Id, awaitingFanout.Id], + "the self erasure fell due two days ago when its window ended, the fan-out a day ago when it was created"); + overdue!.Items.Select(item => item.RequestId).Should().Equal([overdueClosure.Id, overdueErasure.Id], + "a window that ended is overdue whatever the kind, and one still open is not listed"); + stuck!.Items.Select(item => item.RequestId).Should().Equal([stuckExport.Id, stuckFanout.Id], + "only what is still fulfilling two hours after it fell due is stuck"); + expired!.Items.Select(item => item.Artifact!.ArtifactId).Should().Equal(new[] { expiredMarked.Artifact!.Value, expiredAvailable.Artifact!.Value }, + "an unpurged artifact past its expiry is listed, a readable, purged or revoked one is not"); + + var self = awaiting.Items[0]; + (self.TenantId, self.OrganizationId, self.Kind, self.Origin, self.Status).Should().Be( + (Tenant, Branch, "erasure", "self", "awaiting_privileged_step")); + self.ExecuteAt.Should().Be(self.CreatedAt + DataRequestLimits.CancellationWindow); + self.Artifact.Should().BeNull(); + var artifact = expired.Items[0]; + (artifact.RequestId, artifact.Kind, artifact.Status, artifact.OrganizationId).Should().Be( + (expiredMarked.Id, "export", "completed", Branch), "the artifact list names the export it belongs to and its group"); + (artifact.Artifact!.Status, artifact.Artifact.ExpiresAt < DateTimeOffset.UtcNow).Should().Be(("expired", true)); + + var shown = JsonSerializer.Serialize(new object[] { awaiting, overdue, stuck, expired }); + foreach (var row in new[] { awaitingFanout, awaitingSelf, overdueErasure, overdueClosure, stuckFanout, stuckExport, expiredAvailable }) + { + shown.Should().NotContain(row.Subject.ToString("D"), "no list names the subject").And + .NotContain(row.Membership.ToString("D"), "or the frozen snapshot"); + } + } + + [Fact] + public async Task Pages_cover_a_list_without_a_repeat_or_a_gap_and_a_cursor_belongs_to_the_list_that_issued_it() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var ids = new List(); + for (var index = 0; index < 5; index++) + { + // Equal due instants: the order and the cursor rest on the request's own identifier. + ids.Add((await proof.RequestAsync("erasure", "closure_fanout", "awaiting_privileged_step", "'2026-11-01 12:00:00.000001+00'")).Id); + } + + var owner = proof.Owner(); + var seen = new List(); + string? cursor = null; + var pages = 0; + do + { + var page = await owner.InspectAsync(Proof.Admission(), Query(DataRequestInspectionState.AwaitingPrivilegedStep, cursor, 2)); + seen.AddRange(page!.Items.Select(item => item.RequestId)); + cursor = page.NextCursor; + pages++; + } + while (cursor is not null && pages < 10); + + pages.Should().Be(3); + seen.Should().Equal(ids.Order(), "every row once, by its own key when the instants are equal"); + + var issued = (await owner.InspectAsync(Proof.Admission(), Query(DataRequestInspectionState.AwaitingPrivilegedStep, null, 1)))!.NextCursor; + issued.Should().NotBeNull(); + var refused = Proof.Admission(); + (await owner.InspectAsync(refused, Query(DataRequestInspectionState.OverdueScheduled, issued, 10))).Should().BeNull( + "a cursor carries its list, so it cannot move another one"); + (await owner.InspectAsync(Proof.Admission(), Query(DataRequestInspectionState.ExpiredArtifact, issued, 10))).Should().BeNull(); + (await owner.InspectAsync(Proof.Admission(), Query(DataRequestInspectionState.AwaitingPrivilegedStep, "not-a-cursor", 10))).Should().BeNull(); + (await proof.AuditAsync(refused.Operator.CorrelationId!)).Should().BeEmpty("a refused cursor enters no scope"); + (await owner.InspectAsync(Proof.Admission(), Query(DataRequestInspectionState.AwaitingPrivilegedStep, issued, 10)))!.Items + .Should().HaveCount(4, "the cursor still moves the list that issued it"); + } + + [Fact] + public async Task Each_page_writes_one_entry_row_naming_the_inspection_with_its_ticket_and_no_result_row() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var awaiting = await proof.RequestAsync("erasure", "self", "awaiting_privileged_step", "now() - interval '3 days'"); + var admission = Proof.Admission("INC-310"); + + var page = await proof.Owner().InspectAsync(admission, Query(DataRequestInspectionState.AwaitingPrivilegedStep)); + + page!.Items.Should().ContainSingle().Which.RequestId.Should().Be(awaiting.Id); + var entry = (await proof.AuditAsync(admission.Operator.CorrelationId!)).Should() + .ContainSingle("the scope reads and changes nothing, so it writes no result row").Which; + (entry.Operation, entry.Reason, entry.Tenant).Should().Be( + (PlatformAdminScope.EnterOperation, "data_request_inspect", TenantId.PlatformSentinel.Value)); + entry.Metadata.Should().Contain("INC-310", "a sentinel-tenant row is unreadable to every tenant, so it carries the ticket"); + (await proof.ReadAsync(awaiting)).Version.Should().Be(2, "the inspection changed nothing"); + } + + [Fact] + public async Task Every_list_is_an_ordered_scan_of_its_partial_index_with_no_sort() + { + // The statement is the text the inspection runs. Sequential and bitmap scans are disabled so that the only plan + // left is an ordered scan of an index: the index absent from the plan, or a Sort above it, means the statement's + // predicate or order no longer matches it, and a page would scan and sort every request or artifact. + await using var proof = await Proof.CreateAsync(schema.Postgres); + await proof.SqlAsync($""" + SET session_replication_role = replica; + CREATE TEMP TABLE bulk AS SELECT g, uuidv7() AS request, uuidv7() AS artifact, uuidv7() AS subject + FROM generate_series(1, 6000) g; + INSERT INTO data_subject_requests (id, tenant_id, kind, origin, subject_user_id, requester_user_id, status, + membership_snapshot, execute_at, completed_at, created_at, created_by, row_version) + SELECT request, '{Tenant}', 'erasure', 'self', subject, subject, + (ARRAY['scheduled','fulfilling','awaiting_privileged_step','completed','cancelled'])[1 + g % 5], + jsonb_build_array(uuidv7()::text), now() - make_interval(hours => g) + interval '24 hours', + CASE WHEN g % 5 = 3 THEN now() END, now() - make_interval(hours => g), subject, 2 + FROM bulk WHERE g <= 3000; + INSERT INTO data_subject_requests (id, tenant_id, kind, origin, subject_user_id, requester_user_id, status, + membership_snapshot, completed_at, created_at, created_by, row_version) + SELECT request, '{Tenant}', 'export', 'self', subject, subject, 'completed', jsonb_build_array(uuidv7()::text), + now() - make_interval(days => 8) + interval '1 hour', now() - make_interval(days => 8), subject, 2 + FROM bulk WHERE g > 3000; + INSERT INTO data_export_artifacts (id, tenant_id, request_id, subject_user_id, status, byte_count, chunk_count, + key_version, expires_at, purged_at, created_at, created_by) + SELECT artifact, '{Tenant}', request, subject, CASE WHEN g % 30 = 0 THEN 'expired' ELSE 'purged' END, 100, 1, 'v1', + now() - make_interval(days => 1, mins => g), CASE WHEN g % 30 = 0 THEN NULL ELSE now() - make_interval(days => 1, mins => g) END, + now() - make_interval(days => 8, mins => g), '{UserId.SystemActor.Value}' + FROM bulk WHERE g > 3000; + ANALYZE data_subject_requests; + ANALYZE data_export_artifacts; + """); + await using var platform = (NpgsqlConnection)await PostgresFixture.OpenAsync(proof.Database.PlatformConnectionString); + + async Task Plan(DataRequestInspectionState state, bool afterCursor) + { + await using var command = new NpgsqlCommand( + "SET enable_seqscan = off; SET enable_bitmapscan = off; EXPLAIN (FORMAT JSON) " + + DataRequestOperatorOperations.InspectionSql(state, afterCursor), platform); + command.Parameters.AddWithValue("size", 21); + if (state == DataRequestInspectionState.StuckFulfilling) command.Parameters.AddWithValue("stuck", DataRequestLimits.StuckFulfillingAfter); + if (afterCursor) + { + command.Parameters.AddWithValue("after", new DateTimeOffset(2026, 10, 1, 12, 0, 0, TimeSpan.Zero)); + command.Parameters.AddWithValue("key", Guid.CreateVersion7()); + } + + return (await command.ExecuteScalarAsync())!.ToString()!; + } + + foreach (var state in Enum.GetValues()) + { + foreach (var afterCursor in new[] { false, true }) + { + var plan = await Plan(state, afterCursor); + var index = state == DataRequestInspectionState.ExpiredArtifact + ? "ix_data_export_artifacts_unpurged_expiry" : "ix_data_subject_requests_operator_due"; + plan.Should().Contain(index, $"{state}, after a cursor: {afterCursor}").And.NotContain("\"Node Type\": \"Sort\"") + .And.NotContain("Incremental Sort").And.NotContain("Seq Scan"); + } + } + + await using var definitions = new NpgsqlCommand( + "SELECT string_agg(indexdef, ' | ' ORDER BY indexname) FROM pg_indexes WHERE indexname IN " + + "('ix_data_subject_requests_operator_due', 'ix_data_export_artifacts_unpurged_expiry')", platform); + var indexes = (string)(await definitions.ExecuteScalarAsync())!; + indexes.Should().Contain("(expires_at, id) WHERE (status = ANY (ARRAY['available'::text, 'expired'::text]))") + .And.Contain("(status, COALESCE(execute_at, created_at), id) WHERE (status = ANY (ARRAY['scheduled'::text, " + + "'fulfilling'::text, 'awaiting_privileged_step'::text]))"); + } + + [Fact] + public async Task A_completion_redacts_completes_and_records_in_one_transaction_from_the_row_s_own_subject() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var request = await proof.RequestAsync("erasure", "administrator", "awaiting_privileged_step", "now() - interval '3 days'", Branch, + """{"consent_evidence":2,"request_receipt":1,"audit_actor_reference":9}"""); + var report = new AuditRedactionReport( + 12, + new Dictionary { [AuditRedactedColumn.IpAddress] = 5, [AuditRedactedColumn.AfterState] = 3 }, + [ + new(RetainedReferenceKind.AuditActorReference, 4), new(RetainedReferenceKind.AuditMetadataReference, 2), + new(RetainedReferenceKind.UnscopedAuditRows, 1), + ]); + var redactor = new RecordingRedactor(report); + var admission = Proof.Admission("INC-311", PlatformOperations.ErasureComplete); + + var result = await proof.Owner(redactor).CompleteErasureAsync(admission, request.Id); + + result.Outcome.Should().Be(ErasureCompletionOutcome.Completed); + result.TenantId.Should().Be(Tenant); + result.Report.Should().BeSameAs(report); + var expected = new Dictionary + { + ["consent_evidence"] = 2, + ["request_receipt"] = 1, + ["audit_actor_reference"] = 4, + ["audit_metadata_reference"] = 2, + ["unscoped_audit_rows"] = 1, + }; + result.Retained.Should().BeEquivalentTo(expected, "the tenant side's kinds stay and the audit log's are set from the report"); + + var plan = redactor.Plans.Should().ContainSingle().Which; + (plan.Subject.RequestId, plan.Subject.Kind, plan.Subject.Origin, plan.Subject.SubjectUserId.Value).Should().Be( + (request.Id, DataRequestKind.Erasure, DataRequestOrigin.Administrator, request.Subject)); + (plan.TenantId.Value, plan.OrganizationId?.Value, plan.WholeTenant).Should().Be((Tenant, (Guid?)Branch, false), + "an administrator's erasure redacts its group's rows only"); + plan.Subject.MembershipIds.Should().Equal([request.Membership], "the plan is the row's frozen snapshot"); + + var stored = await proof.ReadAsync(request); + stored.Status.Should().Be("completed"); + stored.Version.Should().Be(3, "the completion steps the version once"); + stored.CompletedAt.Should().Be(stored.UpdatedAt, "the guard stamps both from one database clock"); + stored.CompletedAt.Should().Be(result.CompletedAt); + stored.CompletedAt!.Value.Should().BeCloseTo(DateTimeOffset.UtcNow, TimeSpan.FromMinutes(1)); + stored.UpdatedBy.Should().Be(UserId.SystemActor.Value, "an operator is not a user"); + JsonSerializer.Deserialize>(stored.Result).Should().BeEquivalentTo(expected); + + var rows = await proof.AuditAsync(admission.Operator.CorrelationId!); + rows.Should().HaveCount(2, "the entry row and one result row"); + var entry = rows.Single(row => row.Operation == PlatformAdminScope.EnterOperation); + (entry.Tenant, entry.Reason).Should().Be((TenantId.PlatformSentinel.Value, "erasure_complete")); + entry.Metadata.Should().Contain("INC-311"); + var recorded = rows.Single(row => row.Operation == "audit.redaction.apply"); + (recorded.Tenant, recorded.Module, recorded.Reason, recorded.Actor, recorded.EntityType, recorded.EntityId).Should().Be( + (Tenant, "audit", "erasure_complete", (Guid?)null, "DataSubjectRequest", request.Id.ToString("D"))); + recorded.Metadata.Should().NotContain("INC-311", "the tenant can read its own row, so it never carries the ticket"); + JsonDocument.Parse(recorded.Before).RootElement.GetProperty("status").GetString().Should().Be("awaiting_privileged_step"); + using var after = JsonDocument.Parse(recorded.After); + after.RootElement.GetProperty("status").GetString().Should().Be("completed"); + after.RootElement.GetProperty("rows_selected").GetInt64().Should().Be(12); + after.RootElement.GetProperty("redacted").GetProperty("ip_address").GetInt64().Should().Be(5); + after.RootElement.GetProperty("retained").GetProperty("audit_actor_reference").GetInt64().Should().Be(4); + recorded.After.Should().NotContain(request.Subject.ToString("D")).And.NotContain(request.Membership.ToString("D")); + } + + [Fact] + public async Task A_repeat_answers_the_recorded_result_and_writes_no_second_row() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var request = await proof.RequestAsync("erasure", "self", "awaiting_privileged_step", "now() - interval '1 day'", + Branch, """{"request_receipt":1}"""); + var redactor = new RecordingRedactor(new AuditRedactionReport( + 1, new Dictionary(), [new(RetainedReferenceKind.AuditEntityReference, 3)])); + var owner = proof.Owner(redactor); + var first = await owner.CompleteErasureAsync(Proof.Admission(operation: PlatformOperations.ErasureComplete), request.Id); + var repeat = Proof.Admission(operation: PlatformOperations.ErasureComplete); + + var second = await owner.CompleteErasureAsync(repeat, request.Id); + + second.Outcome.Should().Be(ErasureCompletionOutcome.AlreadyCompleted); + (second.TenantId, second.Status, second.CompletedAt).Should().Be((Tenant, "completed", first.CompletedAt)); + second.Retained.Should().BeEquivalentTo(first.Retained, "the recorded result, read back from the request"); + second.Report.Should().BeNull("a repeat redacts nothing; the counts are in the first act's row"); + var plan = redactor.Plans.Should().ContainSingle("the repeat never reached the executor").Which; + (plan.Subject.Origin, plan.OrganizationId?.Value, plan.WholeTenant).Should().Be((DataRequestOrigin.Self, (Guid?)Branch, true), + "a person's own erasure, filed in a branch, still redacts the person's rows in the whole tenant"); + (await proof.AuditAsync(repeat.Operator.CorrelationId!)).Should().ContainSingle() + .Which.Operation.Should().Be(PlatformAdminScope.EnterOperation, "the repeat is on the record by its entry row alone"); + (await proof.ResultRowsAsync(request.Id)).Should().Be(1, "one completion, one result row"); + (await proof.ReadAsync(request)).Version.Should().Be(3); + } + + [Fact] + public async Task A_closure_s_fan_out_erasure_is_refused_in_its_every_status_and_nothing_changes() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var redactor = new RecordingRedactor(); + var owner = proof.Owner(redactor); + foreach (var status in new[] { "awaiting_privileged_step", "completed" }) + { + var request = await proof.RequestAsync("erasure", "closure_fanout", status, "now() - interval '3 days'"); + var before = await proof.ReadAsync(request); + + var result = await owner.CompleteErasureAsync(Proof.Admission(operation: PlatformOperations.ErasureComplete), request.Id); + + result.Outcome.Should().Be(ErasureCompletionOutcome.ClosureFanout, "only that closure's finalization completes it: " + status); + (await proof.ReadAsync(request)).Should().Be(before, "a refused completion changes nothing"); + (await proof.ResultRowsAsync(request.Id)).Should().Be(0, "no result row describes a refused act"); + } + + redactor.Plans.Should().BeEmpty("no refused request reached the executor"); + } + + [Fact] + public async Task A_completion_refuses_a_missing_request_another_kind_and_every_status_but_awaiting_and_changes_nothing() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var redactor = new RecordingRedactor(); + var owner = proof.Owner(redactor); + var export = await proof.RequestAsync("export", "self", "completed", "now() - interval '2 days'"); + var closure = await proof.RequestAsync("closure", "self", "fulfilling", "now() - interval '2 days'"); + var refusals = new List<(Proof.Row Row, ErasureCompletionOutcome Outcome, string Status)> + { + (export, ErasureCompletionOutcome.NotErasure, "completed"), + (closure, ErasureCompletionOutcome.NotErasure, "fulfilling"), + }; + foreach (var status in new[] { "scheduled", "fulfilling", "blocked", "failed", "cancelled" }) + { + refusals.Add((await proof.RequestAsync("erasure", "self", status, "now() - interval '3 days'"), + ErasureCompletionOutcome.NotAwaiting, status)); + } + + var missing = Proof.Admission(operation: PlatformOperations.ErasureComplete); + (await owner.CompleteErasureAsync(missing, Guid.CreateVersion7())).Outcome.Should().Be(ErasureCompletionOutcome.NotFound); + (await proof.AuditAsync(missing.Operator.CorrelationId!)).Should().ContainSingle() + .Which.Operation.Should().Be(PlatformAdminScope.EnterOperation); + foreach (var (row, outcome, status) in refusals) + { + var before = await proof.ReadAsync(row); + var admission = Proof.Admission(operation: PlatformOperations.ErasureComplete); + + var result = await owner.CompleteErasureAsync(admission, row.Id); + + (result.Outcome, result.Status, result.TenantId).Should().Be((outcome, status, (Guid?)Tenant), status); + (await proof.ReadAsync(row)).Should().Be(before, "a refused completion changes nothing: " + status); + (await proof.AuditAsync(admission.Operator.CorrelationId!)).Should().ContainSingle(status) + .Which.Operation.Should().Be(PlatformAdminScope.EnterOperation, "only the entry row records the attempt"); + } + + redactor.Plans.Should().BeEmpty("no refused request reached the executor"); + } + + [Fact] + public async Task A_failed_redaction_or_result_row_leaves_the_request_awaiting_and_only_the_entry_on_the_record() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var request = await proof.RequestAsync("erasure", "self", "awaiting_privileged_step", "now() - interval '3 days'"); + var before = await proof.ReadAsync(request); + + async Task Fails(DataRequestOperatorOperations owner) + { + var admission = Proof.Admission(operation: PlatformOperations.ErasureComplete); + var act = async () => await owner.CompleteErasureAsync(admission, request.Id); + var failure = (await act.Should().ThrowAsync()).Which; + (await proof.ReadAsync(request)).Should().Be(before, "nothing of the act committed"); + (await proof.AuditAsync(admission.Operator.CorrelationId!)).Should().ContainSingle() + .Which.Operation.Should().Be(PlatformAdminScope.EnterOperation); + return failure; + } + + (await Fails(proof.Owner(new RecordingRedactor(failure: new InvalidOperationException("forced defect"))))) + .Should().BeOfType("a defect is not retryable and is not dressed as one"); + var transient = await Fails(proof.Owner(new RecordingRedactor(failure: new TimeoutException("forced timeout")))); + transient.Should().BeOfType() + .Which.CommitOutcomeUnknown.Should().BeFalse("nothing was sent to commit, and the redaction is idempotent"); + (await Fails(proof.Owner(new RecordingRedactor(), Proof.FailingResultStore()))) + .Should().BeOfType("a MUST row that cannot be written refuses the act"); + (await proof.ResultRowsAsync(request.Id)).Should().Be(0); + + (await proof.Owner(new RecordingRedactor()).CompleteErasureAsync(Proof.Admission(operation: PlatformOperations.ErasureComplete), request.Id)) + .Outcome.Should().Be(ErasureCompletionOutcome.Completed, "each failure left the request as it was, so a repeat completes it"); + } + + [Fact] + public async Task A_commit_whose_answer_is_lost_is_the_unknown_outcome_and_a_repeat_settles_it() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var request = await proof.RequestAsync("erasure", "self", "awaiting_privileged_step", "now() - interval '3 days'"); + var lost = new DataRequestOperatorOperations(new LostCommitScope(proof.Scope(new RecordingRedactor()))); + + var act = async () => await lost.CompleteErasureAsync(Proof.Admission(operation: PlatformOperations.ErasureComplete), request.Id); + + var failure = (await act.Should().ThrowAsync()).Which; + failure.CommitOutcomeUnknown.Should().BeTrue("the commit was sent, so the act may have landed"); + failure.InnerException.Should().BeOfType("the cause is kept for the route's log"); + (await proof.Owner(new RecordingRedactor()).CompleteErasureAsync(Proof.Admission(operation: PlatformOperations.ErasureComplete), request.Id)) + .Outcome.Should().Be(ErasureCompletionOutcome.Completed, "this commit never reached the database, so the repeat completes it"); + } + + [Fact] + public async Task Two_concurrent_completions_serialize_on_the_row_and_the_second_finds_the_first() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var request = await proof.RequestAsync("erasure", "self", "awaiting_privileged_step", "now() - interval '3 days'"); + var redactor = new RecordingRedactor(hold: true); + var owner = proof.Owner(redactor); + + var first = owner.CompleteErasureAsync(Proof.Admission(operation: PlatformOperations.ErasureComplete), request.Id); + ErasureCompletionResult[] outcomes; + try + { + await redactor.Entered.Task.WaitAsync(TimeSpan.FromSeconds(30)); + var second = owner.CompleteErasureAsync(Proof.Admission(operation: PlatformOperations.ErasureComplete), request.Id); + await proof.WaitUntilALockIsAwaitedAsync(second, "the second completion waits on the first's row lock"); + redactor.Release.SetResult(); + outcomes = await Task.WhenAll(first, second); + } + finally + { + // A failed wait must not leave the first act holding its transaction open past the test. + redactor.Release.TrySetResult(); + } + + + outcomes.Select(result => result.Outcome).Should().Equal( + ErasureCompletionOutcome.Completed, ErasureCompletionOutcome.AlreadyCompleted); + redactor.Plans.Should().ContainSingle("the second read the committed completion and redacted nothing"); + (await proof.ResultRowsAsync(request.Id)).Should().Be(1); + } + + [Fact] + public async Task The_real_executor_redacts_through_the_scope_and_its_report_commits_with_the_request() + { + await using var proof = await Proof.CreateAsync(schema.Postgres); + var request = await proof.RequestAsync("erasure", "self", "awaiting_privileged_step", "now() - interval '3 days'"); + Guid actor = Guid.CreateVersion7(), entity = Guid.CreateVersion7(), payload = Guid.CreateVersion7(), + unrelated = Guid.CreateVersion7(), foreign = Guid.CreateVersion7(), course = Guid.CreateVersion7(); + var other = Guid.CreateVersion7(); + await proof.SqlAsync($$""" + INSERT INTO audit_log (id, "timestamp", tenant_id, organization_id, actor_user_id, actor_email, module, operation, + operation_type, operation_class, entity_type, entity_id, outcome, after_state, correlation_id, ip_address, user_agent) + VALUES + ('{{actor}}', clock_timestamp(), '{{Tenant}}', NULL, '{{request.Subject}}', 'p@example.test', 'education', 'e2e.row', + 'Update', 'Must', 'Course', '{{course}}', 'success', NULL, '00-{{actor:N}}-01', '198.51.100.7', 'UA/1.0'), + ('{{entity}}', clock_timestamp(), '{{Tenant}}', NULL, '{{other}}', 'a@example.test', 'identity', 'e2e.row', + 'Update', 'Must', 'Membership', '{{request.Membership}}', 'success', NULL, '00-{{entity:N}}-01', '198.51.100.7', 'UA/1.0'), + ('{{payload}}', clock_timestamp(), '{{Tenant}}', '{{Branch}}', '{{other}}', 'a@example.test', 'education', 'e2e.row', + 'Update', 'Must', 'Course', '{{course}}', 'success', + '{"Id":"{{course}}","CreatedBy":"{{other}}","UpdatedBy":"{{request.Subject}}"}', '00-{{payload:N}}-01', '198.51.100.7', 'UA/1.0'), + ('{{unrelated}}', clock_timestamp(), '{{Tenant}}', NULL, '{{other}}', 'a@example.test', 'education', 'e2e.row', + 'Update', 'Must', 'Course', '{{course}}', 'success', + '{"Id":"{{course}}","CreatedBy":"{{other}}","UpdatedBy":"{{other}}"}', '00-{{unrelated:N}}-01', '198.51.100.7', 'UA/1.0'), + ('{{foreign}}', clock_timestamp(), '{{SchemaFixture.TenantB}}', NULL, '{{request.Subject}}', 'p@example.test', 'education', + 'e2e.row', 'Update', 'Must', 'Course', '{{course}}', 'success', + '{"Id":"{{course}}","UpdatedBy":"{{request.Subject}}"}', '00-{{foreign:N}}-01', '198.51.100.7', 'UA/1.0') + """); + var services = new ServiceCollection(); + services.AddIdentityContextualFoundation(); + services.AddDataExportCustody(new ConfigurationBuilder().Build()); + await using var provider = services.BuildServiceProvider(); + var executor = new AuditRedactionExecutor(provider.GetServices()); + var admission = Proof.Admission("INC-312", PlatformOperations.ErasureComplete); + + var result = await proof.Owner(executor).CompleteErasureAsync(admission, request.Id); + + result.Outcome.Should().Be(ErasureCompletionOutcome.Completed); + var report = result.Report.Should().NotBeNull().And.Subject.As(); + report.RowsSelected.Should().Be(3, "the actor row, the Membership row and the payload row of a person's own request"); + (report.Redacted[AuditRedactedColumn.IpAddress], report.Redacted[AuditRedactedColumn.UserAgent], + report.Redacted[AuditRedactedColumn.ActorEmail], report.Redacted[AuditRedactedColumn.AfterState]) + .Should().Be((3L, 3L, 3L, 1L)); + result.Retained.Should().Contain(new KeyValuePair("audit_actor_reference", 1)) + .And.Contain(new KeyValuePair("audit_entity_reference", 1)); + + foreach (var selected in new[] { actor, entity, payload }) + { + (await proof.AuditColumnsAsync(selected)).Should().Match( + row => row.Address == null && row.Agent == null && row.Email == null, "{0} is selected", selected); + } + + var redacted = JsonDocument.Parse((await proof.AuditColumnsAsync(payload)).After!).RootElement; + redacted.GetProperty("UpdatedBy").GetString().Should().Be(SensitiveTokenCatalog.RedactedValue); + redacted.GetProperty("CreatedBy").GetString().Should().Be(other.ToString("D"), "another person's value at the same path stays"); + foreach (var kept in new[] { unrelated, foreign }) + { + (await proof.AuditColumnsAsync(kept)).Should().Match( + row => row.Address == "198.51.100.7" && row.Agent == "UA/1.0" && row.Email != null + && row.After!.Contains(kept == foreign ? request.Subject.ToString("D") : other.ToString("D")), + "{0} names no one of this request's tenant", kept); + } + + (await proof.ReadAsync(request)).Status.Should().Be("completed"); + (await proof.ResultRowsAsync(request.Id)).Should().Be(1, "the redaction's result row commits with the request"); + var repeat = await proof.Owner(executor).CompleteErasureAsync( + Proof.Admission(operation: PlatformOperations.ErasureComplete), request.Id); + repeat.Outcome.Should().Be(ErasureCompletionOutcome.AlreadyCompleted); + (await proof.ResultRowsAsync(request.Id)).Should().Be(1, "a repeat writes no second result row and redacts nothing"); + } + + private static DataRequestInspectionQuery Query(DataRequestInspectionState state, string? cursor = null, int limit = 10) => + new(state, cursor, limit); + + /// The Audit executor's stand-in: it records each plan, may hold the first call, and returns its report or fails. + private sealed class RecordingRedactor(AuditRedactionReport? report = null, Exception? failure = null, bool hold = false) : IAuditRedactor + { + public List Plans { get; } = []; + public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public async Task RedactAsync( + AuditRedactionPlan plan, PlatformAdmission admission, System.Data.Common.DbConnection connection, + System.Data.Common.DbTransaction transaction, CancellationToken cancellationToken = default) + { + admission.Operation.Should().BeSameAs(PlatformOperations.ErasureComplete); + Plans.Add(plan); + if (hold && Plans.Count == 1) + { + Entered.SetResult(); + await Release.Task; + } + + return failure is null + ? report ?? new AuditRedactionReport(0, new Dictionary(), []) + : throw failure; + } + } + + /// The real scope with a handle whose commit is never sent and whose answer is a timeout, as a lost reply. + private sealed class LostCommitScope(IPlatformAdminScope inner) : IPlatformAdminScope + { + public async Task EnterAsync( + PlatformAdmission admission, CancellationToken cancellationToken = default, + [System.Runtime.CompilerServices.CallerMemberName] string? callerMember = null, + [System.Runtime.CompilerServices.CallerFilePath] string? callerFile = null, + [System.Runtime.CompilerServices.CallerLineNumber] int callerLine = 0) => + new Handle(await inner.EnterAsync(admission, cancellationToken, callerMember, callerFile, callerLine)); + + private sealed class Handle(IPlatformAdminScopeHandle real) : IPlatformAdminScopeHandle + { + public Task ExecuteAsync(string sql, IReadOnlyList? parameters = null, CancellationToken cancellationToken = default) => + real.ExecuteAsync(sql, parameters, cancellationToken); + + public Task> QueryAsync( + string sql, IReadOnlyList? parameters, Func map, + CancellationToken cancellationToken = default) => real.QueryAsync(sql, parameters, map, cancellationToken); + + public Task WriteIntentAsync(PlatformResult intent, CancellationToken cancellationToken = default) => + real.WriteIntentAsync(intent, cancellationToken); + + public Task RedactAuditAsync(AuditRedactionPlan plan, CancellationToken cancellationToken = default) => + real.RedactAuditAsync(plan, cancellationToken); + + public Task WriteResultAsync(PlatformResult result, CancellationToken cancellationToken = default) => + real.WriteResultAsync(result, cancellationToken); + + public Task CommitAsync(CancellationToken cancellationToken = default) => + Task.FromException(new TimeoutException("forced lost commit")); + + public ValueTask DisposeAsync() => real.DisposeAsync(); + } + } + + private sealed record AuditRow( + Guid Tenant, string Module, string Operation, string? Reason, Guid? Actor, string? EntityType, string? EntityId, + string Before, string After, string Metadata); + + private sealed record AuditColumns(string? Address, string? Agent, string? Email, string? After); + + private sealed record StoredRequest( + string Status, long Version, DateTimeOffset? CompletedAt, DateTimeOffset? UpdatedAt, Guid? UpdatedBy, string Result); + + private sealed class Proof : IAsyncDisposable + { + private readonly PostgresFixture _postgres; + private readonly NpgsqlDataSource _platform; + + private Proof(PostgresFixture postgres, DisposableSchemaDatabase database) + { + _postgres = postgres; + Database = database; + _platform = LearnStack.Api.Composition.PersistenceCompositionExtensions.BuildPlatformDataSource(database.PlatformConnectionString); + } + + internal sealed record Row(Guid Id, Guid Subject, Guid Membership, Guid? Organization, Guid? Artifact = null); + + internal DisposableSchemaDatabase Database { get; } + + internal static async Task CreateAsync(PostgresFixture postgres) => + new(postgres, await DisposableSchemaDatabase.CreateAsync(postgres)); + + internal static PlatformAdmission Admission(string? ticket = null, PlatformOperation? operation = null) => + TestPlatformAdmissions.Admission( + operation ?? PlatformOperations.DataRequestInspect, ticket, correlationId: "00-data-request-" + Guid.NewGuid().ToString("N")); + + /// The scope as production builds it, with the real audit store and the given executor. + internal PlatformAdminScope Scope(IAuditRedactor? redactor = null, IServiceScopeFactory? audit = null) => new( + new PrivilegedDataSource(() => _platform), new AuditCatalog([new TenancyAuditCatalogSource()]), + audit ?? AuditServices(redactor), new SystemClock(), new SystemGuidFactory(), NullLogger.Instance); + + internal DataRequestOperatorOperations Owner(IAuditRedactor? redactor = null, IServiceScopeFactory? audit = null) => + new(Scope(redactor, audit is null ? null : WithRedactor(audit, redactor))); + + /// A store that writes the scope's entry row and fails every result row, as an outage between them would. + internal static IServiceScopeFactory FailingResultStore() => new ServiceCollection() + .AddScoped(_ => new ResultFailingStore(AuditServices(null).CreateScope().ServiceProvider.GetRequiredService())) + .BuildServiceProvider().GetRequiredService(); + + /// One request, written with the guards paused; the identifiers are fresh and its times follow its kind. + internal async Task RequestAsync( + string kind, string origin, string status, string createdAt, Guid? organization = null, string result = "{}") + { + var row = new Row(Guid.CreateVersion7(), Guid.CreateVersion7(), Guid.CreateVersion7(), organization); + var requester = origin switch + { + "self" => $"'{row.Subject}'", + "administrator" => $"'{Guid.CreateVersion7()}'", + _ => "NULL", + }; + var window = kind != "export" && origin != "closure_fanout"; + // A request that left its initial state was last stamped by its job, never after the present. + var initial = status is "requested" or "scheduled"; + const string Stamped = "LEAST(at + interval '25 hours', now())"; + await SqlAsync($""" + SET session_replication_role = replica; + INSERT INTO data_subject_requests (id, tenant_id, organization_id, kind, origin, subject_user_id, requester_user_id, + status, membership_snapshot, execute_at, result, completed_at, failure_reason, last_refusal, created_at, + created_by, updated_at, updated_by, row_version) + SELECT '{row.Id}', '{Tenant}', {Literal(organization)}, '{kind}', '{origin}', '{row.Subject}', {requester}, + '{status}', '["{row.Membership}"]'::jsonb, {(window ? "at + interval '24 hours'" : "NULL")}, '{result}'::jsonb, + {(status == "completed" ? Stamped : "NULL")}, + {(status == "failed" ? "'execution_failed'" : "NULL")}, {(status == "blocked" ? "'blocked_hold'" : "NULL")}, + at, COALESCE({requester}, '{UserId.SystemActor.Value}')::uuid, + {(initial ? "NULL" : Stamped)}, {(initial ? "NULL" : $"'{UserId.SystemActor.Value}'")}, {(initial ? 0 : 2)} + FROM (SELECT ({createdAt})::timestamptz AS at) AS created + """); + return row; + } + + /// A completed export and its artifact in the given status, created at the given time. + internal async Task ArtifactAsync(string status, string createdAt, Guid? organization = null) + { + var request = await RequestAsync("export", "self", "completed", $"({createdAt}) - interval '1 hour'", organization); + var artifact = Guid.CreateVersion7(); + var purged = status is "revoked" or "purged"; + await SqlAsync($""" + SET session_replication_role = replica; + INSERT INTO data_export_artifacts (id, tenant_id, organization_id, request_id, subject_user_id, status, byte_count, + chunk_count, key_version, expires_at, purged_at, created_at, created_by) + SELECT '{artifact}', '{Tenant}', {Literal(organization)}, '{request.Id}', '{request.Subject}', '{status}', 100, 1, 'v1', + at + interval '7 days', {(purged ? "at + interval '1 day'" : "NULL")}, at, '{UserId.SystemActor.Value}' + FROM (SELECT ({createdAt})::timestamptz AS at) AS created + """); + return request with { Artifact = artifact }; + } + + /// The columns the platform role is not granted, read as the application role announcing the row's group. + internal async Task ReadAsync(Row row) + { + await using var app = await DataExportTestKit.OpenAppAsync(Database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await IdentityMembershipFixture.ScopeAsync(app, transaction, Tenant, row.Organization); + await using var command = new NpgsqlCommand( + "SELECT status, row_version, completed_at, updated_at, updated_by, result::text FROM data_subject_requests WHERE id = @id", + app, transaction); + command.Parameters.AddWithValue("id", row.Id); + await using var reader = await command.ExecuteReaderAsync(); + (await reader.ReadAsync()).Should().BeTrue("the row is visible to its own group"); + return new StoredRequest( + reader.GetString(0), reader.GetInt64(1), reader.IsDBNull(2) ? null : reader.GetFieldValue(2), + reader.IsDBNull(3) ? null : reader.GetFieldValue(3), reader.IsDBNull(4) ? null : reader.GetGuid(4), + reader.GetString(5)); + } + + internal async Task> AuditAsync(string correlation) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.PlatformConnectionString); + await using var command = new NpgsqlCommand(""" + SELECT tenant_id, module, operation, reason, actor_user_id, entity_type, entity_id, before_state::text, + after_state::text, metadata::text + FROM audit_log WHERE correlation_id = @c ORDER BY timestamp, id + """, connection); + command.Parameters.AddWithValue("c", correlation); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await reader.ReadAsync()) + { + rows.Add(new AuditRow( + reader.GetGuid(0), reader.GetString(1), reader.GetString(2), reader.IsDBNull(3) ? null : reader.GetString(3), + reader.IsDBNull(4) ? null : reader.GetGuid(4), reader.IsDBNull(5) ? null : reader.GetString(5), + reader.IsDBNull(6) ? null : reader.GetString(6), reader.IsDBNull(7) ? string.Empty : reader.GetString(7), + reader.IsDBNull(8) ? string.Empty : reader.GetString(8), reader.IsDBNull(9) ? string.Empty : reader.GetString(9))); + } + + return rows; + } + + internal async Task AuditColumnsAsync(Guid id) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.PlatformConnectionString); + await using var command = new NpgsqlCommand( + "SELECT host(ip_address), user_agent, actor_email, after_state::text FROM audit_log WHERE id = @id", connection); + command.Parameters.AddWithValue("id", id); + await using var reader = await command.ExecuteReaderAsync(); + (await reader.ReadAsync()).Should().BeTrue("the audit row exists"); + return new AuditColumns( + reader.IsDBNull(0) ? null : reader.GetString(0), reader.IsDBNull(1) ? null : reader.GetString(1), + reader.IsDBNull(2) ? null : reader.GetString(2), reader.IsDBNull(3) ? null : reader.GetString(3)); + } + + internal async Task ResultRowsAsync(Guid request) + { + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.PlatformConnectionString); + await using var command = new NpgsqlCommand( + "SELECT count(*) FROM audit_log WHERE operation = 'audit.redaction.apply' AND entity_id = @id", connection); + command.Parameters.AddWithValue("id", request.ToString("D")); + return (long)(await command.ExecuteScalarAsync())!; + } + + /// + /// Waits until a backend connected to this database waits on a lock, from pg_locks, instead of sleeping. A + /// row-lock waiter waits on the holder's transaction identifier, a lock with no database, so the backend is matched + /// through its session's database instead. + /// + internal async Task WaitUntilALockIsAwaitedAsync(Task contender, string because) + { + await using var observer = (NpgsqlConnection)await PostgresFixture.OpenAsync(Database.PlatformConnectionString); + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(30); + while (true) + { + contender.IsCompleted.Should().BeFalse(because); + await using var command = new NpgsqlCommand( + "SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_locks l JOIN pg_catalog.pg_stat_activity a ON a.pid = l.pid " + + "WHERE a.datname = current_database() AND NOT l.granted)", observer); + if ((bool)(await command.ExecuteScalarAsync())!) return; + DateTime.UtcNow.Should().BeBefore(deadline, because); + await Task.Delay(TimeSpan.FromMilliseconds(20)); + } + } + + internal Task SqlAsync(string sql) => _postgres.ExecuteAsSuperuserAsync(sql, RebindProofSupport.DatabaseOf(Database.MigrationConnectionString)); + + public async ValueTask DisposeAsync() + { + await _platform.DisposeAsync(); + await Database.DisposeAsync(); + } + + private static string Literal(Guid? value) => value is { } id ? $"'{id}'" : "NULL"; + + private static IServiceScopeFactory WithRedactor(IServiceScopeFactory audit, IAuditRedactor? redactor) => + redactor is null ? audit : new RedactorScopeFactory(audit, redactor); + + private static IServiceScopeFactory AuditServices(IAuditRedactor? redactor) => + (redactor is null ? new ServiceCollection() : new ServiceCollection().AddSingleton(redactor)) + .AddMetrics() + .AddLogging() + .AddScoped() + .AddSingleton() + .AddSingleton(new AuditCatalog([new TenancyAuditCatalogSource()])) + .AddSingleton(StaticTenantContextAccessor.Unresolved) + .AddScoped() + .AddSingleton(new Lazy( + () => throw new InvalidOperationException("The scope's rows are written on its own connection."))) + .AddScoped() + .BuildServiceProvider() + .GetRequiredService(); + } + + /// A store's service scope that also holds the executor, so a failing store and a redactor combine. + private sealed class RedactorScopeFactory(IServiceScopeFactory inner, IAuditRedactor redactor) : IServiceScopeFactory + { + public IServiceScope CreateScope() => new Scope(inner.CreateScope(), redactor); + + private sealed class Scope(IServiceScope inner, IAuditRedactor redactor) : IServiceScope, IServiceProvider + { + public IServiceProvider ServiceProvider => this; + + public object? GetService(Type type) => type == typeof(IAuditRedactor) ? redactor : inner.ServiceProvider.GetService(type); + + public void Dispose() => inner.Dispose(); + } + } + + private sealed class ResultFailingStore(IAuditStore store) : IAuditStore + { + public Task WritePlatformScopeAsync(AuditEntryDraft entry, System.Data.Common.DbConnection connection, + System.Data.Common.DbTransaction transaction, CancellationToken cancellationToken = default) => + store.WritePlatformScopeAsync(entry, connection, transaction, cancellationToken); + + public Task WritePlatformOperatorResultAsync(AuditEntryDraft entry, PlatformAdmission admission, + System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) => throw new AuditWriteFailedException("forced result failure"); + + public Task WriteGlobalIdentityPendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unit, + GlobalIdentityCreationReference creation, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task ReconcileGlobalIdentityAsync(AuditIntent intent, IReadOnlyList changes, + AuditIntentState state, DateTimeOffset timestamp, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WritePendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unitOfWork, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteStandaloneAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteBestEffortAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteJobTerminalAsync(AuditEntryDraft entry, JobTerminalTransition transition, + System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + + public Task WriteEventTerminalAsync(AuditEntryDraft entry, EventTerminalTransition transition, + System.Data.Common.DbConnection connection, System.Data.Common.DbTransaction transaction, + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + } +} 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 000000000..bb43ee124 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestSchemaSeed.cs @@ -0,0 +1,120 @@ +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 = await DataExportTestKit.OpenAppAsync(connectionString); + 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/DataRequestServiceStorageTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestServiceStorageTests.cs new file mode 100644 index 000000000..bab47e5d6 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestServiceStorageTests.cs @@ -0,0 +1,407 @@ +using System.Reflection; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Application.Messaging; +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.Errors; +using LearnStack.SharedKernel.Identifiers; +using Npgsql; +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 DataExportTestKit.CreateSeededDatabaseAsync(fixture.Postgres); + 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 DataExportTestKit.CreateSeededDatabaseAsync(fixture.Postgres); + 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().Be(DataRequestInsertion.AlreadyActive); + scope.Unit.IsRollbackOnly.Should().BeTrue(); + scope.Db.ChangeTracker.Entries().Should().NotContain(entry => entry.Entity == second); + } + + /// + /// ADR-0107 § 7: the request guard admits every person's and administrator's request only for a subject whose User is + /// Active, read under the subject's User fence. A filing that reaches the insertion after the person's account began + /// closing (a Begin that committed while the filing waited for the fence, or an administrator filing for a person whose + /// account is closing) is refused by the database, and the real creation core maps that refusal to the closed + /// subject_not_admitted business refusal: nothing is stored, nothing is submitted, and the transaction is + /// rollback-only. Every kind each role files is taken through the real store, eligibility, fences and guard; the live and + /// retained entries share this core. + /// + [Theory] + [InlineData("export", DataRequestRole.Subject)] + [InlineData("erasure", DataRequestRole.Subject)] + [InlineData("closure", DataRequestRole.Subject)] + [InlineData("export", DataRequestRole.Administrator)] + [InlineData("erasure", DataRequestRole.Administrator)] + public async Task A_filing_for_a_person_whose_account_is_closing_is_the_closed_subject_not_admitted_refusal(string kind, DataRequestRole role) + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(fixture.Postgres); + var person = Guid.CreateVersion7(); + var membership = Guid.CreateVersion7(); + await InsertUserAsync(database.AppConnectionString, person); + await using (var app = await DataExportTestKit.OpenAppAsync(database.AppConnectionString)) + { + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + await LockAsync(app, transaction, SchemaFixture.TenantA, person, false); + await InsertMemberAsync(app, transaction, SchemaFixture.TenantA, null, membership, person, + RoleId(SchemaFixture.TenantA, LearnStack.SharedKernel.Permissions.BuiltInRoleKey.Learner, + LearnStack.SharedKernel.Permissions.PermissionScope.Tenant)); + if (role == DataRequestRole.Administrator && kind == "erasure") + { + // An administrator erases only a person whose Membership of the group is already Revoked (ADR-0106 § 3). + await ExecuteAsync(app, transaction, """ + UPDATE public.memberships SET status='Revoked', deleted_at=clock_timestamp(), deleted_by=@system, + updated_at=clock_timestamp(), updated_by=@system, row_version=row_version+1 WHERE id=@member + """, ("member", membership), ("system", SystemActor)); + } + + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await transaction.CommitAsync(); + } + + // The closure's Begin, as its acquirer holds the fences: the User key, then the person's one participant tenant. + await using (var platform = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.PlatformConnectionString)) + { + await using var transaction = await platform.BeginTransactionAsync(); + await ExecuteAsync(platform, transaction, "SELECT pg_catalog.pg_advisory_xact_lock(@key)", + ("key", LearnStack.SharedKernel.Identity.IdentityAdvisoryLockKey.ForUser(UserId.From(person)))); + await ExecuteAsync(platform, transaction, "SELECT pg_catalog.pg_advisory_xact_lock(@key)", + ("key", LearnStack.SharedKernel.Identity.IdentityAdvisoryLockKey.ForTenant(TenantId.From(SchemaFixture.TenantA)))); + await ExecuteAsync(platform, transaction, "UPDATE public.users SET status='Closing' WHERE id=@user", ("user", person)); + await transaction.CommitAsync(); + } + + // No lock plan yet: the creation core takes its own, as the request pipeline's would. + await using (var scope = await DataExportTestKit.OpenAsync(database.AppConnectionString, SchemaFixture.TenantA, null, fenced: false)) + { + var service = Service(scope); + var caller = new DataRequestCaller(UserId.From(role == DataRequestRole.Subject ? person : AdminA), role, + _ => Task.FromResult(LearnStack.SharedKernel.Results.Result.Ok(LearnStack.SharedKernel.Results.None.Value))); + var subject = UserId.From(person); + var refused = (kind, role) switch + { + ("export", DataRequestRole.Subject) => await service.CreateExportAsync(caller, subject, CancellationToken.None), + ("erasure", DataRequestRole.Subject) => await service.CreateErasureAsync(caller, subject, CancellationToken.None), + ("closure", _) => await service.CreateClosureAsync(caller, subject, CancellationToken.None), + ("export", _) => await service.CreateExportForMembershipAsync(caller, membership, CancellationToken.None), + _ => await service.CreateErasureForMembershipAsync(caller, membership, CancellationToken.None), + }; + + refused.IsFailure.Should().BeTrue(); + refused.Error!.Code.Should().Be("business_rule_violation"); + refused.Error.Details!["$"].Single().Key.Should().Be("lockey_subject_not_admitted", + "the guard's refusal of the subject is a closed business refusal, never a storage fault"); + scope.Unit.IsRollbackOnly.Should().BeTrue("the refused insertion aborted the transaction"); + await scope.Frame.FailAsync(); + } + + await using var reader = await DataExportTestKit.OpenAppAsync(database.AppConnectionString); + await using var read = await reader.BeginTransactionAsync(); + await ScopeAsync(reader, read, SchemaFixture.TenantA); + (await ScalarAsync(reader, read, "SELECT count(*) FROM public.data_subject_requests WHERE subject_user_id=@person", ("person", person))) + .Should().Be(0, "nothing is stored"); + } + + /// + /// A storage wait past the five-second statement budget is the retryable storage failure (503), never a 500, and it + /// leaves the owner rollback-only: a cancellation behind an export job's request row lock, and a chunk read behind a + /// lock on the chunk table. + /// + [Theory] + [InlineData("request_row_lock")] + [InlineData("chunk_read")] + public async Task A_wait_past_the_statement_budget_is_the_retryable_storage_failure_and_leaves_the_owner_rollback_only(string wait) + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(fixture.Postgres); + await using var holder = (NpgsqlConnection)await PostgresFixture.OpenAsync(wait == "chunk_read" + ? database.MigrationConnectionString : database.AppConnectionString); + await using var held = await holder.BeginTransactionAsync(); + if (wait == "chunk_read") + await ExecuteAsync(holder, held, "LOCK TABLE public.data_export_chunks IN ACCESS EXCLUSIVE MODE"); + else + { + await ScopeAsync(holder, held, SchemaFixture.TenantA); + await ExecuteAsync(holder, held, "SELECT id FROM public.data_subject_requests WHERE id=@id FOR UPDATE", ("id", TenantWideA.Request)); + } + + await using var scope = await DataExportTestKit.OpenAsync(database.AppConnectionString, SchemaFixture.TenantA, null); + using var cipher = DataExportTestKit.Cipher(); + var started = System.Diagnostics.Stopwatch.StartNew(); + Func act = wait == "chunk_read" + ? () => DataExportArtifactStoreTests.Store(scope, cipher).ReadChunkAsync(new DataExportArtifactLocator(TenantWideA.Artifact!.Value, + new DataRequestScopeGroup(scope.Context.TenantId, null)), 0, CancellationToken.None) + : () => Store(scope).FindLockedAsync(DataSubjectRequestId.From(TenantWideA.Request), CancellationToken.None); + + (await act.Should().ThrowAsync()).Which.Error.Code.Should().Be("dependency_unavailable"); + started.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(20), "the budget bounds the wait"); + scope.Unit.IsRollbackOnly.Should().BeTrue("a timed-out statement leaves the owner unusable for anything but rollback"); + await held.RollbackAsync(); + } + + /// + /// ADR-0106 § 8: a receipt reads its export job's phase by the job's exact route. Among thousands of the tenant's + /// jobs of hundreds of other definitions, the generic plan of the reader's statement (the shape a parameterized + /// command is planned with) seeks ix_background_jobs_definition on the tenant and the definition key and + /// filters only the group's export jobs; with the index removed the same statement filters the tenant's history. Both + /// statements the reader runs, the single read and the page read, are explained verbatim: the test reads them from + /// the reader's own constants. + /// + [Fact] + public async Task The_job_phase_read_seeks_the_definition_index_instead_of_the_tenants_job_history() + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(fixture.Postgres); + var request = Guid.CreateVersion7(); + var parameters = BackgroundJobPayloadContract.Serialize(new DataExportJobParameters(request), typeof(DataExportJobParameters), + BackgroundJobPayloadKind.Parameters); + var definition = DataExportJobKeys.ExportFor(new DataRequestScopeGroup(TenantId.From(SchemaFixture.TenantA), null)).Value; + await using (var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await EducationSchemaSeed.AnnounceAsync(app, transaction, SchemaFixture.TenantA, null); + await SchemaQueries.ExecuteAsync(app, transaction, """ + INSERT INTO background_jobs (id, tenant_id, definition_key, profile, queue, parameters, original_due_at, traceparent) + SELECT uuidv7(), @tenant, 'fixture.backlog_' || (n % 400) || '.v1', 'transactional', 'fixture', '{}', + clock_timestamp() + interval '1 day', @trace FROM generate_series(1, 8000) n; + INSERT INTO background_jobs (id, tenant_id, definition_key, profile, queue, parameters, original_due_at, traceparent) + SELECT uuidv7(), @tenant, @definition, 'transactional', 'fixture', + CASE WHEN n = 1 THEN @parameters ELSE '{"requestId":"' || uuidv7() || '"}' END, + clock_timestamp() + interval '1 day', @trace FROM generate_series(1, 12) n; + """, ("tenant", SchemaFixture.TenantA), ("trace", BackgroundJobSchemaSeed.Traceparent), ("definition", definition), + ("parameters", parameters)); + await transaction.CommitAsync(); + } + + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString); + await SchemaQueries.ExecuteAsync(owner, null, "ANALYZE background_jobs"); + (await SchemaQueries.ReadStringsAsync(owner, """ + SELECT indexname || ':' || indexdef FROM pg_indexes + WHERE schemaname = 'public' AND indexname IN ('ix_background_jobs_definition', 'ix_data_subject_requests_group_page') + ORDER BY indexname + """)).Should().Equal( + "ix_background_jobs_definition:CREATE INDEX ix_background_jobs_definition ON public.background_jobs USING btree (tenant_id, definition_key, organization_id)", + "ix_data_subject_requests_group_page:CREATE INDEX ix_data_subject_requests_group_page ON public.data_subject_requests USING btree (tenant_id, organization_id, id)"); + + foreach (var page in new[] { false, true }) + { + var clean = await PhasePlanAsync(database, parameters, definition, page); + PlanIndexes(clean).Should().Contain("ix_background_jobs_definition", page ? "the page read" : "the single read"); + MaximumRowsRemoved(clean).Should().BeLessThan(100, "the seek reads the group's export jobs, not the tenant's history"); + } + + await using (var scope = await DataExportTestKit.OpenAsync(database.AppConnectionString, SchemaFixture.TenantA, null)) + { + var reader = new DataRequestJobPhaseReader(scope.Unit, scope.Context); + (await reader.ReadAsync(DataSubjectRequestId.From(request), DataRequestKind.Export, CancellationToken.None)) + .Should().Be(DataRequestJobPhase.Pending, "the reader finds its job"); + var unknown = DataSubjectRequestId.From(Guid.CreateVersion7()); + (await reader.ReadManyAsync([DataSubjectRequestId.From(request), unknown], DataRequestKind.Export, CancellationToken.None)).Should().BeEquivalentTo( + new Dictionary + { + [DataSubjectRequestId.From(request)] = DataRequestJobPhase.Pending, + [unknown] = DataRequestJobPhase.Unavailable, + }, "the page read finds its job among the group's other export jobs and none for a request without one"); + await scope.Frame.FailAsync(); + } + + await SchemaQueries.ExecuteAsync(owner, null, "DROP INDEX public.ix_background_jobs_definition"); + foreach (var page in new[] { false, true }) + { + var dirty = await PhasePlanAsync(database, parameters, definition, page); + PlanIndexes(dirty).Should().NotContain("ix_background_jobs_definition"); + MaximumRowsRemoved(dirty).Should().BeGreaterThanOrEqualTo(1000, "without it the same statement filters the tenant's history"); + } + } + + /// + /// ADR-0107 § 4's ticket bounds read by the database clock in one statement: the open tickets of one session binding + /// (a consumed one and another binding's do not count) and every ticket ever minted over the artifact. + /// + [Fact] + public async Task The_ticket_counts_read_one_bindings_open_tickets_and_every_ticket_ever_minted() + { + await using var database = await DataExportTestKit.CreateSeededDatabaseAsync(fixture.Postgres); + var artifact = TenantWideA.Artifact!.Value; + // The seeded ticket's binding is sha256(uuid_send(artifact)); uuid_send writes the identifier big-endian. + var seeded = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(artifact.ToByteArray(bigEndian: true))); + var other = Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData("other"u8)); + await using var scope = await DataExportTestKit.OpenAsync(database.AppConnectionString, SchemaFixture.TenantA, null); + await InsertTicketAsync(scope.Connection, scope.Transaction, Guid.CreateVersion7(), SchemaFixture.TenantA, null, artifact, PersonA); + var consumed = Guid.CreateVersion7(); + await ExecuteAsync(scope.Connection, scope.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,sha256(uuid_send(@id)),sha256('other'::bytea),now(),@subject,now()+interval '15 minutes') + """, ("id", consumed), ("tenant", SchemaFixture.TenantA), ("artifact", artifact), ("subject", PersonA)); + await ExecuteAsync(scope.Connection, scope.Transaction, + "UPDATE public.data_export_tickets SET consumed_at=now() WHERE id=@id", ("id", consumed)); + var store = new DataExportTicketStore(scope.Db, scope.Unit, scope.Context); + var id = DataExportArtifactId.From(artifact); + + (await store.CountAsync(id, seeded, CancellationToken.None)).Should().Be(new DataExportTicketCounts(2, 3), + "the seeded ticket and the new one share the seeded binding; the consumed one is another binding's"); + (await store.CountAsync(id, other, CancellationToken.None)).Should().Be(new DataExportTicketCounts(0, 3), + "a consumed ticket is no longer open, but it was minted"); + (await store.CountAsync(id, new string('0', 64), CancellationToken.None)).Should().Be(new DataExportTicketCounts(0, 3)); + await FluentActions.Awaiting(() => store.CountAsync(id, "not-a-digest", CancellationToken.None)) + .Should().ThrowAsync(); + await scope.Frame.FailAsync(); + } + + /// + /// One of the phase reader's two statements, read from its constant, explained as the generic plan a parameterized + /// command gets: the named parameters become positional ones of the types the reader binds. + /// + private static async Task PhasePlanAsync(DisposableSchemaDatabase database, string parameters, string definition, bool page) + { + var statement = (string)typeof(DataRequestJobPhaseReader) + .GetField(page ? "PageStatement" : "SingleStatement", BindingFlags.Static | BindingFlags.NonPublic)!.GetRawConstantValue()!; + var positional = statement.Replace("@tenant", "$1", StringComparison.Ordinal) + .Replace("@organization", "$2", StringComparison.Ordinal) + .Replace("@definition", "$3", StringComparison.Ordinal) + .Replace("@parameters", "$4", StringComparison.Ordinal); + positional.Should().NotContain("@", "every named parameter of the reader's statement is bound here"); + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await EducationSchemaSeed.AnnounceAsync(app, transaction, SchemaFixture.TenantA, null); + await SchemaQueries.ExecuteAsync(app, transaction, "DEALLOCATE ALL; SET LOCAL plan_cache_mode = force_generic_plan;\n" + + "PREPARE phase_read(uuid, uuid, text, " + (page ? "text[]" : "text") + ") AS\n" + positional + ";"); + // A generic plan is fixed before its arguments are seen, so these test-owned literals do not shape it. + var argument = "'" + parameters.Replace("'", "''", StringComparison.Ordinal) + "'"; + await using var command = new NpgsqlCommand("EXPLAIN (ANALYZE, FORMAT JSON) EXECUTE phase_read('" + + SchemaFixture.TenantA.ToString("D") + "'::uuid, NULL, '" + definition.Replace("'", "''", StringComparison.Ordinal) + "', " + + (page ? "ARRAY[" + argument + "]::text[]" : argument) + ")", app, transaction); + var plan = (string)(await command.ExecuteScalarAsync())!; + await SchemaQueries.ExecuteAsync(app, transaction, "DEALLOCATE phase_read"); + await transaction.RollbackAsync(); + return plan; + } + + private static string[] PlanIndexes(string json) + { + using var document = JsonDocument.Parse(json); + return Walk(document.RootElement[0].GetProperty("Plan")).Where(node => node.TryGetProperty("Index Name", out _)) + .Select(node => node.GetProperty("Index Name").GetString()!).ToArray(); + } + + private static long MaximumRowsRemoved(string json) + { + using var document = JsonDocument.Parse(json); + return Walk(document.RootElement[0].GetProperty("Plan")).Where(node => node.TryGetProperty("Rows Removed by Filter", out _)) + .Select(node => node.GetProperty("Rows Removed by Filter").GetInt64()).DefaultIfEmpty().Max(); + } + + private static IEnumerable Walk(JsonElement node) + { + yield return node; + if (node.TryGetProperty("Plans", out var children)) + foreach (var child in children.EnumerateArray()) + foreach (var descendant in Walk(child)) + yield return descendant; + } + + private static DataRequestStore Store(DataExportTestKit.GroupScope scope) => + new(scope.Db, scope.Unit, new ProducerExecution(scope.Unit), scope.Context); + + /// The real creation core over the scope's group, with no job runtime: a refused filing submits nothing. + private static DataRequestService Service(DataExportTestKit.GroupScope scope) + { + var store = Store(scope); + var phases = new DataRequestJobPhaseReader(scope.Unit, scope.Context); + var locks = new LearnStack.Infrastructure.Persistence.IdentityMutationLocks(scope.Unit); + var clock = new LearnStack.SharedKernel.Time.SystemClock(); + return new DataRequestService(store, new DataRequestReader(scope.Db, scope.Unit, scope.Context), phases, + new DataRequestFailureReconciler(store, phases, locks, scope.Context, clock), + new DataRequestEligibility(store, new NoHoldSource(), scope.Context), new NoSubmissions(), new NoArtifacts(), locks, + scope.Context, new DataExportTestKit.NoAuditSubject(), new LearnStack.SharedKernel.Identifiers.SystemGuidFactory(), clock); + } + + private sealed class NoSubmissions : IDataRequestFulfillmentScheduler + { + public ValueTask SubmitAsync(DataRequestFulfillment fulfillment, CancellationToken cancellationToken) => + throw new InvalidOperationException("A refused filing submits nothing."); + + public ValueTask SchedulePurgeAsync(Guid artifactId, DateTimeOffset dueAt, CancellationToken cancellationToken) => + throw new InvalidOperationException("A refused filing schedules nothing."); + } + + private sealed class NoArtifacts : IDataExportArtifactStore + { + public Task PutAsync(DataExportArtifactPut put, IAsyncEnumerable> plaintextChunks, + CancellationToken cancellationToken) => throw new NotSupportedException(); + + public Task ReadMetadataAsync(DataExportArtifactLocator artifact, CancellationToken cancellationToken) => + throw new NotSupportedException(); + + public bool CanOpen(string keyVersion) => false; + + public Task ReadChunkAsync(DataExportArtifactLocator artifact, int index, CancellationToken cancellationToken) => + throw new NotSupportedException(); + + public Task PurgeAsync(DataExportArtifactLocator artifact, DataExportArtifactStatus outcome, + CancellationToken cancellationToken) => throw new NotSupportedException(); + } +} 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 000000000..27fd1603a --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestStorageControlTests.cs @@ -0,0 +1,546 @@ +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 WaitUntilBlockedAsync(database, second.ProcessID, 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 WaitUntilBlockedAsync(database, second.ProcessID, 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"); + } + } + + /// + /// ADR-0107 § 8 and ADR-0108 § 8: the guard's platform arm, on erasures the application role created and moved through + /// its own arrows. learnstack_platform takes exactly awaiting_privileged_step → completed, with the version + /// step, the audit log's retained kinds as the only change to the result, and the completion stamped by the guard; the + /// application role cannot take that arrow, and the platform role cannot take one of the application's. + /// + [Fact] + public async Task The_platform_arm_admits_exactly_an_erasure_s_completion_and_each_role_keeps_to_its_own_arrows() + { + await using var database = await SeededAsync(); + var awaiting = Guid.CreateVersion7(); + var scheduled = Guid.CreateVersion7(); + const string FanOutInsert = """ + 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,'erasure','closure_fanout',@subject,NULL,'fulfilling',@snapshot::jsonb,NULL,now(),@system) + """; + 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, scheduled, SchemaFixture.TenantB, null, AdminB, [AdminMembershipB], "erasure"); + await transaction.CommitAsync(); + } + + // A request is born fulfilling only as the fan-out of a subject who is Closing (ADR-0107 § 7), and person B is Active: + // such a row would stand in for the erasure the profile clearing of a Revoked Membership requires. The arm reads the + // subject's status under the User fence and refuses the row for that alone. + await using (var app = await OpenAppAsync(database)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, SchemaFixture.TenantB, SchemaFixture.OrgB1, PersonB); + var born = () => ExecuteAsync(app, transaction, FanOutInsert, ("id", awaiting), ("tenant", SchemaFixture.TenantB), + ("organization", SchemaFixture.OrgB1), ("subject", PersonB), ("snapshot", Snapshot(BranchMembershipB)), ("system", SystemActor)); + (await born.Should().ThrowAsync()).Which.MessageText.Should().Be("Data request subject is not admitted."); + } + + // The fixture row is written by the owner with the guard paused: a fan-out of a subject who is not Closing, which the + // closure's arrows refuse to complete (AccountClosureStorageTests proves the fan-out a Closing subject admits). + 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.TenantB, SchemaFixture.OrgB1); + await ExecuteAsync(owner, transaction, FanOutInsert, ("id", awaiting), ("tenant", SchemaFixture.TenantB), + ("organization", SchemaFixture.OrgB1), ("subject", PersonB), ("snapshot", Snapshot(BranchMembershipB)), ("system", SystemActor)); + await ExecuteAsync(owner, transaction, "ALTER TABLE public.data_subject_requests ENABLE TRIGGER tg_data_subject_requests_mutation_guard"); + await transaction.CommitAsync(); + } + + await using (var app = await OpenAppAsync(database)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, SchemaFixture.TenantB, SchemaFixture.OrgB1, null); + await StepAsync(app, transaction, awaiting, "result='{\"consent_evidence\":2,\"audit_actor_reference\":9}'"); + await StepAsync(app, transaction, awaiting, "status='awaiting_privileged_step'"); + await transaction.CommitAsync(); + } + + await using (var app = await OpenAppAsync(database)) + { + foreach (var (set, reason) in new[] + { + ("status='completed',completed_at=now()", "Data request transition refused."), + ("result='{\"consent_evidence\":2,\"audit_actor_reference\":4}'", "Data request result refused."), + }) + { + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, SchemaFixture.TenantB, SchemaFixture.OrgB1, null); + var act = () => StepAsync(app, transaction, awaiting, set); + (await act.Should().ThrowAsync()).Which.MessageText.Should().Be(reason, + "the application's arms are unchanged and never take the operator's step: " + set); + } + } + + await using var platform = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.PlatformConnectionString); + async Task RefusedAsync(string sql, params (string Name, object? Value)[] values) + { + await using var transaction = await platform.BeginTransactionAsync(); + var act = () => ExecuteAsync(platform, transaction, sql, values); + return (await act.Should().ThrowAsync(sql)).Which; + } + + const string Complete = "UPDATE public.data_subject_requests SET {0} WHERE id=@id"; + foreach (var (target, set, reason) in new[] + { + (awaiting, "status='completed'", "Data request immutable state refused."), + (awaiting, "status='completed',row_version=row_version+2", "Data request immutable state refused."), + (awaiting, "status='completed',row_version=row_version+1,result='{\"consent_evidence\":3,\"audit_actor_reference\":4}'", + "Data request result refused."), + (awaiting, "status='completed',row_version=row_version+1,result='{\"audit_actor_reference\":4}'", "Data request result refused."), + (awaiting, "status='completed',row_version=row_version+1,result='{\"consent_evidence\":2,\"request_receipt\":1}'", + "Data request result refused."), + (awaiting, "status='completed',row_version=row_version+1", + "Data request closure subject refused."), // a closure's fan-out erasure is completed by its closure's Finalize alone + (awaiting, "status='cancelled',row_version=row_version+1", "Data request transition refused."), + (awaiting, "status='failed',row_version=row_version+1", "Data request transition refused."), + (awaiting, "status='blocked',row_version=row_version+1", "Data request transition refused."), + (awaiting, "status='scheduled',row_version=row_version+1", "Data request transition refused."), + (awaiting, "status='fulfilling',row_version=row_version+1", "Data request transition refused."), + (scheduled, "status='fulfilling',row_version=row_version+1", "Data request transition refused."), + (scheduled, "status='cancelled',row_version=row_version+1", "Data request transition refused."), + (scheduled, "status='completed',row_version=row_version+1", "Data request transition refused."), + }) + { + var refusal = await RefusedAsync(string.Format(System.Globalization.CultureInfo.InvariantCulture, Complete, set), ("id", target)); + refusal.SqlState.Should().Be("23514", set); + refusal.MessageText.Should().Be(reason, set); + } + + (await RefusedAsync("UPDATE public.data_subject_requests SET updated_by=NULL WHERE id=@id", ("id", awaiting))) + .SqlState.Should().Be("42501", "a column outside the grant never reaches the guard"); + (await RefusedAsync("UPDATE public.data_subject_requests SET last_refusal='blocked_hold',row_version=row_version+1 WHERE id=@id", + ("id", awaiting))).MessageText.Should().Be("Data request refusal record refused.", + "the grant reaches the guard, which admits a refusal record on a scheduled closure alone"); + (await RefusedAsync("DELETE FROM public.data_subject_requests WHERE id=@id", ("id", awaiting))).SqlState.Should().Be("42501"); + + // The erasure a person or an administrator filed, past its window (the owner backdates it with the one guard paused, + // as the window and expiry test does) and walked to the privileged step by the application's own arrows. + 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.TenantB, null); + 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", scheduled)); + await ExecuteAsync(owner, transaction, "ALTER TABLE public.data_subject_requests ENABLE TRIGGER tg_data_subject_requests_mutation_guard"); + await transaction.CommitAsync(); + } + + await using (var app = await OpenAppAsync(database)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await FenceAsync(app, transaction, SchemaFixture.TenantB, null, null); + await StepAsync(app, transaction, scheduled, "status='fulfilling'"); + await StepAsync(app, transaction, scheduled, "result='{\"consent_evidence\":2,\"audit_actor_reference\":9}'"); + await StepAsync(app, transaction, scheduled, "status='awaiting_privileged_step'"); + await transaction.CommitAsync(); + } + + // The one arrow. The statement's own completion time is replaced by the database clock the guard stamps. + await using (var transaction = await platform.BeginTransactionAsync()) + { + var completedAt = await ScalarAsync(platform, transaction, """ + UPDATE public.data_subject_requests SET status='completed',completed_at='2001-01-01T00:00:00Z',row_version=row_version+1, + result='{"consent_evidence":2,"audit_actor_reference":4,"unscoped_audit_rows":1}' + WHERE id=@id RETURNING completed_at + """, ("id", scheduled)); + completedAt.Should().BeCloseTo(DateTime.UtcNow, TimeSpan.FromMinutes(1), "no caller supplies the completion time"); + await transaction.CommitAsync(); + } + + await using (var app = await OpenAppAsync(database)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, transaction, SchemaFixture.TenantB, null); + (await ScalarAsync(app, transaction, """ + SELECT status || ':' || row_version || ':' || (completed_at = updated_at)::text || ':' || updated_by::text || ':' + || (result = '{"consent_evidence":2,"audit_actor_reference":4,"unscoped_audit_rows":1}'::jsonb)::text + FROM public.data_subject_requests WHERE id=@id + """, ("id", scheduled))).Should().Be($"completed:4:true:{SystemActor}:true", + "the arm stamps the completion and the system actor, steps the version once and keeps the tenant side's kinds"); + } + + (await RefusedAsync("UPDATE public.data_subject_requests SET status='completed',row_version=row_version+1 WHERE id=@id", + ("id", scheduled))).MessageText.Should().Be("Data request transition refused.", "a completed erasure is terminal"); + } + + /// + /// ADR-0107 § 4: a chunk written while a revocation of its artifact is in flight waits for it and then meets the + /// committed status, so ciphertext never lands on a withdrawn artifact (which nothing would clean afterwards). + /// + [Fact] + public async Task A_chunk_insert_racing_a_revocation_waits_for_it_and_is_refused() + { + await using var database = await SeededAsync(); + await using var revoker = await OpenAppAsync(database); + await using var writer = await OpenAppAsync(database); + var artifact = TenantWideA.Artifact!.Value; + await using (var revocation = await revoker.BeginTransactionAsync()) + { + await FenceAsync(revoker, revocation, SchemaFixture.TenantA, null, null); + // The store's revocation: lock the artifact, record it revoked, then delete its chunks; not yet committed. + await ExecuteAsync(revoker, revocation, "SELECT id FROM public.data_export_artifacts WHERE id=@id FOR UPDATE", ("id", artifact)); + await ExecuteAsync(revoker, revocation, """ + 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", PersonA)); + await ExecuteAsync(revoker, revocation, "DELETE FROM public.data_export_chunks WHERE artifact_id=@id", ("id", artifact)); + + await using var insert = await writer.BeginTransactionAsync(); + await ScopeAsync(writer, insert, SchemaFixture.TenantA); + var contender = InsertChunkAsync(writer, insert, SchemaFixture.TenantA, null, artifact, 0); + await WaitUntilBlockedAsync(database, writer.ProcessID, contender, "the chunk guard reads its artifact behind the revocation's row lock"); + await revocation.CommitAsync(); + + var refusal = (await FluentActions.Awaiting(() => contender).Should().ThrowAsync()).Which; + refusal.SqlState.Should().Be("23514"); + refusal.MessageText.Should().Be("Data export chunk refused.", "the guard re-read the committed revoked status"); + } + + 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 a.status || ':' || (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", artifact))).Should().Be("revoked:0", "a withdrawn artifact keeps no ciphertext"); + } + + /// + /// Waits until the backend waits on a lock, from pg_locks (readable by every role, unlike + /// another role's pg_stat_activity wait columns), instead of sleeping and hoping. + /// + private static async Task WaitUntilBlockedAsync(DisposableSchemaDatabase database, int pid, Task contender, string because) + { + await using var observer = await PostgresFixture.OpenAsync(database.MigrationConnectionString); + var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(30); + while (true) + { + contender.IsCompleted.Should().BeFalse(because); + if (await ScalarAsync((NpgsqlConnection)observer, null, + "SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_locks WHERE pid = @pid AND NOT granted)", ("pid", pid))) + return; + DateTime.UtcNow.Should().BeBefore(deadline, because); + await Task.Delay(TimeSpan.FromMilliseconds(20)); + } + } + + /// + /// The request guard's INSERT arm admits exactly one initial status per kind and origin and refuses every other, for + /// every kind and origin the CHECK constraints admit: requested for an export, scheduled for an erasure or + /// a closure of a person, and nothing for a closure's fan-out erasure of person A: its one initial status, + /// fulfilling, is admitted only for a Closing subject and person A is Active, so the guard refuses it as a + /// subject not admitted (the fan-out of a Closing subject is proven in ). Each + /// combination first inserts its own initial row (so the arrangement is valid and only the status differs), then each + /// other status as the application role with the fences held; the refusal is the guard's, which fires before any + /// constraint. + /// + [Fact] + public async Task The_request_guard_refuses_every_status_but_the_initial_one_for_every_kind_and_origin_the_constraints_admit() + { + await using var database = await SeededAsync(); + string[] statuses = ["requested", "scheduled", "fulfilling", "awaiting_privileged_step", "completed", "blocked", "failed", "cancelled"]; + // (kind, origin, requester, window, the one initial status or none) + (string Kind, string Origin, Guid? Requester, bool Window, string? Initial)[] combinations = + [ + ("export", "self", PersonA, false, "requested"), + ("export", "administrator", AdminA, false, "requested"), + ("erasure", "self", PersonA, true, "scheduled"), + ("erasure", "administrator", AdminA, true, "scheduled"), + ("erasure", "closure_fanout", null, false, null), + ("closure", "self", PersonA, true, "scheduled"), + ]; + const string Insert = """ + 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,NULL,@kind,@origin,@subject,@requester::uuid,@status,@snapshot::jsonb, + CASE WHEN @window THEN now() + interval '24 hours' ELSE NULL END,now(),COALESCE(@requester::uuid, @system::uuid)) + """; + await using var app = await OpenAppAsync(database); + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, SchemaFixture.TenantA, null, PersonA); + Task Insertion(string kind, string origin, Guid? requester, bool window, string status) => ExecuteAsync(app, transaction, Insert, + ("id", Guid.CreateVersion7()), ("tenant", SchemaFixture.TenantA), ("kind", kind), ("origin", origin), ("subject", PersonA), + ("requester", requester), ("status", status), ("snapshot", Snapshot(LearnerMembershipA)), ("window", window), + ("system", SystemActor)); + + foreach (var (kind, origin, requester, window, initial) in combinations) + { + var label = kind + "/" + origin; + if (initial is not null) + { + await transaction.SaveAsync("control"); + await Insertion(kind, origin, requester, window, initial); + await transaction.RollbackAsync("control"); + } + + foreach (var status in statuses.Where(status => status != initial)) + { + var refusal = await DataExportTestKit.RefuseAsync(transaction, () => Insertion(kind, origin, requester, window, status)); + var reason = origin == "closure_fanout" && status == "fulfilling" + ? "Data request subject is not admitted." : "Data request initial state refused."; + (refusal.SqlState, refusal.MessageText).Should().Be((PostgresErrorCodes.CheckViolation, reason), + $"{label} is never born {status} for an Active subject: the guard's refusal, not a constraint's"); + } + } + } + + private async Task SeededAsync() + { + var database = await DisposableSchemaDatabase.CreateAsync(schema.Postgres); + await SeedSchemaAsync(database.MigrationConnectionString, database.AppConnectionString); + return database; + } + + private static Task OpenAppAsync(DisposableSchemaDatabase database) => + DataExportTestKit.OpenAppAsync(database.AppConnectionString); +} 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 000000000..dc9dca58f --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/DataRequestStorageTests.cs @@ -0,0 +1,783 @@ +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.DataExportTestKit; +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"]; + // ADR-0107 § 7: the closure's Finalize reads the update stamp, a begun closure's Begin moment; it names no actor. + 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", "updated_at"]; + // ADR-0107 § 8: the closure's refusal record joined the four columns the erasure completion writes. + private static readonly string[] PlatformRequestUpdate = ["status", "row_version", "completed_at", "result", "last_refusal"]; + private static readonly string[] PlatformArtifactSelect = ["id", "tenant_id", "request_id", "status", "expires_at"]; + 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); + // The request completes on the same transaction, so the forced check below judges the chunks alone. + await StepAsync(app, transaction, await RequestOfAsync(app, transaction, artifact), "status='completed',completed_at=now()"); + 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 RefuseAsync(transaction, () => ExecuteAsync(app, transaction, + "DELETE FROM public.data_export_chunks WHERE artifact_id=@id AND chunk_index=1", ("id", artifact)))) + .MessageText.Should().Be("Data export chunk deletion refused.", "an available artifact's ciphertext is never replaced or removed"); + 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 RequestOfAsync(app, transaction, first); + await InsertChunkAsync(app, transaction, SchemaFixture.TenantA, null, first, 0); + 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 is still fulfilling); 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 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 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)"); + 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 StepAsync(app, transaction, second, "status='completed',completed_at=now()"); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + } + + /// + /// The artifact bracket (ADR-0107 § 4): an artifact is inserted only while its export is fulfilling and commits only + /// with that export completed. The guard compares no transaction identity, so it holds under the savepoints EF Core + /// opens and past the first xid epoch, where a cast of the full transaction id to xid fails. + /// + [Theory] + [InlineData("left_fulfilling", "data_export_artifact_request")] + [InlineData("failed", "data_export_artifact_request")] + [InlineData("completed", null)] + public async Task An_artifact_commits_only_with_its_export_completed_on_the_same_transaction(string outcome, string? refusal) + { + 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); + var request = await RequestOfAsync(app, transaction, artifact); + if (outcome == "failed") + await StepAsync(app, transaction, request, "status='failed',failure_reason='execution_failed'"); + else if (outcome == "completed") + { + // Completed at the top level of this transaction, before any savepoint: the request row's xmin is this + // transaction's own id, which is exactly what the withdrawn "completed and fresh" arm admitted. + await StepAsync(app, transaction, request, "status='completed',completed_at=now()"); + (await RefuseAsync(transaction, () => InsertArtifactAsync(app, transaction, Guid.CreateVersion7(), SchemaFixture.TenantA, null, + request, AdminA, 10))).MessageText.Should().Be("Data export artifact request refused.", + "an artifact is stored while its export is fulfilling, never once this transaction has completed it"); + } + + if (refusal is null) + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + else + { + var refused = await RefuseAsync(transaction, () => ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE")); + refused.ConstraintName.Should().Be(refusal, "an artifact never commits beside an export that did not complete"); + refused.MessageText.Should().Be("Data export artifact request is not completed."); + } + + (await ScalarAsync(app, transaction, + "SELECT position('xmin' in pg_get_functiondef('public.fn_identity_data_export_artifact_guard()'::regprocedure)) = 0")) + .Should().BeTrue("the guard no longer reads a transaction identity, so no xid cast can fail after epoch 1"); + } + + /// + /// The reverse half of the bracket: an export that reaches completed commits only with its artifact, so a + /// receipt never shows a completed export with nothing behind it. A failed export has no artifact and commits. + /// + [Fact] + public async Task An_export_commits_completed_only_with_its_artifact() + { + await using var app = await OpenAppAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await FenceAsync(app, transaction, SchemaFixture.TenantA, null, PersonA); + var failed = Guid.CreateVersion7(); + await InsertRequestAsync(app, transaction, failed, SchemaFixture.TenantA, null, PersonA, [LearnerMembershipA]); + await StepAsync(app, transaction, failed, "status='fulfilling'"); + await StepAsync(app, transaction, failed, "status='failed',failure_reason='export_too_large'"); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL DEFERRED"); + + await LockAsync(app, transaction, SchemaFixture.TenantA, AdminA, false); + var completed = Guid.CreateVersion7(); + await InsertRequestAsync(app, transaction, completed, SchemaFixture.TenantA, null, AdminA, [AdminMembershipA]); + await StepAsync(app, transaction, completed, "status='fulfilling'"); + await StepAsync(app, transaction, completed, "status='completed',completed_at=now()"); + var refused = await RefuseAsync(transaction, () => ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE")); + refused.ConstraintName.Should().Be("data_export_request_artifact", "a completed export without its artifact never commits"); + refused.MessageText.Should().Be("Data export request completed without its artifact."); + (await ScalarAsync(app, transaction, """ + SELECT tgdeferrable AND tginitdeferred FROM pg_trigger + WHERE tgrelid = 'public.data_subject_requests'::regclass AND tgname = 'tg_data_subject_requests_export_artifact' + """)).Should().BeTrue("the check runs at commit, after the job has stored the artifact on the same transaction"); + } + + [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")) + .Concat(PlatformArtifactSelect.Select(column => $"data_export_artifacts.{column}:learnstack_platform:SELECT")); + 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 and the five artifact columns its inspection reads"); + PlatformRequestSelect.Should().NotContain(UnreadActors, + "the operator read names no actor beyond the subject"); + PlatformArtifactSelect.Should().NotContain(["subject_user_id", "byte_count", "chunk_count", "key_version", "truncation"], + "the inspection of an unpurged artifact names no subject, size, key or truncation"); + } + + [Fact] + public async Task The_platform_role_reads_only_its_closed_columns_and_writes_nothing_its_guard_has_not_admitted() + { + // The seeded rows are exports, which the platform arm never completes; the one arrow it admits, an erasure's + // privileged step, is proven on committed erasures in DataRequestStorageControlTests. + 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"); + (await ScalarAsync(platform, null, "SELECT count(*) FROM (SELECT id,tenant_id,request_id,status,expires_at FROM public.data_export_artifacts) rows")) + .Should().Be(Rows.Count(row => row.Artifact is not null), "the inspection's five artifact columns are readable"); + foreach (var statement in new[] + { + "SELECT requester_user_id FROM public.data_subject_requests", + "SELECT updated_by 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 progress='{}'::jsonb", + "UPDATE public.data_subject_requests SET updated_at=now()", + "DELETE FROM public.data_subject_requests", + "SELECT subject_user_id FROM public.data_export_artifacts", + "SELECT organization_id FROM public.data_export_artifacts", + "SELECT key_version FROM public.data_export_artifacts", + "SELECT purged_at FROM public.data_export_artifacts", + "SELECT * FROM public.data_export_artifacts", + "UPDATE public.data_export_artifacts SET status='revoked'", + "DELETE FROM public.data_export_artifacts", + "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", + // The closure's closed-column reads of these two tables are proven in AccountClosureStorageTests. + "SELECT * FROM public.memberships", + "SELECT * FROM public.users", + }) + { + await using var transaction = await platform.BeginTransactionAsync(); + var act = () => ExecuteAsync(platform, transaction, statement); + (await act.Should().ThrowAsync()).Which.SqlState.Should().Be("42501", statement); + } + + foreach (var (request, set) in new[] + { + (BranchB.Request, "status='completed',completed_at=now(),row_version=row_version+1"), + (TenantWideA.Request, "status='completed',row_version=row_version+1"), + (BranchB.Request, "status='cancelled',row_version=row_version+1"), + (BranchB.Request, "status='fulfilling',row_version=row_version+1"), + }) + { + await using var transaction = await platform.BeginTransactionAsync(); + var act = () => ExecuteAsync(platform, transaction, $"UPDATE public.data_subject_requests SET {set} WHERE id=@id", ("id", request)); + var refusal = (await act.Should().ThrowAsync()).Which; + refusal.SqlState.Should().Be("23514", set); + refusal.MessageText.Should().Be("Data request transition refused.", + "the grant reaches the platform arm, which admits an erasure's completion and neither an export's nor an application arrow: " + set); + } + } + + [Fact] + public async Task The_platform_role_can_select_exactly_the_five_artifact_columns_its_inspection_reads() + { + await using var platform = (NpgsqlConnection)await PostgresFixture.OpenAsync(schema.Postgres.PlatformConnectionString); + var granted = await SchemaQueries.ReadStringsAsync(platform, """ + SELECT attname FROM pg_attribute + WHERE attrelid = 'public.data_export_artifacts'::regclass AND attnum > 0 AND NOT attisdropped + AND has_column_privilege('learnstack_platform', 'public.data_export_artifacts', attnum, 'SELECT') + ORDER BY attname + """); + + granted.Should().Equal(PlatformArtifactSelect.Order(StringComparer.Ordinal), "no subject, size, key version or purge time"); + foreach (var table in new[] { "data_export_tickets", "data_export_chunks" }) + { + (await SchemaQueries.ReadStringsAsync(platform, $""" + SELECT attname FROM pg_attribute + WHERE attrelid = 'public.{table}'::regclass AND attnum > 0 AND NOT attisdropped + AND has_column_privilege('learnstack_platform', 'public.{table}', attnum, 'SELECT,UPDATE,INSERT') + """)).Should().BeEmpty(table + " stays closed to the platform role"); + } + } + + [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 RequestOfAsync(NpgsqlConnection app, NpgsqlTransaction transaction, Guid artifact) => + ScalarAsync(app, transaction, "SELECT request_id FROM public.data_export_artifacts WHERE id=@id", ("id", 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)); + + 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 Task OpenAppAsync() => DataExportTestKit.OpenAppAsync(schema.Postgres.AppConnectionString); +} 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 000000000..39dc71ba9 --- /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 348cc842c..46946710e 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.IdentityGuard.cs b/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.IdentityGuard.cs index 736b69f53..21e1b387b 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.IdentityGuard.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.IdentityGuard.cs @@ -5,13 +5,15 @@ public sealed partial class EducationStructureTests // Independent whole-body expectation for the combined contextual guard. A // fragment match would miss an early return or a branch that bypasses the // parent lookup. This fixture is not obtained from the production installer. + // ADR-0107 § 5's erasure exception is part of the body: a clearing profile + // UPDATE of a Revoked parent under the User fence and a fulfilling erasure. private static bool IsIdentityParentGuardBody(string body) => NormalizeFunction(body) == NormalizeFunction(IdentityParentGuardBody); private const string IdentityParentGuardBody = """ DECLARE target_tenant uuid; target_member uuid; target_role uuid; parent_org uuid; parent_status text; role_scope text; role_key text; require_exclusive boolean := false; - has_history boolean; parent_fresh boolean; + has_history boolean; parent_fresh boolean; parent_user uuid; erasure_clearing boolean := false; BEGIN target_tenant := CASE WHEN TG_OP = 'DELETE' THEN OLD.tenant_id ELSE NEW.tenant_id END; IF TG_OP = 'UPDATE' AND NEW.tenant_id IS DISTINCT FROM OLD.tenant_id THEN @@ -38,14 +40,24 @@ ELSIF TG_TABLE_NAME IN ('membership_profiles','membership_role_assignments') THE IF TG_OP = 'UPDATE' AND NEW.membership_id IS DISTINCT FROM OLD.membership_id THEN RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; END IF; - SELECT member.organization_id, member.status INTO parent_org, parent_status + SELECT member.organization_id, member.status, member.user_id INTO parent_org, parent_status, parent_user FROM public.memberships AS member WHERE member.tenant_id = target_tenant AND member.id = target_member FOR NO KEY UPDATE; IF NOT FOUND OR parent_org IS DISTINCT FROM (CASE WHEN TG_OP = 'DELETE' THEN OLD.organization_id ELSE NEW.organization_id END) THEN RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = '23514', CONSTRAINT = 'membership_parent_scope'; END IF; - IF TG_OP <> 'DELETE' AND parent_status = 'Revoked' THEN + IF TG_TABLE_NAME = 'membership_profiles' AND TG_OP = 'UPDATE' AND parent_status = 'Revoked' THEN + erasure_clearing := NEW.display_name IS NULL AND NEW.preferred_locale IS NULL AND NEW.custom_fields = '[]'::jsonb + AND public.fn_identity_lock_held('user',parent_user,true) IS TRUE + AND EXISTS (SELECT 1 FROM public.data_subject_requests AS erasure + WHERE erasure.tenant_id = target_tenant AND erasure.subject_user_id = parent_user + AND erasure.organization_id IS NOT DISTINCT FROM parent_org + AND erasure.kind = 'erasure' AND erasure.status = 'fulfilling' + AND erasure.membership_snapshot @> jsonb_build_array(target_member::text)); + END IF; + IF TG_OP <> 'DELETE' AND parent_status = 'Revoked' AND erasure_clearing IS NOT TRUE THEN RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; END IF; + require_exclusive := erasure_clearing IS TRUE; IF TG_TABLE_NAME = 'membership_profiles' AND TG_OP = 'DELETE' THEN RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; ELSIF TG_TABLE_NAME = 'membership_role_assignments' THEN diff --git a/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.IdentityRelations.cs b/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.IdentityRelations.cs index 4092cc5c5..ee788e975 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.IdentityRelations.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.IdentityRelations.cs @@ -108,6 +108,12 @@ await SchemaQueries.ExecuteAsync(owner, transaction, [InlineData("missing-constraint")] [InlineData("wrong-branch")] [InlineData("early-return")] + [InlineData("erasure-without-user-fence")] + [InlineData("erasure-without-fulfilling-request")] + [InlineData("erasure-shared-tenant-fence")] + [InlineData("erasure-other-group")] + [InlineData("erasure-other-subject")] + [InlineData("erasure-outside-snapshot")] public async Task The_Identity_Parent_Guard_Rejects_A_Weakened_Applied_Function(string defect) { await using var owner = await PostgresFixture.OpenAsync(_schema.Postgres.MigrationConnectionString); @@ -134,6 +140,16 @@ public async Task The_Identity_Parent_Guard_Rejects_A_Weakened_Applied_Function( "wrong-branch" => body.Replace("ELSIF TG_TABLE_NAME IN ('membership_profiles','membership_role_assignments')", "ELSIF TG_TABLE_NAME IN ('membership_profiles')", StringComparison.Ordinal), "early-return" => body.Replace("BEGIN", "BEGIN RETURN NEW;", StringComparison.Ordinal), + // ADR-0107 § 5: each condition of the erasure witness is part of the pinned body. + "erasure-without-user-fence" => body.Replace("AND public.fn_identity_lock_held('user',parent_user,true) IS TRUE", + "", StringComparison.Ordinal), + "erasure-without-fulfilling-request" => body.Replace("AND erasure.status = 'fulfilling'", "", StringComparison.Ordinal), + "erasure-shared-tenant-fence" => body.Replace("require_exclusive := erasure_clearing IS TRUE;", "", StringComparison.Ordinal), + // The witness is the person's, the group's and the frozen snapshot's: each is also pinned alone. + "erasure-other-group" => body.Replace("AND erasure.organization_id IS NOT DISTINCT FROM parent_org", "", StringComparison.Ordinal), + "erasure-other-subject" => body.Replace("AND erasure.subject_user_id = parent_user", "", StringComparison.Ordinal), + "erasure-outside-snapshot" => body.Replace("AND erasure.membership_snapshot @> jsonb_build_array(target_member::text)", "", + StringComparison.Ordinal), _ => body, }; if (defect is not ("security-definer" or "search-path" or "stable")) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.InvitationUpgrade.cs b/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.InvitationUpgrade.cs index 67bf43d68..0becd9fb6 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/FederationBrokerOperationsTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/FederationBrokerOperationsTests.cs index 0c72c09e1..aa891a4d2 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/FederationBrokerOperationsTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/FederationBrokerOperationsTests.cs @@ -892,6 +892,9 @@ public Task> QueryAsync( public Task WriteIntentAsync(PlatformResult intent, CancellationToken cancellationToken = default) => inner.WriteIntentAsync(intent, cancellationToken); + public Task RedactAuditAsync(AuditRedactionPlan plan, CancellationToken cancellationToken = default) => + inner.RedactAuditAsync(plan, cancellationToken); + public Task WriteResultAsync(PlatformResult result, CancellationToken cancellationToken = default) => inner.WriteResultAsync(result, cancellationToken); @@ -931,6 +934,9 @@ public Task> QueryAsync( public Task WriteIntentAsync(PlatformResult intent, CancellationToken cancellationToken = default) => real.WriteIntentAsync(intent, cancellationToken); + public Task RedactAuditAsync(AuditRedactionPlan plan, CancellationToken cancellationToken = default) => + real.RedactAuditAsync(plan, cancellationToken); + public async Task WriteResultAsync(PlatformResult result, CancellationToken cancellationToken = default) { if (faults.HangResult) await Task.Delay(Timeout.Infinite, cancellationToken); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs index c32ca8b0b..dc90aa288 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs @@ -320,10 +320,15 @@ FROM aclexplode(COALESCE(p.proacl,acldefault('f',p.proowner))) a if (reader.GetString(9) != function.IdentityArguments || reader.GetInt16(10) != 0) issues.Add(function.Name + ":arguments"); if (reader.GetBoolean(11) != function.AppCallable) issues.Add(function.Name + ":app-execute"); if (reader.GetBoolean(12)) issues.Add(function.Name + ":public-execute"); - var permittedGrantees = function.AppCallable ? new[] { "learnstack_app" } + // The two lock observers read only the calling backend's own pg_locks rows; the closure's users trigger + // exception and request-guard arrows call them as learnstack_platform (ADR-0107 § 8). + var permittedGrantees = function.Name is "fn_identity_lock_held" or "fn_identity_contextual_lock_key" + ? new[] { "learnstack_app", "learnstack_platform" } + : function.AppCallable ? new[] { "learnstack_app" } : function.Name is "fn_identity_provider_event_accept" or "fn_identity_provider_event_claim" or "fn_identity_provider_event_retire" ? new[] { "learnstack_identity_ingress" } : []; - if (!reader.GetFieldValue(13).SequenceEqual(permittedGrantees)) issues.Add(function.Name + ":execution-grantees"); + if (!reader.GetFieldValue(13).Order(StringComparer.Ordinal).SequenceEqual(permittedGrantees)) + issues.Add(function.Name + ":execution-grantees"); if (reader.GetBoolean(14) != function.Strict || reader.GetString(15) != "u" || reader.GetBoolean(16)) issues.Add(function.Name + ":execution-properties"); } @@ -407,12 +412,22 @@ 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.Count(function => function.Definer).Should().Be(16); + functions.Should().HaveCount(42, "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 and completed-export completeness checks, three canonical parent-scope checks, the retained own data-request scope definer, " + + "the request guard's User status witness and the delayed provider mirror's subject status"); + functions.Count(function => function.Definer).Should().Be(19); + functions.Single(function => function.Name == "fn_identity_provider_event_subject_status").Signature + .Should().Be("public.fn_identity_provider_event_subject_status(uuid)"); + functions.Single(function => function.Name == "fn_identity_user_status").Signature + .Should().Be("public.fn_identity_user_status(uuid)"); + 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)); - functions.SelectMany(function => function.Triggers).Should().HaveCount(30); + functions.SelectMany(function => function.Triggers).Should().HaveCount(40, + "the data-request functions add four mutation guards, three deferred completeness triggers (the chunk pair and the " + + "completed export's artifact) and three parent-scope triggers; the closure adds no trigger"); 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"); @@ -422,6 +437,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 91331e7bc..d5cd189bb 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 8791bc8b1..488ce1f89 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.cs @@ -55,20 +55,24 @@ 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_nineteen_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 """, null); + // The eighteenth is the request guard's User status witness (ADR-0107 § 7); the nineteenth is the delayed provider + // mirror's subject status (ADR-0107 § 9). They are the two reads of another person's status. 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_provider_event_subject_status", "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"); + "fn_identity_user_status", "fn_invitation_smtp_claim_or_read", "fn_invitation_smtp_complete_attempt", + "fn_tenancy_own_field_consent_scope"); (await ScalarAsync(owner, null, """ SELECT count(*) FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace JOIN pg_roles r ON r.oid=p.proowner @@ -76,7 +80,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(19); (await ScalarAsync(owner, null, """ SELECT count(*) FROM pg_class WHERE oid IN ('public.users'::regclass,'public.identity_authority'::regclass) AND relrowsecurity AND relforcerowsecurity @@ -163,7 +167,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/IdentityAuthorizationReaderTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorizationReaderTests.cs index ac8f3ccd1..8cf9307d9 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorizationReaderTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityAuthorizationReaderTests.cs @@ -675,6 +675,9 @@ private sealed class LifecycleProbe(IIdentityScopeLifecycleReader inner, { public Task ReadAsync(TenantId tenantId, OrganizationId? organizationId, CancellationToken cancellationToken = default) => inner.ReadAsync(tenantId, organizationId, cancellationToken); + public Task> ReadOnPlatformScopeAsync( + LearnStack.SharedKernel.Tenancy.IPlatformAdminScopeHandle handle, IReadOnlyList scopes, + CancellationToken cancellationToken = default) => inner.ReadOnPlatformScopeAsync(handle, scopes, cancellationToken); public async Task ReadAuthorizationAsync(IUnitOfWork child, AuthorizationCandidate candidate, CancellationToken cancellationToken = default) { diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipFixture.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipFixture.cs index 0cde89fc2..60fcd03da 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 6169b205f..224e68d99 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/IdentityScopeLifecyclePlatformTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityScopeLifecyclePlatformTests.cs new file mode 100644 index 000000000..1f8be1e50 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityScopeLifecyclePlatformTests.cs @@ -0,0 +1,115 @@ +using FluentAssertions; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Tenancy.Application.Contracts.IdentityLifecycle; +using LearnStack.Modules.Tenancy.Infrastructure.Persistence; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.Extensions.Logging.Abstractions; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// Tenancy's lifecycle port read on an entered platform scope (ADR-0107 § 7): many groups in one statement, in their order, +/// with no announcement, the same four facts the announced read answers, and its refusals before any statement runs. +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed class IdentityScopeLifecyclePlatformTests(SchemaFixture schema) +{ + private static readonly TenantId TenantA = TenantId.From(SchemaFixture.TenantA); + private static readonly TenantId TenantB = TenantId.From(SchemaFixture.TenantB); + + [Fact] + public async Task The_platform_read_answers_every_group_in_order_with_the_announced_read_s_facts() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + await kit.OrganizationStatusAsync(SchemaFixture.TenantA, SchemaFixture.OrgA2, "Archived"); + await kit.TenantStatusAsync(SchemaFixture.TenantB, "Suspended"); + // The platform form reads on the handle it is given and never on the announced unit, so none is constructed. + var reader = new IdentityScopeLifecycleReader(null!); + IdentityLifecycleScope[] scopes = + [ + new(TenantA, null), + new(TenantA, OrganizationId.From(SchemaFixture.OrgA1)), + new(TenantA, OrganizationId.From(SchemaFixture.OrgA2)), + new(TenantA, OrganizationId.From(SchemaFixture.OrgB1)), + new(TenantA, OrganizationId.From(Guid.CreateVersion7())), + new(TenantB, null), + new(TenantB, OrganizationId.From(SchemaFixture.OrgB1)), + new(TenantId.From(Guid.CreateVersion7()), null), + new(TenantA, OrganizationId.From(SchemaFixture.OrgA1)), + ]; + + IReadOnlyList facts; + await using (var handle = await kit.Scope().EnterAsync(AccountClosureBeginKit.Admission())) + { + facts = await reader.ReadOnPlatformScopeAsync(handle, scopes); + } + + facts.Should().Equal( + new IdentityScopeLifecycle(true, true, false, false), + new IdentityScopeLifecycle(true, true, true, true), + new IdentityScopeLifecycle(true, true, true, false), + new IdentityScopeLifecycle(true, true, false, false), + new IdentityScopeLifecycle(true, true, false, false), + new IdentityScopeLifecycle(true, false, false, false), + new IdentityScopeLifecycle(true, false, true, true), + new IdentityScopeLifecycle(false, false, false, false), + new IdentityScopeLifecycle(true, true, true, true)); + + // The announced read of the same group, on the application role, answers the same. + await using var source = ApplicationDataSource.Build(kit.Database.AppConnectionString); + await using var unit = new NpgsqlUnitOfWork(source, NullLogger.Instance); + await using (var frame = await unit.BeginTransactionAsync()) + { + await unit.SetTenantContextAsync(new Context(TenantB, OrganizationId.From(SchemaFixture.OrgB1))); + (await new IdentityScopeLifecycleReader(unit).ReadAsync(TenantB, OrganizationId.From(SchemaFixture.OrgB1))) + .Should().Be(facts[6]); + } + + // A deleted tenant does not exist for the read, whatever its status. + await kit.SqlAsync($"SET session_replication_role = replica; UPDATE public.tenants SET deleted_at = now() WHERE id = '{SchemaFixture.TenantB}'"); + await using (var handle = await kit.Scope().EnterAsync(AccountClosureBeginKit.Admission())) + { + (await reader.ReadOnPlatformScopeAsync(handle, [new(TenantB, null)])).Should().Equal(new IdentityScopeLifecycle(false, false, false, false)); + } + } + + [Fact] + public async Task The_platform_read_refuses_an_empty_an_oversized_or_an_unreal_scope_list_before_any_statement() + { + await using var kit = await AccountClosureBeginKit.CreateAsync(schema.Postgres); + var reader = new IdentityScopeLifecycleReader(null!); + await using var handle = await kit.Scope().EnterAsync(AccountClosureBeginKit.Admission()); + + foreach (var refused in new IReadOnlyList[] + { + [], + [.. Enumerable.Repeat(new IdentityLifecycleScope(TenantA, null), IIdentityScopeLifecycleReader.MaximumPlatformScopes + 1)], + [new(TenantId.PlatformSentinel, null)], + [new(TenantId.From(Guid.Empty), null)], + [new(TenantA, OrganizationId.From(Guid.Empty))], + [null!], + }) + { + var act = () => reader.ReadOnPlatformScopeAsync(handle, refused); + await act.Should().ThrowAsync(); + } + + // Nothing ran, so the scope is still usable: the bound itself is admitted. + (await reader.ReadOnPlatformScopeAsync(handle, + [.. Enumerable.Repeat(new IdentityLifecycleScope(TenantA, null), IIdentityScopeLifecycleReader.MaximumPlatformScopes)])) + .Should().HaveCount(IIdentityScopeLifecycleReader.MaximumPlatformScopes).And.OnlyContain(fact => fact.TenantAllowsOrdinaryWork); + await FluentActions.Awaiting(() => reader.ReadOnPlatformScopeAsync(null!, [new(TenantA, null)])) + .Should().ThrowAsync(); + } + + private sealed record Context(TenantId TenantId, OrganizationId? OrganizationId) : ITenantContext + { + public bool IsResolved => true; + public UserId? UserId => LearnStack.SharedKernel.Identifiers.UserId.SystemActor; + public string? CorrelationId => null; + public string? ModuleName => "identity"; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/InvitationSmtpStorageTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/InvitationSmtpStorageTests.cs index a2aaf53be..1ea0d7fb7 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/InvitationSmtpStorageTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/InvitationSmtpStorageTests.cs @@ -16,14 +16,17 @@ 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_provider_event_subject_status", "fn_identity_self_membership_scopes", "fn_identity_user_capacity_guard", "fn_identity_user_creation_audit_guard", + "fn_identity_user_status", "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_provider_event_subject_status", "fn_identity_self_membership_scopes", "fn_identity_user_status", "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 891cf7d22..e89a8bca5 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,10 @@ 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(34L, + "current Identity also installs three provider definers, one target transition guard, the federation connection guard, the operator subject resolver, the authority key guard, " + + "the four data-request guards with their chunk and completed-export completeness checks, the retained own data-request scope definer, " + + "the request guard's User status witness and the delayed provider mirror's subject status"); await _fixture.AssertCurrentHeadsRefuseReversalAsync(); await EducationSchemaSeed.SeedAsync(_fixture.Postgres.AppConnectionString); await using var app = await PostgresFixture.OpenAsync(_fixture.Postgres.AppConnectionString); @@ -219,16 +222,38 @@ 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 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."); + 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."); + Action ownDataRequestScopes = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.add_own_data_request_scopes().DownOperations; + ownDataRequestScopes.Should().Throw().WithMessage("The retained own data-request scope requires a reviewed forward migration."); + Action platformDataRequests = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.grant_platform_data_request_operations().DownOperations; + platformDataRequests.Should().Throw().WithMessage("The platform data-request operations require a reviewed forward migration."); + Action erasureClearing = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.admit_erasure_profile_clearing().DownOperations; + erasureClearing.Should().Throw().WithMessage("The erasure profile clearing requires a reviewed forward migration."); + Action accountClosure = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.admit_account_closure().DownOperations; + accountClosure.Should().Throw().WithMessage("The account closure storage requires a reviewed forward migration."); + Action providerSubjectStatus = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.refuse_closing_provider_event_delivery().DownOperations; + providerSubjectStatus.Should().Throw().WithMessage("The provider event subject status requires a reviewed forward migration."); + Action closureFinalize = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.admit_closure_finalize().DownOperations; + closureFinalize.Should().Throw().WithMessage("The closure finalize storage requires a reviewed forward migration."); + Action guardHardening = () => _ = new LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.harden_closure_request_guard().DownOperations; + guardHardening.Should().Throw().WithMessage("The closure request guard hardening requires a reviewed forward migration."); foreach (var (context, immediate, historical, head, reason) in new (DbContext, string, string, string, string)[] { (tenancy, "20261029112940_guard_retained_tenancy_defaults", TenancyReversibleHead, "20261109230237_membership_field_consent_evidence", "Retained consent evidence requires a reviewed forward migration."), - (platform, "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."), + (platform, "20261120120000_grant_platform_delivery_inspection", PlatformReversibleHead, + "20261122160000_add_data_request_protected_receipts", "Retained data request receipts require a reviewed forward migration."), + (identity, "20261123120000_admit_closure_finalize", IdentityReversibleHead, + "20261123130000_harden_closure_request_guard", "The closure request guard hardening 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 f25059952..1e77b85bc 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/OwnDataRequestScopeTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/OwnDataRequestScopeTests.cs new file mode 100644 index 000000000..eab917016 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/OwnDataRequestScopeTests.cs @@ -0,0 +1,533 @@ +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); + // The platform role reads six closed Membership columns for a closure's participants (ADR-0107 § 8), never a + // whole row; the outbox role reads nothing of the table. + var read = () => ScalarAsync(other, null, + role == "platform" ? "SELECT count(created_by) FROM public.memberships" : "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 = await DataExportTestKit.OpenAppAsync(database.AppConnectionString)) + { + 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.Integration/Database/PlatformAdminScopeTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs index 8a12dae2e..4922108ae 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs @@ -4,7 +4,9 @@ using LearnStack.Infrastructure.MultiTenancy; using LearnStack.Modules.Tenancy.Application.Audit; using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; using LearnStack.SharedKernel.Tenancy; using LearnStack.SharedKernel.Time; using Microsoft.Extensions.DependencyInjection; @@ -1418,6 +1420,232 @@ public async Task Two_First_Toggles_Of_One_Key_Serialise_On_The_Row_Lock() } } + [Fact] + public async Task Only_The_Erasure_Completion_And_The_Closure_Finalize_Redact_Each_Its_Own_Plans_And_A_Refusal_Leaves_The_Scope_Usable() + { + // ADR-0108 § 2, ADR-0107 § 7: the redaction is bound to the admitted operation and the plan's pass. complete_erasure + // redacts an erasure's plan and the closure's Finalize a closure's tenant and sentinel passes; each is refused the + // other's, and every other operation that enters the platform scope is refused all three. A refusal comes before + // the executor is resolved and is not a failed statement. + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var redactor = new RecordingRedactor(); + var scope = Build(dataSource, NullLogger.Instance, AuditStoreScopeFactory(redactor)); + var tenant = Guid.CreateVersion7(); + var plans = new (string Name, AuditRedactionPlan Plan, PlatformOperation Owner)[] + { + ("erasure", Plan(tenant), PlatformOperations.ErasureComplete), + ("closure tenant pass", ClosureTenantPlan(tenant), PlatformOperations.ClosureFinalize), + ("closure sentinel pass", ClosureSentinelPlan(), PlatformOperations.ClosureFinalize), + }; + var entering = PlatformOperations.All.Where(operation => operation.NeedsPlatformRole).ToList(); + entering.Should().Contain([PlatformOperations.ErasureComplete, PlatformOperations.ClosureFinalize]).And.HaveCountGreaterThan(2); + + foreach (var operation in entering) + { + await using var handle = await scope.EnterAsync(TestPlatformAdmissions.Admission(operation)); + foreach (var (name, plan, _) in plans.Where(candidate => !ReferenceEquals(candidate.Owner, operation))) + { + var redact = async () => await handle.RedactAuditAsync(plan); + + await redact.Should().ThrowAsync(name + " under " + operation.AuditSlug) + .WithMessage("*may not redact*"); + (await ScalarAsync(handle, "SELECT 1")).Should().Be(1, "a refusal before anything ran does not fault the scope"); + } + } + + redactor.Calls.Should().BeEmpty("no pairing but the sanctioned ones reaches the executor"); + + // And each owner's own plans do reach it, with the admission its scope was entered with. + foreach (var owner in new[] { PlatformOperations.ErasureComplete, PlatformOperations.ClosureFinalize }) + { + var admission = TestPlatformAdmissions.Admission(owner); + await using var handle = await scope.EnterAsync(admission); + foreach (var (_, plan, _) in plans.Where(candidate => ReferenceEquals(candidate.Owner, owner))) + { + await handle.RedactAuditAsync(plan); + var call = redactor.Calls[^1]; + call.Plan.Should().BeSameAs(plan); + call.Admission.Should().BeSameAs(admission); + } + } + + redactor.Calls.Select(call => call.Plan.Pass).Should().Equal( + AuditRedactionPass.Erasure, AuditRedactionPass.ClosureTenant, AuditRedactionPass.ClosureSentinel); + } + + [Fact] + public async Task The_Redaction_Runs_On_The_Scope_s_Connection_And_Transaction_With_Its_Admission_And_Commits_With_The_Result_Row() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var host = $"redact-{Guid.NewGuid():N}.example.com"; + var redactor = new RecordingRedactor(async (connection, transaction) => + { + // The executor's statements are the scope's: the same backend and transaction, so its write commits or rolls + // back with the act. A host row stands in for the audit rows it would change. + await ScalarAsync(connection, transaction, + "INSERT INTO platform_host_to_tenant (host, tenant_id, is_active, is_publicly_live) VALUES (@h, @t, true, true) RETURNING 1", + ("h", host), ("t", SchemaFixture.TenantA)); + return await ScalarAsync(connection, transaction, "SELECT txid_current()"); + }); + var scope = Build(dataSource, NullLogger.Instance, AuditStoreScopeFactory(redactor)); + var admission = TestPlatformAdmissions.Admission( + PlatformOperations.ErasureComplete, ticket: "INC-9", correlationId: $"corr-{Guid.NewGuid():N}"); + var target = Guid.CreateVersion7(); + var plan = Plan(target); + + await using (var handle = await scope.EnterAsync(admission)) + { + var own = await ScalarAsync(handle, "SELECT txid_current()"); + + var report = await handle.RedactAuditAsync(plan); + + var call = redactor.Calls.Should().ContainSingle().Which; + call.Plan.Should().BeSameAs(plan); + call.Admission.Should().BeSameAs(admission, "the executor checks the admission the scope was entered with"); + redactor.Observed.Should().Equal([own], "the executor ran inside the scope's own work transaction"); + report.RowsSelected.Should().Be(0); + await handle.WriteResultAsync(new PlatformResult( + TenantId.From(target), "DataSubjectRequest", plan.Subject.RequestId.ToString("D"), "{}", report.ToClosedJson())); + await handle.CommitAsync(); + } + + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + (await ScalarAsync(read, null, "SELECT count(*) FROM platform_host_to_tenant WHERE host = @h", ("h", host))) + .Should().Be(1, "the redaction committed with the result row"); + var rows = await Rows(read, admission.Operator.CorrelationId!); + var result = rows.Single(row => row.Operation == PlatformOperations.ErasureComplete.AuditSlug); + result.Tenant.Should().Be(target, "the result row names the request's real tenant"); + result.Actor.Should().BeNull(); + result.Metadata.Should().NotContain("INC-9", "a row the tenant can read never carries the operator's ticket"); + rows.Single(row => row.Operation == PlatformAdminScope.EnterOperation).Metadata.Should().Contain("INC-9"); + + await using var cleanup = await Build(dataSource).EnterAsync(Admission()); + await cleanup.ExecuteAsync("DELETE FROM platform_host_to_tenant WHERE host = @h", [new PlatformSqlParameter("h", host)]); + await CompleteAsync(cleanup); + } + + [Fact] + public async Task A_Redaction_Rolls_Back_With_A_Scope_That_Is_Abandoned_And_Writes_Nothing_After_Its_Result_Row_Or_Its_End() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var host = $"abandon-{Guid.NewGuid():N}.example.com"; + var redactor = new RecordingRedactor(async (connection, transaction) => + { + await ScalarAsync(connection, transaction, + "INSERT INTO platform_host_to_tenant (host, tenant_id, is_active, is_publicly_live) VALUES (@h, @t, true, true) RETURNING 1", + ("h", host), ("t", SchemaFixture.TenantA)); + return 0; + }); + var scope = Build(dataSource, NullLogger.Instance, AuditStoreScopeFactory(redactor)); + var target = Guid.CreateVersion7(); + + await using (var abandoned = await scope.EnterAsync(TestPlatformAdmissions.Admission(PlatformOperations.ErasureComplete))) + { + await abandoned.RedactAuditAsync(Plan(target)); + // Disposed without a commit. + } + + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + (await ScalarAsync(read, null, "SELECT count(*) FROM platform_host_to_tenant WHERE host = @h", ("h", host))) + .Should().Be(0, "an abandoned act rolls its redaction back with it"); + + var handle = await scope.EnterAsync(TestPlatformAdmissions.Admission(PlatformOperations.ErasureComplete)); + await handle.WriteResultAsync(new PlatformResult(TenantId.From(target), "DataSubjectRequest", target.ToString("D"), null, "{}")); + var afterResult = async () => await handle.RedactAuditAsync(Plan(target)); + await afterResult.Should().ThrowAsync().WithMessage("*last write*", + "a redaction after the result row would change what the row does not describe"); + await handle.CommitAsync(); + var afterCommit = async () => await handle.RedactAuditAsync(Plan(target)); + await afterCommit.Should().ThrowAsync("the connection closed at the commit"); + await handle.DisposeAsync(); + var afterDisposal = async () => await handle.RedactAuditAsync(Plan(target)); + await afterDisposal.Should().ThrowAsync(); + redactor.Calls.Should().ContainSingle("only the abandoned act reached the executor"); + } + + [Fact] + public async Task A_Failed_Redaction_Faults_The_Scope_So_Nothing_Of_The_Act_Commits_While_The_Entry_Stays() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var host = $"failed-{Guid.NewGuid():N}.example.com"; + var redactor = new RecordingRedactor(async (connection, transaction) => + await ScalarAsync(connection, transaction, "SELECT 1/0")); + var scope = Build(dataSource, NullLogger.Instance, AuditStoreScopeFactory(redactor)); + var admission = TestPlatformAdmissions.Admission(PlatformOperations.ErasureComplete, correlationId: $"corr-{Guid.NewGuid():N}"); + var target = Guid.CreateVersion7(); + + await using (var handle = await scope.EnterAsync(admission)) + { + await InsertHostAsync(handle, host); + + var redact = async () => await handle.RedactAuditAsync(Plan(target)); + + await redact.Should().ThrowAsync("the executor's failure is the caller's, unchanged"); + var result = async () => await handle.WriteResultAsync( + new PlatformResult(TenantId.From(target), "DataSubjectRequest", target.ToString("D"), null, "{}")); + await result.Should().ThrowAsync().WithMessage("*Dispose the scope*"); + var commit = async () => await handle.CommitAsync(); + await commit.Should().ThrowAsync(); + } + + await using var read = await PostgresFixture.OpenAsync(_schema.Postgres.PlatformConnectionString); + (await ScalarAsync(read, null, "SELECT count(*) FROM platform_host_to_tenant WHERE host = @h", ("h", host))) + .Should().Be(0, "the work before the failed redaction rolled back with it"); + (await Rows(read, admission.Operator.CorrelationId!)).Should().ContainSingle() + .Which.Operation.Should().Be(PlatformAdminScope.EnterOperation, "the entry is on the record and no result row is"); + } + + [Fact] + public async Task Without_A_Registered_Executor_A_Completion_Cannot_Redact_And_Cannot_Commit() + { + await using var dataSource = PlatformSource(_schema.Postgres.PlatformConnectionString); + var target = Guid.CreateVersion7(); + await using var handle = await Build(dataSource).EnterAsync(TestPlatformAdmissions.Admission(PlatformOperations.ErasureComplete)); + + var redact = async () => await handle.RedactAuditAsync(Plan(target)); + + await redact.Should().ThrowAsync().WithMessage("*IAuditRedactor*", + "a deployment that cannot redact refuses by name rather than completing an erasure with nothing redacted"); + var result = async () => await handle.WriteResultAsync( + new PlatformResult(TenantId.From(target), "DataSubjectRequest", target.ToString("D"), null, "{}")); + await result.Should().ThrowAsync().WithMessage("*Dispose the scope*"); + } + + /// A plan for an erasure a person filed in a tenant-wide group; its identifiers are fresh. + private static AuditRedactionPlan Plan(Guid tenant) => new(new UserDataSubject( + Guid.CreateVersion7(), DataRequestKind.Erasure, DataRequestOrigin.Self, UserId.From(Guid.CreateVersion7()), + new DataRequestScopeGroup(TenantId.From(tenant), null), [Guid.CreateVersion7()])); + + /// A closure's pass over a tenant; its identifiers are fresh. + private static AuditRedactionPlan ClosureTenantPlan(Guid tenant) => + AuditRedactionPlan.ForClosureTenant(TenantId.From(tenant), UserId.From(Guid.CreateVersion7()), [Guid.CreateVersion7()]); + + /// A closure's pass over the platform sentinel tenant; its identifiers are fresh. + private static AuditRedactionPlan ClosureSentinelPlan() => AuditRedactionPlan.ForClosureSentinel( + UserId.From(Guid.CreateVersion7()), IdentitySubjectKey.FromBytes(System.Security.Cryptography.RandomNumberGenerator.GetBytes(32))); + + /// Records each call and runs on the handed-over connection and transaction. + private sealed class RecordingRedactor( + Func>? work = null) : IAuditRedactor + { + public List<(AuditRedactionPlan Plan, PlatformAdmission Admission, System.Data.Common.DbTransaction Transaction)> Calls { get; } = []; + + public List Observed { get; } = []; + + public async Task RedactAsync( + AuditRedactionPlan plan, PlatformAdmission admission, System.Data.Common.DbConnection connection, + System.Data.Common.DbTransaction transaction, CancellationToken cancellationToken = default) + { + Calls.Add((plan, admission, transaction)); + if (work is not null) + { + Observed.Add(await work(connection, transaction)); + } + + return new AuditRedactionReport(0, new Dictionary(), []); + } + } + private static Task InsertHostAsync(IPlatformAdminScopeHandle handle, string host) => handle.ExecuteAsync( "INSERT INTO platform_host_to_tenant (host, tenant_id, is_active, is_publicly_live) VALUES (@host, @tenant, true, true)", @@ -1552,8 +1780,8 @@ private static PlatformAdminScope Build( new SystemGuidFactory(), logger); - private static IServiceScopeFactory AuditStoreScopeFactory() => - new ServiceCollection() + private static IServiceScopeFactory AuditStoreScopeFactory(IAuditRedactor? redactor = null) => + (redactor is null ? new ServiceCollection() : new ServiceCollection().AddSingleton(redactor)) .AddMetrics() .AddLogging() .AddScoped() diff --git a/backend/tests/LearnStack.Tests.Integration/Database/PlatformOperatorOnboardingTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/PlatformOperatorOnboardingTests.cs index cb8af710b..a90f11ac9 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/PlatformOperatorOnboardingTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/PlatformOperatorOnboardingTests.cs @@ -856,6 +856,12 @@ public async ValueTask DisposeAsync() /// Counts the outcome label of every onboarding act counted while it is alive. private sealed class ActOutcomes : IDisposable { + private static readonly string[] Onboarding = + [ + PlatformOperations.TenantProvision.AuditSlug, PlatformOperations.HostMap.AuditSlug, PlatformOperations.RoleInitialize.AuditSlug, + PlatformOperations.FirstAdminCreate.AuditSlug, PlatformOperations.AdminRecover.AuditSlug, + ]; + private readonly MeterListener _listener = new(); private readonly Dictionary _counts = []; @@ -871,15 +877,19 @@ public ActOutcomes() }; _listener.SetMeasurementEventCallback((_, _, tags, _) => { + // The meter is process-wide: a closure's fan-out acts another class runs at the same time are not this + // proof's, so only the onboarding acts are counted. + string? operation = null, outcome = null; foreach (var tag in tags) { - if (tag is { Key: "outcome", Value: string outcome }) - { - lock (_counts) - { - _counts[outcome] = _counts.GetValueOrDefault(outcome) + 1; - } - } + if (tag is { Key: "operation", Value: string named }) operation = named; + if (tag is { Key: "outcome", Value: string ended }) outcome = ended; + } + + if (outcome is null || !Onboarding.Contains(operation)) return; + lock (_counts) + { + _counts[outcome] = _counts.GetValueOrDefault(outcome) + 1; } }); _listener.Start(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/ProviderEventStorageTests.Closure.cs b/backend/tests/LearnStack.Tests.Integration/Database/ProviderEventStorageTests.Closure.cs new file mode 100644 index 000000000..304c2515f --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/ProviderEventStorageTests.Closure.cs @@ -0,0 +1,66 @@ +using FluentAssertions; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// +/// ADR-0097's intake table and ADR-0107 § 7 ("a person cannot be resurrected by ... provider intake"): a fact about a +/// person whose User is Closing, or Closed, is a durable receipt only, subject_closed, with no tenant target, so no +/// mirror is ever produced for it. The same person's fact while Active is the control: it routes to the person's tenant. +/// +public sealed partial class ProviderEventStorageTests +{ + [Theory] + [InlineData("Closing")] + [InlineData("Closed")] + public async Task A_fact_about_a_closing_or_closed_User_is_receipt_only_subject_closed_without_a_target(string status) + { + // A person of this case alone, so the shared fixture's people are untouched. + var person = Guid.CreateVersion7(); + await IdentityMembershipFixture.InsertUserAsync(fixture.Postgres.AppConnectionString, person); + await using (var app = await OpenAsync(fixture.Postgres.AppConnectionString)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await IdentityMembershipFixture.ScopeAsync(app, transaction, SchemaFixture.TenantA); + await IdentityMembershipFixture.LockAsync(app, transaction, SchemaFixture.TenantA, person, false); + await IdentityMembershipFixture.InsertMemberAsync(app, transaction, SchemaFixture.TenantA, null, Guid.CreateVersion7(), person, + IdentityMembershipFixture.RoleId(SchemaFixture.TenantA, BuiltInRoleKey.Learner, PermissionScope.Tenant)); + await IdentityMembershipFixture.ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await transaction.CommitAsync(); + } + + var active = await AcceptAsync(Guid.CreateVersion7(), "LOGIN", SubjectKey(person)); + (active.Accepted, active.Disposition, active.Count).Should().Be((true, "routed", 1), "the Active person's fact reaches the tenant"); + + // The closure's transitions, on the platform role under the User key and the person's one participant tenant key. + foreach (var sql in status == "Closed" + ? new[] { "UPDATE public.users SET status='Closing' WHERE id=@user", + "UPDATE public.users SET status='Closed', provider_subject=NULL WHERE id=@user" } + : ["UPDATE public.users SET status='Closing' WHERE id=@user"]) + { + await using var platform = await OpenAsync(fixture.Postgres.PlatformConnectionString); + await using var transaction = await platform.BeginTransactionAsync(); + await IdentityMembershipFixture.ExecuteAsync(platform, transaction, "SELECT pg_catalog.pg_advisory_xact_lock(@key)", + ("key", IdentityAdvisoryLockKey.ForUser(UserId.From(person)))); + await IdentityMembershipFixture.ExecuteAsync(platform, transaction, "SELECT pg_catalog.pg_advisory_xact_lock(@key)", + ("key", IdentityAdvisoryLockKey.ForTenant(TenantId.From(SchemaFixture.TenantA)))); + await IdentityMembershipFixture.ExecuteAsync(platform, transaction, sql, ("user", person)); + await transaction.CommitAsync(); + } + + var fact = Guid.CreateVersion7(); + var refused = await AcceptAsync(fact, "LOGIN", SubjectKey(person)); + + (refused.Accepted, refused.Disposition, refused.Count).Should().Be((true, "subject_closed", 0), + "a closing or closed person's fact is a durable receipt with no target"); + (await AcceptAsync(fact, "LOGIN", SubjectKey(person), refused.At)).Should().Be(refused, "the receipt is the fact's one answer"); + await using var reader = await OpenAsync(fixture.Postgres.AppConnectionString); + await using var read = await reader.BeginTransactionAsync(); + await IdentityMembershipFixture.ScopeAsync(reader, read, SchemaFixture.TenantA); + (await IdentityMembershipFixture.ScalarAsync(reader, read, + "SELECT count(*) FROM public.identity_provider_event_targets WHERE provider_event_id=@id", ("id", fact))).Should().Be(0); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/SchemaFixture.cs b/backend/tests/LearnStack.Tests.Integration/Database/SchemaFixture.cs index 75040c14b..734d7b4f0 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 f1674ff6b..f77574a49 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 e2e5f41ee..11a8c7a43 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.Integration/Database/TenantExistingBindingAdmissionTests.Observation.cs b/backend/tests/LearnStack.Tests.Integration/Database/TenantExistingBindingAdmissionTests.Observation.cs index 85eec1e12..e9b4800b5 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/TenantExistingBindingAdmissionTests.Observation.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/TenantExistingBindingAdmissionTests.Observation.cs @@ -171,7 +171,8 @@ private static async Task ExecuteOwnerAsync(IdentityPublicReadFixture database, { await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString); await using var transaction = await owner.BeginTransactionAsync(); - // The production schema admits no closure writer. This isolated database's + // The production schema admits only the platform session's fenced closure + // (ADR-0107 § 7), never the owner. This isolated database's // fixture temporarily enables owner-only setup and restores its trigger // and policy before COMMIT. Collision alone removes the exact digest CHECK // until the caller's finally restores the retained subject and definition. diff --git a/backend/tests/LearnStack.Tests.Integration/KillswitchToggleOrderingTests.cs b/backend/tests/LearnStack.Tests.Integration/KillswitchToggleOrderingTests.cs index fc743154a..cdc3e1a43 100644 --- a/backend/tests/LearnStack.Tests.Integration/KillswitchToggleOrderingTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/KillswitchToggleOrderingTests.cs @@ -1,6 +1,7 @@ using System.Data.Common; using FluentAssertions; using LearnStack.Modules.Tenancy.Infrastructure; +using LearnStack.SharedKernel.Audit; using LearnStack.SharedKernel.Caching; using LearnStack.SharedKernel.Entitlements; using LearnStack.SharedKernel.Platform; @@ -166,6 +167,10 @@ public Task WriteIntentAsync(PlatformResult intent, CancellationToken cancellati return Task.CompletedTask; } + public Task RedactAuditAsync( + AuditRedactionPlan plan, CancellationToken cancellationToken = default) => + throw new NotSupportedException("A killswitch toggle never redacts the audit log."); + public Task WriteResultAsync(PlatformResult result, CancellationToken cancellationToken = default) { Steps.Add("result"); diff --git a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.Closure.cs b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.Closure.cs new file mode 100644 index 000000000..0dff8552b --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.Closure.cs @@ -0,0 +1,324 @@ +using System.Net; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Xunit; + +namespace LearnStack.Tests.Integration; + +/// +/// The closure's Begin route (ADR-0107 §§ 7 and 8): the admission it runs under, the answers it maps, the key that admits +/// it, its counter, its document, and the production composition that fails the act closed with no fan-out registered. +/// +public sealed partial class PlatformOperatorHttpTests +{ + private const string ClosureRequest = "019a1929-5450-7bbb-8df1-516e8e002505"; + private const string BeginPath = DataRequests + "/" + ClosureRequest + "/begin-closure"; + + [Fact] + public async Task A_Begin_Runs_Under_An_Admission_For_Exactly_That_Operation_And_Answers_The_Closed_Tallies() + { + var response = await Call(HttpMethod.Post, BeginPath, Valid(), """{"ticket":"CHG-21"}"""); + + response.StatusCode.Should().Be(HttpStatusCode.OK, await response.Content.ReadAsStringAsync()); + var (admission, requestId) = _closures.Calls.Should().ContainSingle().Which; + requestId.Should().Be(Guid.Parse(ClosureRequest)); + admission.Operation.Should().BeSameAs(PlatformOperations.ClosureBegin); + admission.Ticket.Should().Be("CHG-21"); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + var root = body.RootElement; + root.GetProperty("outcome").GetString().Should().Be("begun"); + root.GetProperty("requestId").GetString().Should().Be(ClosureRequest); + root.GetProperty("status").GetString().Should().Be("fulfilling"); + root.GetProperty("complete").GetBoolean().Should().BeTrue(); + root.GetProperty("groups").ToString().Should().Be( + """{"served":2,"started":1,"adopted":1,"waiting":0,"failed":0,"unserved":1}"""); + root.GetProperty("correlationId").GetString().Should().Be(admission.Operator.CorrelationId); + root.EnumerateObject().Select(property => property.Name).Should().BeEquivalentTo( + ["outcome", "requestId", "status", "complete", "groups", "correlationId"], "the answer names no person and no tenant"); + } + + [Fact] + public async Task A_Begin_Whose_Fan_Out_Did_Not_Reach_Every_Group_Is_A_200_That_Says_It_Is_Incomplete() + { + _closures.Result = new ClosureBeginResult( + ClosureBeginOutcome.Resumed, "fulfilling", Groups: new ClosureBeginTally(3, 0, 1, 1, 1, 0)); + + var response = await Call(HttpMethod.Post, BeginPath, Valid(), "{}"); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + body.RootElement.GetProperty("outcome").GetString().Should().Be("resumed"); + body.RootElement.GetProperty("complete").GetBoolean().Should().BeFalse("a waiting or failed group is owed a repeat"); + body.RootElement.GetProperty("groups").GetProperty("failed").GetInt32().Should().Be(1); + } + + [Theory] + [InlineData(ClosureBeginOutcome.RefusedWindow, "refusal", "lockey_data_request_closure_refused", "blocked_window")] + [InlineData(ClosureBeginOutcome.RefusedHold, "refusal", "lockey_data_request_closure_refused", "blocked_hold")] + [InlineData(ClosureBeginOutcome.RefusedLastAdministrator, "refusal", "lockey_data_request_closure_refused", "blocked_last_administrator")] + [InlineData(ClosureBeginOutcome.NotClosure, "kind", "lockey_data_request_not_closure", null)] + [InlineData(ClosureBeginOutcome.NotBeginnable, "status", "lockey_data_request_closure_not_beginnable", "cancelled")] + [InlineData(ClosureBeginOutcome.SubjectNotAdmitted, "account", "lockey_data_request_closure_account_closed", null)] + public async Task A_Refused_Begin_Is_A_409_With_Its_Reason_On_The_Field_It_Concerns( + ClosureBeginOutcome outcome, string field, string reason, string? cause) + { + _closures.Result = new ClosureBeginResult( + outcome, outcome == ClosureBeginOutcome.NotBeginnable ? cause : "scheduled", + outcome is ClosureBeginOutcome.RefusedWindow or ClosureBeginOutcome.RefusedHold or ClosureBeginOutcome.RefusedLastAdministrator + ? cause : null); + + var response = await Call(HttpMethod.Post, BeginPath, Valid(), "{}"); + + response.StatusCode.Should().Be(HttpStatusCode.Conflict); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + body.RootElement.GetProperty("code").GetString().Should().Be("business_rule_violation"); + var errors = body.RootElement.GetProperty("errors"); + errors.EnumerateObject().Select(property => property.Name).Should().Equal([field], "the reason is on the field it concerns, and only there"); + errors.GetProperty(field)[0].GetProperty("key").GetString().Should().Be(reason); + if (cause is not null) + { + errors.GetProperty(field)[0].GetProperty("params").GetProperty("cause").GetString().Should().Be(cause, + "the closed code that refused it is the reason's cause"); + } + } + + [Fact] + public async Task A_Begin_That_Names_No_Request_Is_Not_Found() + { + _closures.Result = new ClosureBeginResult(ClosureBeginOutcome.NotFound); + + var response = await Call(HttpMethod.Post, BeginPath, Valid(), "{}"); + + response.StatusCode.Should().Be(HttpStatusCode.NotFound); + await AssertProblem(response, "not_found"); + } + + [Theory] + [InlineData("/data-requests/not-a-guid/begin-closure", HttpStatusCode.NotFound)] + [InlineData("/data-requests/00000000-0000-0000-0000-000000000000/begin-closure", HttpStatusCode.BadRequest)] + [InlineData("/data-requests/00000000-0000-7000-8000-000000000002/begin-closure", HttpStatusCode.BadRequest)] + [InlineData("/data-requests/4f9c5a3e-2b7d-4c1a-9e8f-0a1b2c3d4e5f/begin-closure", HttpStatusCode.BadRequest)] + public async Task A_Begin_Naming_No_Real_Request_Is_Refused_Without_Calling_The_Owner(string suffix, HttpStatusCode expected) + { + var response = await Call(HttpMethod.Post, "/api/platform/v1" + suffix, Valid(), "{}"); + + response.StatusCode.Should().Be(expected); + _closures.Calls.Should().BeEmpty(); + } + + [Fact] + public async Task A_Begin_Without_A_Body_Or_With_A_Bad_Ticket_Or_Media_Type_Is_Answered_Only_To_A_Granted_Operator() + { + (await Call(HttpMethod.Post, BeginPath, Valid())).StatusCode.Should().Be(HttpStatusCode.BadRequest); + (await Call(HttpMethod.Post, BeginPath, Valid(), """{"ticket":"has space"}""")).StatusCode.Should().Be(HttpStatusCode.BadRequest); + using var wrongType = new HttpRequestMessage(HttpMethod.Post, BeginPath) + { + Headers = { { "Authorization", "Bearer " + Valid() } }, + Content = new StringContent("{}", System.Text.Encoding.UTF8, "text/plain"), + }; + (await _client.SendAsync(wrongType)).StatusCode.Should().Be(HttpStatusCode.UnsupportedMediaType); + (await Call(HttpMethod.Post, BeginPath, Sign(("sub", "someone-else")), "not json")).StatusCode.Should().Be( + HttpStatusCode.Forbidden, "an operator without the grant learns nothing about the body"); + (await Call(HttpMethod.Post, BeginPath, "not-a-token", "{}")).StatusCode.Should().Be(HttpStatusCode.Unauthorized); + _closures.Calls.Should().BeEmpty(); + } + + [Fact] + public async Task A_Begin_Whose_Audit_Or_Fences_Failed_Or_Whose_Commit_Is_Unknown_Is_A_Retryable_503_With_Its_Own_Reason() + { + foreach (var (failure, reason) in new (Exception, string)[] + { + (new AuditWriteFailedException("forced"), "audit_unavailable"), + (new OperatorRecoveryUnavailableException(cause: new TimeoutException("forced")), "dependency_unavailable"), + (new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true, cause: new TimeoutException("forced")), "outcome_unknown"), + }) + { + _closures.Failure = failure; + + var response = await Call(HttpMethod.Post, BeginPath, Valid(), "{}"); + + response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable, reason); + response.Headers.RetryAfter.Should().NotBeNull(reason); + var text = await response.Content.ReadAsStringAsync(); + text.Should().NotContain("forced"); + using var body = JsonDocument.Parse(text); + body.RootElement.GetProperty("code").GetString().Should().Be(reason == "outcome_unknown" ? "dependency_unavailable" : reason); + body.RootElement.TryGetProperty("errors", out var errors).Should().Be(reason == "outcome_unknown", reason); + if (reason == "outcome_unknown") errors.GetProperty("outcome").ToString().Should().Contain("outcome_unknown"); + } + } + + [Fact] + public async Task The_Begin_Counter_Is_Labelled_By_The_Operation_Slug_And_A_Closed_Outcome_And_Counts_Only_Calls_That_Reached_The_Owner() + { + using var counted = new OperatorCounterListener(PlatformOperatorMetrics.DataRequestCounterName); + + (await Call(HttpMethod.Post, BeginPath, Valid(), "{}")).StatusCode.Should().Be(HttpStatusCode.OK); + (await Call(HttpMethod.Post, BeginPath, Valid())).StatusCode.Should().Be(HttpStatusCode.BadRequest); + foreach (var result in new[] + { + new ClosureBeginResult(ClosureBeginOutcome.Begun, "fulfilling", Groups: new ClosureBeginTally(1, 0, 0, 0, 1, 0)), + new ClosureBeginResult(ClosureBeginOutcome.Resumed, "fulfilling", Groups: new ClosureBeginTally(1, 0, 1, 0, 0, 0)), + new ClosureBeginResult(ClosureBeginOutcome.Resumed, "fulfilling", Groups: new ClosureBeginTally(1, 0, 0, 1, 0, 0)), + new ClosureBeginResult(ClosureBeginOutcome.RefusedWindow, "scheduled", "blocked_window"), + new ClosureBeginResult(ClosureBeginOutcome.RefusedHold, "scheduled", "blocked_hold"), + new ClosureBeginResult(ClosureBeginOutcome.RefusedLastAdministrator, "scheduled", "blocked_last_administrator"), + new ClosureBeginResult(ClosureBeginOutcome.NotFound), + new ClosureBeginResult(ClosureBeginOutcome.NotClosure, "scheduled"), + new ClosureBeginResult(ClosureBeginOutcome.NotBeginnable, "completed"), + new ClosureBeginResult(ClosureBeginOutcome.SubjectNotAdmitted, "scheduled"), + }) + { + _closures.Result = result; + (await Call(HttpMethod.Post, BeginPath, Valid(), "{}")).Should().NotBeNull(); + } + + _closures.Failure = new AuditWriteFailedException("forced"); + (await Call(HttpMethod.Post, BeginPath, Valid(), "{}")).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + _closures.Failure = new OperatorRecoveryUnavailableException(cause: new TimeoutException("forced")); + (await Call(HttpMethod.Post, BeginPath, Valid(), "{}")).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + _closures.Failure = new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true); + (await Call(HttpMethod.Post, BeginPath, Valid(), "{}")).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + _closures.Failure = new InvalidOperationException("forced defect"); + var failed = await Call(HttpMethod.Post, BeginPath, Valid(), "{}"); + failed.StatusCode.Should().Be(HttpStatusCode.InternalServerError, "the failure still propagates to the host"); + (await failed.Content.ReadAsStringAsync()).Should().NotContain("forced defect"); + + // The meter is process-wide: a closure's fan-out groups another class counts at the same time are not this route's. + const string Slug = "platform.closure.begin"; + counted.Calls.Where(call => call.Operation == Slug).Should().Equal( + (Slug, "begun"), (Slug, "begun_partial"), (Slug, "resumed"), (Slug, "resumed_partial"), (Slug, "blocked_window"), + (Slug, "blocked_hold"), (Slug, "blocked_last_administrator"), (Slug, "not_found"), (Slug, "not_closure"), + (Slug, "not_beginnable"), (Slug, "account_closed"), (Slug, "audit_unavailable"), (Slug, "unavailable"), + (Slug, "commit_unknown"), (Slug, "failed")); + } + + [Theory] + [InlineData(DataRequestKey.None)] + [InlineData(DataRequestKey.Read)] + [InlineData(DataRequestKey.Write)] + public async Task Only_The_Data_Request_Write_Key_Admits_A_Begin(DataRequestKey held) + { + // ADR-0107 § 8: Begin is a write under platform.data_request.write. The read key does not admit it, and None holds + // every other registered Platform key. + string[] keys = held switch + { + DataRequestKey.Read => [PlatformPermissions.DataRequestRead.Key], + DataRequestKey.Write => [PlatformPermissions.DataRequestWrite.Key], + _ => PlatformPermissions.All + .Where(key => key != PlatformPermissions.DataRequestRead && key != PlatformPermissions.DataRequestWrite) + .Select(key => key.Key).ToArray(), + }; + var closures = new RecordingClosures(); + await using var single = new PlatformOperatorApiFactory(_tenant, _operator, _toggle, grantSubject: Subject, + services: registrations => registrations.AddScoped(_ => closures), + permissions: keys); + using var client = single.CreateClient(); + using var request = new HttpRequestMessage(HttpMethod.Post, BeginPath) + { + Headers = { { "Authorization", "Bearer " + Valid() } }, + Content = new StringContent("{}", System.Text.Encoding.UTF8, "application/json"), + }; + + (await client.SendAsync(request)).StatusCode.Should().Be(held == DataRequestKey.Write ? HttpStatusCode.OK : HttpStatusCode.Forbidden); + closures.Calls.Should().HaveCount(held == DataRequestKey.Write ? 1 : 0); + } + + [Fact] + public async Task The_Production_Composition_Resolves_The_Closure_Owner_And_Fails_The_Act_Closed_Without_A_Fan_Out() + { + // Production's registrations, with the platform scope recorded and every fan-out removed: the act is refused before + // the scope is entered, so no person can be moved to Closing by a host that cannot fan the closure out. The owner + // reads Tenancy's lifecycle port, whose registration holds the request's unit of work, so the host is given the + // application credential's holder a deployment has; nothing here connects with it. + var scope = new RecordingScope(); + await using var production = new PlatformOperatorApiFactory(_tenant, _operator, _toggle, grantSubject: Subject, + services: registrations => + { + registrations.RemoveAll(); + registrations.Replace(ServiceDescriptor.Singleton(scope)); + registrations.Replace(ServiceDescriptor.Singleton(_ => new LearnStack.Infrastructure.Persistence.ApplicationDataSourceLifetime( + "Host=localhost;Port=1;Database=learnstack;Username=learnstack_app"))); + }); + using var client = production.CreateClient(); + await using (var resolved = production.Services.CreateAsyncScope()) + { + resolved.ServiceProvider.GetRequiredService() + .Should().BeOfType(); + } + + using var counted = new OperatorCounterListener(PlatformOperatorMetrics.DataRequestCounterName); + using var request = new HttpRequestMessage(HttpMethod.Post, BeginPath) + { + Headers = { { "Authorization", "Bearer " + Valid() } }, + Content = new StringContent("{}", System.Text.Encoding.UTF8, "application/json"), + }; + var response = await client.SendAsync(request); + + response.StatusCode.Should().Be(HttpStatusCode.InternalServerError, "a host that cannot fan out is a deployment defect"); + scope.Entered.Should().Be(0, "the act was refused before it entered the platform scope"); + // The meter is process-wide: a closure's fan-out groups another class counts at the same time are not this route's. + counted.Calls.Where(call => call.Operation == "platform.closure.begin").Should().Equal(("platform.closure.begin", "failed")); + } + + [Fact] + public async Task The_Served_Contract_Documents_The_Begin_s_Refusals_Partial_Answer_And_Runbook() + { + using var document = JsonDocument.Parse(await _client.GetStringAsync("/openapi/platform-v1.json")); + var begin = document.RootElement.GetProperty("paths").GetProperty("/api/platform/v1/data-requests/{requestId}/begin-closure") + .GetProperty("post"); + begin.GetProperty("description").GetString().Should().Contain("blocked_window").And.Contain("blocked_hold") + .And.Contain("blocked_last_administrator").And.Contain("complete is false").And.Contain("unserved"); + begin.GetProperty("responses").GetProperty("409").GetProperty("description").GetString() + .Should().Contain("errors.refusal").And.Contain("errors.account").And.Contain("A closure Begin answers 409"); + begin.GetProperty("responses").GetProperty("503").GetProperty("description").GetString() + .Should().Contain("three seconds"); + document.RootElement.GetProperty("info").GetProperty("description").GetString().Should().Contain("account-closure.md"); + } + + /// A platform scope that counts its entries and enters nothing. + private sealed class RecordingScope : IPlatformAdminScope + { + public int Entered { get; private set; } + + public Task EnterAsync( + PlatformAdmission admission, CancellationToken cancellationToken = default, + [System.Runtime.CompilerServices.CallerMemberName] string? callerMember = null, + [System.Runtime.CompilerServices.CallerFilePath] string? callerFile = null, + [System.Runtime.CompilerServices.CallerLineNumber] int callerLine = 0) + { + Entered++; + return Task.FromException(new InvalidOperationException("No scope is entered in this test.")); + } + } + + private sealed class RecordingClosures : IAccountClosureOperatorOperations + { + public List<(PlatformAdmission Admission, Guid RequestId)> Calls { get; } = []; + public List<(PlatformAdmission Admission, Guid RequestId)> FinalizeCalls { get; } = []; + public Exception? Failure { get; set; } + public ClosureBeginResult Result { get; set; } = new( + ClosureBeginOutcome.Begun, "fulfilling", Groups: new ClosureBeginTally(2, 1, 1, 0, 0, 1)); + public ClosureFinalizeResult FinalizeResult { get; set; } = FinalizedResult(); + + public Task BeginAsync( + PlatformAdmission admission, Guid closureRequestId, CancellationToken cancellationToken = default) + { + Calls.Add((admission, closureRequestId)); + return Failure is not null ? Task.FromException(Failure) : Task.FromResult(Result); + } + + public Task FinalizeAsync( + PlatformAdmission admission, Guid closureRequestId, CancellationToken cancellationToken = default) + { + FinalizeCalls.Add((admission, closureRequestId)); + return Failure is not null ? Task.FromException(Failure) : Task.FromResult(FinalizeResult); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.ClosureBounds.cs b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.ClosureBounds.cs new file mode 100644 index 000000000..550696644 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.ClosureBounds.cs @@ -0,0 +1,75 @@ +using System.Globalization; +using System.Net; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Platform; +using Xunit; + +namespace LearnStack.Tests.Integration; + +/// +/// The closure routes' answers for what a closure could never finish (ADR-0107 § 7): a Begin refused for the closure's +/// size or for an account the provider's port could never delete answers 409 on the field it concerns, with no cause, no +/// count and no identifier; each has its own counter outcome; and the served contract says what the operator does, and +/// that a Finalize's unavailable answer after its provider step may follow a deleted account. +/// +public sealed partial class PlatformOperatorHttpTests +{ + [Theory] + [InlineData(ClosureBeginOutcome.RefusedTooLarge, "participants", "lockey_data_request_closure_too_large")] + [InlineData(ClosureBeginOutcome.RefusedProvider, "provider", "lockey_account_removal_unavailable")] + public async Task A_Begin_Refused_For_What_It_Could_Never_Finish_Is_A_409_On_Its_Own_Field_With_Nothing_Else( + ClosureBeginOutcome outcome, string field, string reason) + { + _closures.Result = new ClosureBeginResult(outcome, "scheduled"); + + var response = await Call(HttpMethod.Post, BeginPath, Valid(), "{}"); + + response.StatusCode.Should().Be(HttpStatusCode.Conflict); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + body.RootElement.GetProperty("code").GetString().Should().Be("business_rule_violation"); + var errors = body.RootElement.GetProperty("errors"); + errors.EnumerateObject().Select(property => property.Name).Should().Equal([field], "the reason is on the field it concerns, and only there"); + var message = errors.GetProperty(field)[0]; + message.GetProperty("key").GetString().Should().Be(reason); + if (message.TryGetProperty("params", out var parameters) && parameters.ValueKind == JsonValueKind.Object) + { + parameters.EnumerateObject().Should().BeEmpty("no group, no person and no count is named"); + } + } + + [Fact] + public async Task The_Begin_Counter_Counts_The_Refusals_Of_What_A_Closure_Could_Never_Finish_Under_Their_Own_Outcomes() + { + using var counted = new OperatorCounterListener(PlatformOperatorMetrics.DataRequestCounterName); + + foreach (var outcome in new[] { ClosureBeginOutcome.RefusedTooLarge, ClosureBeginOutcome.RefusedProvider }) + { + _closures.Result = new ClosureBeginResult(outcome, "scheduled"); + (await Call(HttpMethod.Post, BeginPath, Valid(), "{}")).StatusCode.Should().Be(HttpStatusCode.Conflict); + } + + const string Slug = "platform.closure.begin"; + counted.Calls.Where(call => call.Operation == Slug).Should().Equal((Slug, "refused_too_large"), (Slug, "refused_provider")); + } + + [Fact] + public async Task The_Served_Contract_Says_What_A_Closure_Could_Never_Finish_And_What_A_Late_Unavailable_Finalize_Means() + { + using var document = JsonDocument.Parse(await _client.GetStringAsync("/openapi/platform-v1.json")); + var paths = document.RootElement.GetProperty("paths"); + var begin = paths.GetProperty("/api/platform/v1/data-requests/{requestId}/begin-closure").GetProperty("post"); + begin.GetProperty("description").GetString().Should() + .Contain(ClosureLimits.MaximumParticipantGroups.ToString(CultureInfo.InvariantCulture) + " participant groups, served or not") + .And.Contain(ClosureLimits.MaximumTenantMemberships.ToString(CultureInfo.InvariantCulture) + " Memberships in one participant tenant") + .And.Contain("could never delete"); + begin.GetProperty("responses").GetProperty("409").GetProperty("description").GetString().Should() + .Contain("errors.participants").And.Contain("errors.provider").And.Contain("Phase 11's data operations"); + var finalize = paths.GetProperty("/api/platform/v1/data-requests/{requestId}/finalize-closure").GetProperty("post"); + finalize.GetProperty("description").GetString().Should().Contain("User fence alone").And.Contain("stays required"); + finalize.GetProperty("responses").GetProperty("503").GetProperty("description").GetString().Should() + .Contain("the person's account may already be deleted at the provider"); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.ClosureFinalize.cs b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.ClosureFinalize.cs new file mode 100644 index 000000000..79a9b8119 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.ClosureFinalize.cs @@ -0,0 +1,301 @@ +using System.Net; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Platform; +using Microsoft.Extensions.DependencyInjection; +using Xunit; + +namespace LearnStack.Tests.Integration; + +/// +/// The closure's Finalize route (ADR-0107 §§ 7 and 8, ADR-0108 § 8): the admission it runs under, the answers it maps (the +/// finalization's closed counts and unserved groups, the refusals on the field they concern, the provider's closed outcome +/// on a retryable 503), the key that admits it, its counter and its document. +/// +public sealed partial class PlatformOperatorHttpTests +{ + private const string FinalizePath = DataRequests + "/" + ClosureRequest + "/finalize-closure"; + private const string UnservedTenant = "019a1929-5450-7bbb-8df1-516e8e0025a1"; + private const string UnservedOrganization = "019a1929-5450-7bbb-8df1-516e8e0025a2"; + + [Fact] + public async Task A_Finalize_Runs_Under_An_Admission_For_Exactly_That_Operation_And_Answers_Closed_Counts_And_The_Unserved_Groups() + { + var response = await Call(HttpMethod.Post, FinalizePath, Valid(), """{"ticket":"CHG-31"}"""); + + response.StatusCode.Should().Be(HttpStatusCode.OK, await response.Content.ReadAsStringAsync()); + var (admission, requestId) = _closures.FinalizeCalls.Should().ContainSingle().Which; + _closures.Calls.Should().BeEmpty("a Finalize is not a Begin"); + requestId.Should().Be(Guid.Parse(ClosureRequest)); + admission.Operation.Should().BeSameAs(PlatformOperations.ClosureFinalize); + admission.Ticket.Should().Be("CHG-31"); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + var root = body.RootElement; + root.GetProperty("outcome").GetString().Should().Be("finalized"); + root.GetProperty("requestId").GetString().Should().Be(ClosureRequest); + root.GetProperty("status").GetString().Should().Be("completed"); + root.GetProperty("groups").ToString().Should().Be( + """{"served":3,"ready":3,"pending":0,"unserved":1,"erasuresCompleted":3,"closuresCompleted":2}"""); + root.GetProperty("unservedGroups").ToString().Should().Be( + $$"""[{"tenantId":"{{UnservedTenant}}","organizationId":"{{UnservedOrganization}}"}]"""); + var redaction = root.GetProperty("redaction"); + redaction.GetProperty("tenants").GetInt32().Should().Be(2); + redaction.GetProperty("rowsSelected").GetInt64().Should().Be(9); + redaction.GetProperty("redacted").GetProperty("ip_address").GetInt64().Should().Be(5); + redaction.GetProperty("retained").GetProperty("audit_metadata_reference").GetInt64().Should().Be(3); + root.GetProperty("retained").ToString().Should().Be("""{"audit_actor_reference":4,"unserved_group":1}"""); + root.GetProperty("correlationId").GetString().Should().Be(admission.Operator.CorrelationId); + root.EnumerateObject().Select(property => property.Name).Should().BeEquivalentTo( + ["outcome", "requestId", "status", "groups", "unservedGroups", "redaction", "retained", "correlationId"], + "the answer names no person: tenants and organizations of unserved groups, and counts"); + } + + [Fact] + public async Task A_Repeat_After_The_Finalize_Landed_Answers_What_It_Recorded_And_No_Counts_Of_Its_Own() + { + _closures.FinalizeResult = new ClosureFinalizeResult( + ClosureFinalizeOutcome.AlreadyFinalized, "completed", + Retained: new Dictionary(StringComparer.Ordinal) { ["audit_actor_reference"] = 4, ["unserved_group"] = 0 }); + + var response = await Call(HttpMethod.Post, FinalizePath, Valid(), "{}"); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + var root = body.RootElement; + root.GetProperty("outcome").GetString().Should().Be("already_finalized"); + root.GetProperty("status").GetString().Should().Be("completed"); + root.GetProperty("groups").ValueKind.Should().Be(JsonValueKind.Null); + root.GetProperty("redaction").ValueKind.Should().Be(JsonValueKind.Null); + root.GetProperty("unservedGroups").GetArrayLength().Should().Be(0); + root.GetProperty("retained").ToString().Should().Be("""{"audit_actor_reference":4,"unserved_group":0}"""); + } + + [Theory] + [InlineData(ClosureFinalizeOutcome.NotClosure, "kind", "lockey_data_request_not_closure", null)] + [InlineData(ClosureFinalizeOutcome.NotFinalizable, "status", "lockey_data_request_closure_not_finalizable", "scheduled")] + [InlineData(ClosureFinalizeOutcome.NotFinalizable, "status", "lockey_data_request_closure_not_finalizable", "cancelled")] + public async Task A_Refused_Finalize_Is_A_409_With_Its_Reason_On_The_Field_It_Concerns( + ClosureFinalizeOutcome outcome, string field, string reason, string? cause) + { + _closures.FinalizeResult = new ClosureFinalizeResult(outcome, cause ?? "scheduled"); + + var response = await Call(HttpMethod.Post, FinalizePath, Valid(), "{}"); + + response.StatusCode.Should().Be(HttpStatusCode.Conflict); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + body.RootElement.GetProperty("code").GetString().Should().Be("business_rule_violation"); + var errors = body.RootElement.GetProperty("errors"); + errors.EnumerateObject().Select(property => property.Name).Should().Equal([field]); + errors.GetProperty(field)[0].GetProperty("key").GetString().Should().Be(reason); + if (cause is not null) + { + errors.GetProperty(field)[0].GetProperty("params").GetProperty("cause").GetString().Should().Be(cause); + } + } + + [Fact] + public async Task A_Finalize_Before_Every_Served_Group_Is_Ready_Is_A_409_With_Closed_Tallies_And_No_Group_Named() + { + _closures.FinalizeResult = new ClosureFinalizeResult( + ClosureFinalizeOutcome.GroupsPending, "fulfilling", new ClosureFinalizeTally(Served: 3, Ready: 1, Pending: 2, Unserved: 1)); + + var response = await Call(HttpMethod.Post, FinalizePath, Valid(), "{}"); + + response.StatusCode.Should().Be(HttpStatusCode.Conflict); + var text = await response.Content.ReadAsStringAsync(); + text.Should().NotContain(UnservedTenant); + using var body = JsonDocument.Parse(text); + var groups = body.RootElement.GetProperty("errors").GetProperty("groups")[0]; + groups.GetProperty("key").GetString().Should().Be("lockey_data_request_closure_groups_pending"); + groups.GetProperty("params").ToString().Should().Be("""{"served":"3","ready":"1","pending":"2","unserved":"1"}"""); + } + + [Fact] + public async Task A_Finalize_That_Names_No_Request_Is_Not_Found_And_Naming_No_Real_Request_Never_Calls_The_Owner() + { + _closures.FinalizeResult = new ClosureFinalizeResult(ClosureFinalizeOutcome.NotFound); + var response = await Call(HttpMethod.Post, FinalizePath, Valid(), "{}"); + response.StatusCode.Should().Be(HttpStatusCode.NotFound); + await AssertProblem(response, "not_found"); + _closures.FinalizeCalls.Clear(); + + foreach (var (suffix, expected) in new[] + { + ("/data-requests/not-a-guid/finalize-closure", HttpStatusCode.NotFound), + ("/data-requests/00000000-0000-0000-0000-000000000000/finalize-closure", HttpStatusCode.BadRequest), + ("/data-requests/00000000-0000-7000-8000-000000000002/finalize-closure", HttpStatusCode.BadRequest), + ("/data-requests/4f9c5a3e-2b7d-4c1a-9e8f-0a1b2c3d4e5f/finalize-closure", HttpStatusCode.BadRequest), + }) + { + (await Call(HttpMethod.Post, "/api/platform/v1" + suffix, Valid(), "{}")).StatusCode.Should().Be(expected, suffix); + } + + (await Call(HttpMethod.Post, FinalizePath, Valid())).StatusCode.Should().Be(HttpStatusCode.BadRequest, "no body"); + (await Call(HttpMethod.Post, FinalizePath, Valid(), """{"ticket":"has space"}""")).StatusCode.Should().Be(HttpStatusCode.BadRequest); + (await Call(HttpMethod.Post, FinalizePath, Sign(("sub", "someone-else")), "not json")).StatusCode.Should().Be( + HttpStatusCode.Forbidden, "an operator without the grant learns nothing about the body"); + _closures.FinalizeCalls.Should().BeEmpty(); + } + + [Theory] + [InlineData(ClosureFinalizeOutcome.ProviderRefused, "lockey_provider_refused")] + [InlineData(ClosureFinalizeOutcome.ProviderUnavailable, "lockey_provider_unavailable")] + [InlineData(ClosureFinalizeOutcome.ProviderUncertain, "lockey_provider_outcome_unknown")] + public async Task A_Finalize_The_Provider_Did_Not_Finish_Is_A_Retryable_503_With_The_Provider_s_Closed_Outcome( + ClosureFinalizeOutcome outcome, string reason) + { + _closures.FinalizeResult = new ClosureFinalizeResult(outcome, "fulfilling", Redaction: Aggregate()); + + var response = await Call(HttpMethod.Post, FinalizePath, Valid(), "{}"); + + response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + response.Headers.RetryAfter.Should().NotBeNull(); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + body.RootElement.GetProperty("code").GetString().Should().Be("dependency_unavailable"); + var errors = body.RootElement.GetProperty("errors"); + errors.EnumerateObject().Select(property => property.Name).Should().Equal(["provider"]); + errors.GetProperty("provider")[0].GetProperty("key").GetString().Should().Be(reason); + } + + [Fact] + public async Task A_Finalize_Whose_Audit_Or_Fences_Failed_Or_Whose_Commit_Is_Unknown_Is_A_Retryable_503_With_Its_Own_Reason() + { + foreach (var (failure, reason) in new (Exception, string)[] + { + (new AuditWriteFailedException("forced"), "audit_unavailable"), + (new OperatorRecoveryUnavailableException(cause: new TimeoutException("forced")), "dependency_unavailable"), + (new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true, cause: new TimeoutException("forced")), "outcome_unknown"), + }) + { + _closures.Failure = failure; + + var response = await Call(HttpMethod.Post, FinalizePath, Valid(), "{}"); + + response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable, reason); + response.Headers.RetryAfter.Should().NotBeNull(reason); + var text = await response.Content.ReadAsStringAsync(); + text.Should().NotContain("forced"); + using var body = JsonDocument.Parse(text); + body.RootElement.GetProperty("code").GetString().Should().Be(reason == "outcome_unknown" ? "dependency_unavailable" : reason); + body.RootElement.TryGetProperty("errors", out var errors).Should().Be(reason == "outcome_unknown", reason); + if (reason == "outcome_unknown") errors.GetProperty("outcome").ToString().Should().Contain("outcome_unknown"); + } + } + + [Fact] + public async Task The_Finalize_Counter_Is_Labelled_By_The_Operation_Slug_And_A_Closed_Outcome_And_Counts_Only_Calls_That_Reached_The_Owner() + { + using var counted = new OperatorCounterListener(PlatformOperatorMetrics.DataRequestCounterName); + + (await Call(HttpMethod.Post, FinalizePath, Valid(), "{}")).StatusCode.Should().Be(HttpStatusCode.OK); + (await Call(HttpMethod.Post, FinalizePath, Valid())).StatusCode.Should().Be(HttpStatusCode.BadRequest); + foreach (var result in new[] + { + new ClosureFinalizeResult(ClosureFinalizeOutcome.AlreadyFinalized, "completed"), + new ClosureFinalizeResult(ClosureFinalizeOutcome.NotFound), + new ClosureFinalizeResult(ClosureFinalizeOutcome.NotClosure, "scheduled"), + new ClosureFinalizeResult(ClosureFinalizeOutcome.NotFinalizable, "cancelled"), + new ClosureFinalizeResult(ClosureFinalizeOutcome.GroupsPending, "fulfilling", new ClosureFinalizeTally(1, 0, 1, 0)), + new ClosureFinalizeResult(ClosureFinalizeOutcome.ProviderRefused, "fulfilling"), + new ClosureFinalizeResult(ClosureFinalizeOutcome.ProviderUnavailable, "fulfilling"), + new ClosureFinalizeResult(ClosureFinalizeOutcome.ProviderUncertain, "fulfilling"), + }) + { + _closures.FinalizeResult = result; + (await Call(HttpMethod.Post, FinalizePath, Valid(), "{}")).Should().NotBeNull(); + } + + _closures.Failure = new AuditWriteFailedException("forced"); + (await Call(HttpMethod.Post, FinalizePath, Valid(), "{}")).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + _closures.Failure = new OperatorRecoveryUnavailableException(cause: new TimeoutException("forced")); + (await Call(HttpMethod.Post, FinalizePath, Valid(), "{}")).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + _closures.Failure = new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true); + (await Call(HttpMethod.Post, FinalizePath, Valid(), "{}")).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + _closures.Failure = new InvalidOperationException("forced defect"); + var failed = await Call(HttpMethod.Post, FinalizePath, Valid(), "{}"); + failed.StatusCode.Should().Be(HttpStatusCode.InternalServerError, "the failure still propagates to the host"); + (await failed.Content.ReadAsStringAsync()).Should().NotContain("forced defect"); + + // The meter is process-wide: a closure's fan-out groups another class counts at the same time are not this route's. + const string Slug = "platform.closure.finalize"; + counted.Calls.Where(call => call.Operation == Slug).Should().Equal( + (Slug, "finalized"), (Slug, "already_finalized"), (Slug, "not_found"), (Slug, "not_closure"), (Slug, "not_finalizable"), + (Slug, "groups_pending"), (Slug, "provider_refused"), (Slug, "provider_unavailable"), (Slug, "provider_uncertain"), + (Slug, "audit_unavailable"), (Slug, "unavailable"), (Slug, "commit_unknown"), (Slug, "failed")); + } + + [Theory] + [InlineData(DataRequestKey.None)] + [InlineData(DataRequestKey.Read)] + [InlineData(DataRequestKey.Write)] + public async Task Only_The_Data_Request_Write_Key_Admits_A_Finalize(DataRequestKey held) + { + // ADR-0107 § 8: Finalize is a write under platform.data_request.write. The read key does not admit it, and None holds + // every other registered Platform key. + string[] keys = held switch + { + DataRequestKey.Read => [PlatformPermissions.DataRequestRead.Key], + DataRequestKey.Write => [PlatformPermissions.DataRequestWrite.Key], + _ => PlatformPermissions.All + .Where(key => key != PlatformPermissions.DataRequestRead && key != PlatformPermissions.DataRequestWrite) + .Select(key => key.Key).ToArray(), + }; + var closures = new RecordingClosures(); + await using var single = new PlatformOperatorApiFactory(_tenant, _operator, _toggle, grantSubject: Subject, + services: registrations => registrations.AddScoped(_ => closures), + permissions: keys); + using var client = single.CreateClient(); + using var request = new HttpRequestMessage(HttpMethod.Post, FinalizePath) + { + Headers = { { "Authorization", "Bearer " + Valid() } }, + Content = new StringContent("{}", System.Text.Encoding.UTF8, "application/json"), + }; + + (await client.SendAsync(request)).StatusCode.Should().Be(held == DataRequestKey.Write ? HttpStatusCode.OK : HttpStatusCode.Forbidden); + closures.FinalizeCalls.Should().HaveCount(held == DataRequestKey.Write ? 1 : 0); + } + + [Fact] + public async Task The_Served_Contract_Documents_The_Finalize_s_Readiness_Provider_Outcomes_And_Repeat() + { + using var document = JsonDocument.Parse(await _client.GetStringAsync("/openapi/platform-v1.json")); + var finalize = document.RootElement.GetProperty("paths") + .GetProperty("/api/platform/v1/data-requests/{requestId}/finalize-closure").GetProperty("post"); + finalize.GetProperty("operationId").GetString().Should().Be("PlatformClosureFinalize"); + finalize.GetProperty("description").GetString().Should().Contain("awaits its privileged step").And.Contain("unserved") + .And.Contain("intent row").And.Contain("missing account is success").And.Contain("already_finalized"); + finalize.GetProperty("responses").GetProperty("409").GetProperty("description").GetString() + .Should().Contain("errors.groups").And.Contain("A closure Finalize answers 409"); + finalize.GetProperty("responses").GetProperty("503").GetProperty("description").GetString() + .Should().Contain("errors.provider").And.Contain("lockey_provider_outcome_unknown"); + finalize.GetProperty("requestBody").GetProperty("content").GetProperty("application/json").ValueKind + .Should().Be(JsonValueKind.Object, "the body is the ticket's, as for every data-request act"); + } + + /// A finalization of three served groups and one unserved, with the redaction this call's passes did. + private static ClosureFinalizeResult FinalizedResult() => new( + ClosureFinalizeOutcome.Finalized, "completed", new ClosureFinalizeTally(3, 3, 0, 1, 3, 2), + [new ClosureParticipantGroup(TenantId.From(Guid.Parse(UnservedTenant)), OrganizationId.From(Guid.Parse(UnservedOrganization)))], + Aggregate(), + new Dictionary(StringComparer.Ordinal) { ["audit_actor_reference"] = 4, ["unserved_group"] = 1 }); + + private static AuditRedactionAggregate Aggregate() + { + static AuditRedactionReport Report(long selected, long redacted, params (RetainedReferenceKind Kind, long Count)[] retained) => new( + selected, + Enum.GetValues().ToDictionary(column => column, column => column is AuditRedactedColumn.IpAddress + or AuditRedactedColumn.UserAgent or AuditRedactedColumn.ActorEmail ? redacted : 0L), + [.. retained.Select(entry => new RetainedReferenceCount(entry.Kind, entry.Count))]); + return new AuditRedactionAggregate( + new Dictionary + { + [TenantId.From(Guid.CreateVersion7())] = Report(2, 1, (RetainedReferenceKind.AuditActorReference, 1)), + [TenantId.From(Guid.CreateVersion7())] = Report(2, 1, (RetainedReferenceKind.AuditEntityReference, 2)), + }, + Report(5, 3, (RetainedReferenceKind.AuditMetadataReference, 3))); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs index a3a753d6c..223e149cf 100644 --- a/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/PlatformOperatorHttpTests.cs @@ -7,6 +7,7 @@ using LearnStack.Api.Authentication; using LearnStack.Infrastructure.PlatformOperator; using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; using LearnStack.SharedKernel.Entitlements; using LearnStack.SharedKernel.Platform; using Microsoft.AspNetCore.Hosting; @@ -37,7 +38,7 @@ namespace LearnStack.Tests.Integration; /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1001:Types that own disposable fields should be disposable", Justification = "xUnit disposes the fields through IAsyncLifetime.DisposeAsync.")] -public sealed class PlatformOperatorHttpTests : IAsyncLifetime +public sealed partial class PlatformOperatorHttpTests : IAsyncLifetime { private const string Path = "/api/platform/v1/killswitches/killswitch.classroom.recording"; private const string Subject = "operator-sub-1"; @@ -49,6 +50,8 @@ public sealed class PlatformOperatorHttpTests : IAsyncLifetime private RecordingRecovery _recovery = null!; private RecordingInspection _inspection = null!; private RecordingBrokers _brokers = null!; + private RecordingDataRequests _dataRequests = null!; + private RecordingClosures _closures = null!; private CapturingLogs _logs = null!; private HttpClient _client = null!; @@ -60,6 +63,8 @@ public async Task InitializeAsync() _recovery = new RecordingRecovery(); _inspection = new RecordingInspection(); _brokers = new RecordingBrokers(); + _dataRequests = new RecordingDataRequests(); + _closures = new RecordingClosures(); _logs = new CapturingLogs(); _factory = new PlatformOperatorApiFactory(_tenant, _operator, _toggle, grantSubject: Subject, services: registrations => @@ -69,6 +74,8 @@ public async Task InitializeAsync() registrations.AddSingleton(_recovery); registrations.AddScoped(_ => _inspection); registrations.AddScoped(_ => _brokers); + registrations.AddScoped(_ => _dataRequests); + registrations.AddScoped(_ => _closures); }); _client = _factory.CreateClient(); } @@ -572,6 +579,10 @@ JsonElement ParameterOf(string route, string name) => root.GetProperty("paths"). ParameterOf(outbox, "limit").GetProperty("minimum").GetRawText().Trim('"').Should().Be("1"); ParameterOf(outbox, "cursor").GetProperty("maxLength").GetInt32().Should().Be(512); ParameterOf(outbox, "ticket").GetProperty("pattern").GetString().Should().Be(@"^[A-Za-z0-9._:/#-]{1,64}$"); + ParameterOf(DataRequests, "state").GetProperty("enum").EnumerateArray().Select(value => value.GetString()) + .Should().Equal(["awaiting_privileged_step", "overdue_scheduled", "stuck_fulfilling", "expired_artifact"], + "the data-request inspection offers its own closed lists, not the recovery's"); + ParameterOf(DataRequests, "limit").GetProperty("minimum").GetRawText().Trim('"').Should().Be("1"); } private const string Work = "/api/platform/v1/asynchronous-work"; @@ -840,7 +851,7 @@ public async Task A_Failed_Federation_Audit_Write_Is_The_Retryable_Audit_503_And [InlineData("remove")] public async Task A_Database_Fault_The_Federation_Owner_Translates_Is_A_Retryable_503_Without_An_Unknown_Outcome(string act) { - using var federation = new FederationListener(); + using var federation = new OperatorCounterListener(); _brokers.Failure = new OperatorRecoveryUnavailableException(cause: new InvalidOperationException("the database is not reachable")); var response = act == "report" @@ -858,7 +869,7 @@ public async Task A_Database_Fault_The_Federation_Owner_Translates_Is_A_Retryabl [Fact] public async Task The_Federation_Counter_Is_Labelled_By_The_Operation_Slug_And_A_Closed_Outcome_And_Counts_Only_Calls_That_Reached_The_Owner() { - using var federation = new FederationListener(); + using var federation = new OperatorCounterListener(); (await Call(HttpMethod.Get, Fed, Valid())).StatusCode.Should().Be(HttpStatusCode.OK); (await Call(HttpMethod.Post, $"{Fed}/{BrokerAlias}/remove", Valid(), "{}")).StatusCode.Should().Be(HttpStatusCode.OK); @@ -1203,15 +1214,26 @@ public async Task The_Production_Composition_Resolves_The_Recovery_Owner_And_The "/api/platform/v1/federation/brokers", "/api/platform/v1/federation/brokers/{alias}/remove", "/api/platform/v1/federation/brokers/{alias}/disable", + "/api/platform/v1/data-requests", + "/api/platform/v1/data-requests/{requestId}/complete-erasure", + "/api/platform/v1/data-requests/{requestId}/begin-closure", + "/api/platform/v1/data-requests/{requestId}/finalize-closure", ]; - /// The verb each operator route answers: reads are GET, recovery acts are POST, the rest are idempotent PUTs. + /// + /// The verb each operator route answers: reads are GET, recovery, federation and data-request acts are POST, the rest + /// are idempotent PUTs. + /// private static string VerbOf(string route) => route.Contains("/asynchronous-work/", StringComparison.Ordinal) ? route.EndsWith("/replay", StringComparison.Ordinal) || route.EndsWith("/reset", StringComparison.Ordinal) ? "post" : "get" : route.Contains("/federation/", StringComparison.Ordinal) ? route.EndsWith("/remove", StringComparison.Ordinal) || route.EndsWith("/disable", StringComparison.Ordinal) ? "post" : "get" - : "put"; + : route.Contains("/data-requests", StringComparison.Ordinal) + ? route.EndsWith("/complete-erasure", StringComparison.Ordinal) || route.EndsWith("/begin-closure", StringComparison.Ordinal) + || route.EndsWith("/finalize-closure", StringComparison.Ordinal) + ? "post" : "get" + : "put"; [Fact] public async Task Without_An_Issuer_The_Surface_And_Its_Document_Do_Not_Exist() @@ -1246,7 +1268,7 @@ public async Task The_Operator_Scheme_Is_Not_The_Default_And_The_Tenant_Scheme_S } [Fact] - public void The_Operator_Surface_Is_Exactly_The_Fourteen_Authorized_Endpoints_Under_Its_Prefix() + public void The_Operator_Surface_Is_Exactly_The_Eighteen_Authorized_Endpoints_Under_Its_Prefix() { // The tenant surface census excludes this surface by exact type (it has its own scheme), so // its population is closed here instead: every routed endpoint under /api/platform (whatever @@ -1262,7 +1284,8 @@ public void The_Operator_Surface_Is_Exactly_The_Fourteen_Authorized_Endpoints_Un endpoints.Select(endpoint => endpoint.RoutePattern.RawText).Should().BeEquivalentTo( OperatorRoutes.Select(route => route.Replace("{tenantId}", "{tenantId:guid}").Replace("{roleId}", "{roleId:guid}") - .Replace("{membershipId}", "{membershipId:guid}").Replace("{eventId}", "{eventId:guid}")), + .Replace("{membershipId}", "{membershipId:guid}").Replace("{eventId}", "{eventId:guid}") + .Replace("{requestId}", "{requestId:guid}")), "the operator population is closed: a new route is a reviewed act with its own policy, grant and audit slug"); foreach (var endpoint in endpoints) { @@ -1276,6 +1299,359 @@ public void The_Operator_Surface_Is_Exactly_The_Fourteen_Authorized_Endpoints_Un } } + private const string DataRequests = "/api/platform/v1/data-requests"; + private const string ErasureRequest = "019a1929-5450-7bbb-8df1-516e8e002503"; + private const string CompletePath = DataRequests + "/" + ErasureRequest + "/complete-erasure"; + + [Fact] + public async Task A_Data_Request_Inspection_Passes_Its_List_And_Page_On_Under_An_Admission_For_The_Inspection() + { + var response = await Call(HttpMethod.Get, DataRequests + "?state=stuck_fulfilling&limit=500&cursor=abc&ticket=CHG-7", Valid()); + + response.StatusCode.Should().Be(HttpStatusCode.OK, await response.Content.ReadAsStringAsync()); + var (admission, query, requestId) = _dataRequests.Calls.Should().ContainSingle().Which; + requestId.Should().BeNull(); + query!.State.Should().Be(DataRequestInspectionState.StuckFulfilling); + query.Cursor.Should().Be("abc"); + query.Limit.Should().Be(100, "a limit above the maximum is clamped, as Standard 04 says"); + admission.Operation.Should().BeSameAs(PlatformOperations.DataRequestInspect); + admission.Ticket.Should().Be("CHG-7"); + var body = await response.Content.ReadAsStringAsync(); + body.Should().Contain("\"items\":[").And.Contain("\"requestId\":\"" + ErasureRequest + "\"").And.Contain("\"nextCursor\":\"next-cursor\"") + .And.Contain("\"hasNext\":true"); + } + + [Theory] + [InlineData("", DataRequestInspectionState.AwaitingPrivilegedStep)] + [InlineData("?state=awaiting_privileged_step", DataRequestInspectionState.AwaitingPrivilegedStep)] + [InlineData("?state=overdue_scheduled", DataRequestInspectionState.OverdueScheduled)] + [InlineData("?state=stuck_fulfilling", DataRequestInspectionState.StuckFulfilling)] + [InlineData("?state=expired_artifact", DataRequestInspectionState.ExpiredArtifact)] + public async Task A_Data_Request_Inspection_Reads_The_Closed_List_It_Names_And_The_Awaiting_One_By_Default( + string query, DataRequestInspectionState expected) + { + var response = await Call(HttpMethod.Get, DataRequests + query, Valid()); + + response.StatusCode.Should().Be(HttpStatusCode.OK, await response.Content.ReadAsStringAsync()); + _dataRequests.Calls.Should().ContainSingle().Which.Query!.State.Should().Be(expected); + } + + [Theory] + [InlineData("state=bogus", "state")] + [InlineData("state=AWAITING_PRIVILEGED_STEP", "state")] + [InlineData("state=dead_lettered", "state")] + [InlineData("limit=0", "limit")] + [InlineData("limit=abc", "limit")] + [InlineData("limt=5", "query")] + [InlineData("subject=019a1929-5450-7bbb-8df1-516e8e002504", "query")] + public async Task A_Data_Request_Inspection_Refuses_A_Bad_Or_Unknown_Parameter_And_Names_It_Without_Echo(string query, string field) + { + var response = await Call(HttpMethod.Get, DataRequests + "?" + query, Valid()); + + response.StatusCode.Should().Be(HttpStatusCode.BadRequest); + var text = await response.Content.ReadAsStringAsync(); + using var body = JsonDocument.Parse(text); + body.RootElement.GetProperty("errors").TryGetProperty(field, out _).Should().BeTrue(field); + text.Should().NotContain("limt").And.NotContain("subject").And.NotContain("bogus"); + _dataRequests.Calls.Should().BeEmpty("a refused parameter enters no scope"); + } + + [Fact] + public async Task A_Cursor_The_Data_Request_Owner_Refuses_Is_A_Validation_Failure_And_Its_Faults_Are_Retryable_503s() + { + _dataRequests.RefuseCursor = true; + var refused = await Call(HttpMethod.Get, DataRequests + "?cursor=forged", Valid()); + refused.StatusCode.Should().Be(HttpStatusCode.BadRequest); + using (var body = JsonDocument.Parse(await refused.Content.ReadAsStringAsync())) + { + body.RootElement.GetProperty("errors").TryGetProperty("cursor", out _).Should().BeTrue(); + } + + _dataRequests.RefuseCursor = false; + foreach (var (failure, code) in new (Exception, string)[] + { + (new AuditWriteFailedException("forced"), "audit_unavailable"), + (new OperatorRecoveryUnavailableException(cause: new TimeoutException("forced")), "dependency_unavailable"), + }) + { + _dataRequests.Failure = failure; + var response = await Call(HttpMethod.Get, DataRequests, Valid()); + + response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable, code); + response.Headers.RetryAfter.Should().NotBeNull(code); + await AssertProblem(response, code); + (await response.Content.ReadAsStringAsync()).Should().NotContain("forced", "the cause is for the log, never the response"); + } + } + + [Fact] + public async Task An_Erasure_Completion_Runs_Under_An_Admission_For_Exactly_That_Operation_And_Answers_The_Closed_Report() + { + var response = await Call(HttpMethod.Post, CompletePath, Valid(), """{"ticket":"CHG-11"}"""); + + response.StatusCode.Should().Be(HttpStatusCode.OK, await response.Content.ReadAsStringAsync()); + var (admission, query, requestId) = _dataRequests.Calls.Should().ContainSingle().Which; + query.Should().BeNull(); + requestId.Should().Be(Guid.Parse(ErasureRequest)); + admission.Operation.Should().BeSameAs(PlatformOperations.ErasureComplete); + admission.Ticket.Should().Be("CHG-11"); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + var root = body.RootElement; + root.GetProperty("outcome").GetString().Should().Be("completed"); + root.GetProperty("requestId").GetString().Should().Be(ErasureRequest); + root.GetProperty("tenantId").GetString().Should().Be(RowTenant); + root.GetProperty("rowsSelected").GetInt64().Should().Be(7); + root.GetProperty("redacted").EnumerateObject().Select(column => column.Name).Should().BeEquivalentTo( + ["ip_address", "user_agent", "actor_email", "before_state", "after_state", "changes"], "every column is reported, zero or not"); + root.GetProperty("redacted").GetProperty("ip_address").GetInt64().Should().Be(3); + root.GetProperty("retained").GetProperty("audit_actor_reference").GetInt64().Should().Be(4); + root.GetProperty("retained").GetProperty("consent_evidence").GetInt64().Should().Be(1); + root.GetProperty("correlationId").GetString().Should().Be(admission.Operator.CorrelationId); + } + + [Fact] + public async Task The_Data_Request_Counter_Is_Labelled_By_The_Operation_Slug_And_A_Closed_Outcome_And_Counts_Only_Calls_That_Reached_The_Owner() + { + using var counted = new OperatorCounterListener(PlatformOperatorMetrics.DataRequestCounterName); + + (await Call(HttpMethod.Get, DataRequests, Valid())).StatusCode.Should().Be(HttpStatusCode.OK); + (await Call(HttpMethod.Get, DataRequests + "?limit=0", Valid())).StatusCode.Should().Be(HttpStatusCode.BadRequest); + (await Call(HttpMethod.Post, CompletePath, Valid(), "{}")).StatusCode.Should().Be(HttpStatusCode.OK); + _dataRequests.Completion = new ErasureCompletionResult(ErasureCompletionOutcome.ClosureFanout, Guid.Parse(RowTenant), "awaiting_privileged_step"); + (await Call(HttpMethod.Post, CompletePath, Valid(), "{}")).StatusCode.Should().Be(HttpStatusCode.Conflict); + _dataRequests.Failure = new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true); + (await Call(HttpMethod.Post, CompletePath, Valid(), "{}")).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + _dataRequests.Failure = null; + + // The remaining outcomes: each is its own closed token, so an alert keyed on one cannot be fed by another. + _dataRequests.RefuseCursor = true; + (await Call(HttpMethod.Get, DataRequests + "?cursor=forged", Valid())).StatusCode.Should().Be(HttpStatusCode.BadRequest); + _dataRequests.RefuseCursor = false; + foreach (var outcome in new[] + { + ErasureCompletionOutcome.NotFound, ErasureCompletionOutcome.NotErasure, ErasureCompletionOutcome.NotAwaiting, + ErasureCompletionOutcome.AlreadyCompleted, + }) + { + _dataRequests.Completion = new ErasureCompletionResult( + outcome, Guid.Parse(RowTenant), "scheduled", DateTimeOffset.UnixEpoch, new Dictionary()); + (await Call(HttpMethod.Post, CompletePath, Valid(), "{}")).Should().NotBeNull(); + } + + _dataRequests.Failure = new AuditWriteFailedException("forced"); + (await Call(HttpMethod.Get, DataRequests, Valid())).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + (await Call(HttpMethod.Post, CompletePath, Valid(), "{}")).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + _dataRequests.Failure = new OperatorRecoveryUnavailableException(cause: new TimeoutException("forced")); + (await Call(HttpMethod.Get, DataRequests, Valid())).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + (await Call(HttpMethod.Post, CompletePath, Valid(), "{}")).StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + + // A defect (a plain exception from the owner) is counted "failed" and still propagates: the host answers its own 500. + _dataRequests.Failure = new InvalidOperationException("forced defect"); + var failedInspection = await Call(HttpMethod.Get, DataRequests, Valid()); + var failedCompletion = await Call(HttpMethod.Post, CompletePath, Valid(), "{}"); + failedInspection.StatusCode.Should().Be(HttpStatusCode.InternalServerError, "the failure still propagates to the host"); + failedCompletion.StatusCode.Should().Be(HttpStatusCode.InternalServerError, "the failure still propagates to the host"); + (await failedInspection.Content.ReadAsStringAsync()).Should().NotContain("forced defect"); + (await failedCompletion.Content.ReadAsStringAsync()).Should().NotContain("forced defect"); + + // The meter is process-wide: a closure's fan-out groups another class counts at the same time are not this route's. + counted.Calls.Where(call => call.Operation != PlatformOperations.ClosureFanOut.AuditSlug).Should().Equal( + ("platform.data_request.inspect", "ok"), ("audit.redaction.apply", "completed"), ("audit.redaction.apply", "closure_fanout"), + ("audit.redaction.apply", "commit_unknown"), ("platform.data_request.inspect", "invalid_cursor"), + ("audit.redaction.apply", "not_found"), ("audit.redaction.apply", "not_erasure"), ("audit.redaction.apply", "not_awaiting"), + ("audit.redaction.apply", "already_completed"), + ("platform.data_request.inspect", "audit_unavailable"), ("audit.redaction.apply", "audit_unavailable"), + ("platform.data_request.inspect", "unavailable"), ("audit.redaction.apply", "unavailable"), + ("platform.data_request.inspect", "failed"), ("audit.redaction.apply", "failed")); + } + + [Fact] + public async Task A_Repeat_Of_A_Landed_Completion_Answers_Already_Completed_With_The_Recorded_Result_And_No_Counts() + { + _dataRequests.Completion = new ErasureCompletionResult( + ErasureCompletionOutcome.AlreadyCompleted, Guid.Parse(RowTenant), "completed", DateTimeOffset.UnixEpoch, + new Dictionary { ["audit_actor_reference"] = 4 }); + + var response = await Call(HttpMethod.Post, CompletePath, Valid(), "{}"); + + response.StatusCode.Should().Be(HttpStatusCode.OK); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + body.RootElement.GetProperty("outcome").GetString().Should().Be("already_completed"); + body.RootElement.GetProperty("retained").GetProperty("audit_actor_reference").GetInt64().Should().Be(4); + body.RootElement.TryGetProperty("redacted", out var redacted).Should().BeTrue(); + redacted.ValueKind.Should().Be(JsonValueKind.Null, "a repeat redacted nothing and the first call's counts are in the audit row"); + body.RootElement.GetProperty("rowsSelected").ValueKind.Should().Be(JsonValueKind.Null); + } + + [Theory] + [InlineData(ErasureCompletionOutcome.NotErasure, "kind", "lockey_data_request_not_erasure", null)] + [InlineData(ErasureCompletionOutcome.ClosureFanout, "origin", "lockey_data_request_closure_fanout", null)] + [InlineData(ErasureCompletionOutcome.NotAwaiting, "status", "lockey_data_request_not_awaiting_privileged_step", "scheduled")] + public async Task A_Refused_Completion_Is_A_409_With_Its_Reason_On_The_Field_It_Concerns( + ErasureCompletionOutcome outcome, string field, string reason, string? cause) + { + _dataRequests.Completion = new ErasureCompletionResult(outcome, Guid.Parse(RowTenant), cause ?? "completed"); + + var response = await Call(HttpMethod.Post, CompletePath, Valid(), "{}"); + + response.StatusCode.Should().Be(HttpStatusCode.Conflict); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + body.RootElement.GetProperty("code").GetString().Should().Be("business_rule_violation"); + var errors = body.RootElement.GetProperty("errors"); + errors.EnumerateObject().Select(property => property.Name).Should().Equal([field], "the reason is on the field it concerns, and only there"); + errors.GetProperty(field)[0].GetProperty("key").GetString().Should().Be(reason); + if (cause is not null) + { + errors.GetProperty(field)[0].GetProperty("params").GetProperty("cause").GetString().Should().Be(cause, + "the stored status that refused it, a closed code, is the reason's cause"); + } + } + + [Fact] + public async Task A_Completion_That_Names_No_Request_Is_Not_Found() + { + _dataRequests.Completion = new ErasureCompletionResult(ErasureCompletionOutcome.NotFound); + + var response = await Call(HttpMethod.Post, CompletePath, Valid(), "{}"); + + response.StatusCode.Should().Be(HttpStatusCode.NotFound); + await AssertProblem(response, "not_found"); + } + + [Theory] + [InlineData("/data-requests/not-a-guid/complete-erasure", HttpStatusCode.NotFound)] + [InlineData("/data-requests/00000000-0000-0000-0000-000000000000/complete-erasure", HttpStatusCode.BadRequest)] + [InlineData("/data-requests/00000000-0000-7000-8000-000000000002/complete-erasure", HttpStatusCode.BadRequest)] + [InlineData("/data-requests/4f9c5a3e-2b7d-4c1a-9e8f-0a1b2c3d4e5f/complete-erasure", HttpStatusCode.BadRequest)] + public async Task A_Completion_Naming_No_Real_Request_Is_Refused_Without_Calling_The_Owner(string suffix, HttpStatusCode expected) + { + // A request identifier that is not a UUID matches no route; the nil value, the platform sentinel and a version-4 + // identifier match it and are refused by the route's own check, after the gate. + var response = await Call(HttpMethod.Post, "/api/platform/v1" + suffix, Valid(), "{}"); + + response.StatusCode.Should().Be(expected); + _dataRequests.Calls.Should().BeEmpty(); + } + + [Fact] + public async Task A_Completion_Without_A_Body_Or_With_A_Bad_Ticket_Or_Media_Type_Is_Answered_Only_To_A_Granted_Operator() + { + (await Call(HttpMethod.Post, CompletePath, Valid())).StatusCode.Should().Be(HttpStatusCode.BadRequest); + (await Call(HttpMethod.Post, CompletePath, Valid(), """{"ticket":"has space"}""")).StatusCode.Should().Be(HttpStatusCode.BadRequest); + using var wrongType = new HttpRequestMessage(HttpMethod.Post, CompletePath) + { + Headers = { { "Authorization", "Bearer " + Valid() } }, + Content = new StringContent("{}", System.Text.Encoding.UTF8, "text/plain"), + }; + (await _client.SendAsync(wrongType)).StatusCode.Should().Be(HttpStatusCode.UnsupportedMediaType); + (await Call(HttpMethod.Post, CompletePath, Sign(("sub", "someone-else")), "not json")).StatusCode.Should().Be( + HttpStatusCode.Forbidden, "an operator without the grant learns nothing about the body"); + (await Call(HttpMethod.Post, CompletePath, "not-a-token", "{}")).StatusCode.Should().Be(HttpStatusCode.Unauthorized); + _dataRequests.Calls.Should().BeEmpty(); + } + + [Fact] + public async Task A_Completion_Whose_Audit_Or_Database_Failed_Or_Whose_Commit_Is_Unknown_Is_A_Retryable_503_With_Its_Own_Reason() + { + using var counted = Counted(); + foreach (var (failure, reason) in new (Exception, string)[] + { + (new AuditWriteFailedException("forced"), "audit_unavailable"), + (new OperatorRecoveryUnavailableException(cause: new TimeoutException("forced")), "dependency_unavailable"), + (new OperatorRecoveryUnavailableException(commitOutcomeUnknown: true, cause: new TimeoutException("forced")), "outcome_unknown"), + }) + { + _dataRequests.Failure = failure; + + var response = await Call(HttpMethod.Post, CompletePath, Valid(), "{}"); + + response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable, reason); + response.Headers.RetryAfter.Should().NotBeNull(reason); + var text = await response.Content.ReadAsStringAsync(); + text.Should().NotContain("forced"); + using var body = JsonDocument.Parse(text); + body.RootElement.GetProperty("status").GetInt32().Should().Be(503, reason); + body.RootElement.GetProperty("code").GetString().Should().Be(reason == "outcome_unknown" ? "dependency_unavailable" : reason); + body.RootElement.TryGetProperty("errors", out var errors).Should().Be(reason == "outcome_unknown", + "only a commit that may have landed names the unknown outcome: " + reason); + if (reason == "outcome_unknown") errors.GetProperty("outcome").ToString().Should().Contain("outcome_unknown"); + } + + counted.AuditFailures.Should().Be(1, "a refused audit write is a signal an alert can watch"); + _logs.Entries.Count(line => line.Id == 7110).Should().Be(2, "each unavailable owner logs its cause under its own event id"); + } + + [Theory] + [InlineData(DataRequestKey.None)] + [InlineData(DataRequestKey.Read)] + [InlineData(DataRequestKey.Write)] + public async Task The_Data_Request_Read_And_Write_Keys_Admit_Only_Their_Own_Routes_And_The_Other_Platform_Keys_Neither( + DataRequestKey held) + { + // ADR-0107 § 8: every other case here holds every key, so none can tell which key a route asks for. Each case holds + // exactly one, and None holds every other registered Platform key: none of them admits either route. + string[] keys = held switch + { + DataRequestKey.Read => [PlatformPermissions.DataRequestRead.Key], + DataRequestKey.Write => [PlatformPermissions.DataRequestWrite.Key], + _ => PlatformPermissions.All + .Where(key => key != PlatformPermissions.DataRequestRead && key != PlatformPermissions.DataRequestWrite) + .Select(key => key.Key).ToArray(), + }; + var operations = new RecordingDataRequests(); + await using var single = new PlatformOperatorApiFactory(_tenant, _operator, _toggle, grantSubject: Subject, + services: registrations => registrations.AddScoped(_ => operations), + permissions: keys); + using var client = single.CreateClient(); + + async Task Send(HttpMethod method, string path, string? json) + { + using var request = new HttpRequestMessage(method, path) { Headers = { { "Authorization", "Bearer " + Valid() } } }; + if (json is not null) request.Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"); + return (await client.SendAsync(request)).StatusCode; + } + + (await Send(HttpMethod.Get, DataRequests, null)).Should().Be(held == DataRequestKey.Read ? HttpStatusCode.OK : HttpStatusCode.Forbidden); + (await Send(HttpMethod.Post, CompletePath, "{}")).Should().Be(held == DataRequestKey.Write ? HttpStatusCode.OK : HttpStatusCode.Forbidden); + operations.Calls.Count.Should().Be(held == DataRequestKey.None ? 0 : 1); + } + + public enum DataRequestKey + { + None, + Read, + Write, + } + + [Fact] + public async Task The_Production_Composition_Resolves_The_Data_Request_Owner_Over_The_Platform_Scope() + { + // The doubles above replace the port, so this builds the host the way production does and asks for it: a + // registration that is missing or cannot be constructed would otherwise surface only on the first operator call. + await using var production = new PlatformOperatorApiFactory(_tenant, _operator, _toggle, grantSubject: Subject); + using var client = production.CreateClient(); + + using var scope = production.Services.CreateScope(); + scope.ServiceProvider.GetRequiredService() + .Should().BeOfType(); + } + + [Fact] + public async Task The_Served_Contract_Documents_The_Inspection_Lists_And_The_Completion_s_Refusals_And_Repeat() + { + using var document = JsonDocument.Parse(await _client.GetStringAsync("/openapi/platform-v1.json")); + var paths = document.RootElement.GetProperty("paths"); + + var inspect = paths.GetProperty(DataRequests).GetProperty("get"); + inspect.GetProperty("description").GetString().Should().Contain("stuck_fulfilling").And.Contain("2 hours") + .And.Contain("never the subject"); + var complete = paths.GetProperty("/api/platform/v1/data-requests/{requestId}/complete-erasure").GetProperty("post"); + complete.GetProperty("description").GetString().Should().Contain("already_completed").And.Contain("actor_user_id"); + complete.GetProperty("responses").GetProperty("409").GetProperty("description").GetString() + .Should().Contain("errors.kind").And.Contain("errors.origin").And.Contain("errors.status"); + document.RootElement.GetProperty("info").GetProperty("description").GetString().Should().Contain("data-erasure.md"); + } + private string Header(string alg, string typ) => JsonSerializer.Serialize(new { alg, typ, kid = _operator.CurrentKey.Kid }); // Correctly signed, with an algorithm the scheme does not allow: only the algorithm is wrong. @@ -1442,17 +1818,17 @@ public Task ToggleAsync( } } - /// Captures the operation and outcome labels of every federation call counted while it is alive. - private sealed class FederationListener : IDisposable + /// Captures the operation and outcome labels of every call one operator counter counts while it is alive. + private sealed class OperatorCounterListener : IDisposable { private readonly MeterListener _listener = new(); private readonly ConcurrentQueue<(string Operation, string Outcome)> _calls = new(); - public FederationListener() + public OperatorCounterListener(string counterName = PlatformOperatorMetrics.FederationCounterName) { _listener.InstrumentPublished = (instrument, listener) => { - if (instrument.Meter.Name == PlatformOperatorMetrics.MeterName && instrument.Name == PlatformOperatorMetrics.FederationCounterName) + if (instrument.Meter.Name == PlatformOperatorMetrics.MeterName && instrument.Name == counterName) { listener.EnableMeasurementEvents(instrument); } @@ -1575,6 +1951,39 @@ private sealed class RecordingInspection : IDeliveryInspection } } + private sealed class RecordingDataRequests : IDataRequestOperatorOperations + { + public List<(PlatformAdmission Admission, DataRequestInspectionQuery? Query, Guid? RequestId)> Calls { get; } = []; + public bool RefuseCursor { get; set; } + public Exception? Failure { get; set; } + public ErasureCompletionResult Completion { get; set; } = new( + ErasureCompletionOutcome.Completed, Guid.Parse(RowTenant), "completed", DateTimeOffset.UnixEpoch, + new Dictionary { ["audit_actor_reference"] = 4, ["consent_evidence"] = 1 }, + new AuditRedactionReport( + 7, new Dictionary { [AuditRedactedColumn.IpAddress] = 3 }, + [new RetainedReferenceCount(RetainedReferenceKind.AuditActorReference, 4)])); + + public Task?> InspectAsync( + PlatformAdmission admission, DataRequestInspectionQuery query, CancellationToken cancellationToken = default) + { + Calls.Add((admission, query, null)); + if (Failure is not null) return Task.FromException?>(Failure); + return Task.FromResult?>(RefuseCursor + ? null + : new InspectionPage( + [new DataRequestInspectionItem(Guid.Parse(ErasureRequest), Guid.Parse(RowTenant), null, "erasure", "self", + "awaiting_privileged_step", DateTimeOffset.UnixEpoch, DateTimeOffset.UnixEpoch.AddDays(1), null, null, null, null)], + "next-cursor")); + } + + public Task CompleteErasureAsync( + PlatformAdmission admission, Guid requestId, CancellationToken cancellationToken = default) + { + Calls.Add((admission, null, requestId)); + return Failure is not null ? Task.FromException(Failure) : Task.FromResult(Completion); + } + } + private sealed class PlatformOperatorApiFactory( TenantAuthenticationIssuer tenant, TenantAuthenticationIssuer @operator, @@ -1598,7 +2007,8 @@ protected override void ConfigureTestHost(IWebHostBuilder builder) [ PlatformPermissions.KillswitchWrite.Key, PlatformPermissions.DeliveryRead.Key, PlatformPermissions.DeliveryWrite.Key, PlatformPermissions.FederationRead.Key, - PlatformPermissions.FederationAdmin.Key, + PlatformPermissions.FederationAdmin.Key, PlatformPermissions.DataRequestRead.Key, + PlatformPermissions.DataRequestWrite.Key, ]; for (var index = 0; index < held.Length; index++) { diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/AccountRemovalProviderTests.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/AccountRemovalProviderTests.cs new file mode 100644 index 000000000..9b1a450a6 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/AccountRemovalProviderTests.cs @@ -0,0 +1,209 @@ +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Infrastructure.Identity.AccountRemoval; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Resilience; +using LearnStack.SharedKernel.Secrets; +using LearnStack.Tests.Integration.Database; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.IdentityModel.Tokens; +using Polly; +using Xunit; + +namespace LearnStack.Tests.Integration.TenancyIdentity; + +/// One owned provider for ADR-0107 § 7: the committed realm, with the account-removal client its import declares. +public sealed class AccountRemovalKeycloakFixture : IAsyncLifetime +{ + internal KeycloakFixture Keycloak { get; private set; } = null!; + + public async Task InitializeAsync() => Keycloak = await KeycloakFixture.StartAsync(); + + public async Task DisposeAsync() => await Keycloak.DisposeAsync(); +} + +/// +/// ADR-0107 § 7 real-provider controls: the confined adapter deletes a real Keycloak user through the committed realm's +/// account-removal client, and the client's authority is exactly what its role grants, no more and no less. Each case +/// carries its dirty control. +/// +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed class AccountRemovalProviderTests(AccountRemovalKeycloakFixture provider) : IClassFixture +{ + private KeycloakFixture Keycloak => provider.Keycloak; + + [Fact] + public async Task The_adapter_deletes_a_real_user_once_and_reports_absent_afterwards_without_touching_another_account() + { + using var admin = await Keycloak.CreateAdminClientAsync(); + var doomed = await CreateUserAsync(admin, "closing-person"); + var bystander = await CreateUserAsync(admin, "bystander-person"); + using var adapter = Adapter(); + + (await adapter.RemoveAsync(doomed)).Should().Be(AccountRemovalOutcome.Removed, + "the real client's token passes the adapter's narrowing and Keycloak accepts the deletion"); + await AssertGoneAsync(admin, doomed); + (await adapter.RemoveAsync(doomed)).Should().Be(AccountRemovalOutcome.Absent, "a missing account is success"); + (await admin.GetAsync("users/" + bystander)).GetProperty("id").GetString().Should().Be(bystander, + "dirty control: the deletion named one identifier and removed that account only"); + (await adapter.RemoveAsync(Guid.CreateVersion7().ToString("D"))).Should().Be(AccountRemovalOutcome.Absent, + "an identifier the provider never issued is absent"); + } + + [Fact] + public async Task Keycloaks_own_not_found_for_a_deletion_is_json_which_is_what_the_adapter_reads_as_absence() + { + // The adapter treats a 404 as absence only when it carries the provider's own JSON type (it never reads the body). That + // rule rests on this observation of the pinned image: a missing user, in any spelling of its identifier, is answered 404 + // with application/json. A proxy that hides the admin path answers in another type, and the unit cases plant it. + using var client = KeycloakHttp.Create(Keycloak.BaseAddress, Keycloak.RootCertificate); + var admin = AdminClient(await TokenAsync(client, "learnstack-account-removal", KeycloakFixture.AccountRemovalSecret)); + var unknown = Guid.CreateVersion7().ToString("D"); + + foreach (var path in new[] { "users/" + unknown, "users/" + unknown.ToUpperInvariant(), "users/not-a-uuid" }) + { + using var response = await KeycloakHttp.SendAsync(admin, HttpMethod.Delete, path); + response.StatusCode.Should().Be(HttpStatusCode.NotFound, path); + response.Content.Headers.ContentType?.MediaType.Should().Be("application/json", + "the provider's own not-found answer carries its JSON type: " + path); + (await KeycloakHttp.ReadBodyAsync(response)).Should().Contain("User not found"); + } + + // Dirty control: a path the provider does not route answers 404 as well, and also in JSON. The adapter never builds such a + // path (the architecture rules pin its two routes), so this is why the type alone is not asked to prove more than the + // deletion route's own answer, and why the runbook has the operator exercise that route after provisioning. + using var unrouted = await KeycloakHttp.SendAsync(admin, HttpMethod.Delete, "unrouted/" + unknown); + unrouted.StatusCode.Should().Be(HttpStatusCode.NotFound); + unrouted.Content.Headers.ContentType?.MediaType.Should().Be("application/json"); + + using var adapter = Adapter(); + (await adapter.RemoveAsync(unknown)).Should().Be(AccountRemovalOutcome.Absent); + } + + [Fact] + public async Task A_wrong_client_secret_is_refused_by_the_provider_and_changes_nothing() + { + using var admin = await Keycloak.CreateAdminClientAsync(); + var kept = await CreateUserAsync(admin, "kept-person"); + using var adapter = Adapter(secret: "a-secret-the-provider-never-issued"); + (await adapter.RemoveAsync(kept)).Should().Be(AccountRemovalOutcome.Refused); + (await admin.GetAsync("users/" + kept)).GetProperty("id").GetString().Should().Be(kept); + } + + [Fact] + public async Task The_client_token_carries_manage_users_alone_and_reaches_neither_federation_nor_client_administration() + { + using var client = KeycloakHttp.Create(Keycloak.BaseAddress, Keycloak.RootCertificate); + var access = await TokenAsync(client, "learnstack-account-removal", KeycloakFixture.AccountRemovalSecret); + using var payload = JsonDocument.Parse(Base64UrlEncoder.DecodeBytes(access.Split('.')[1])); + payload.RootElement.GetProperty("azp").GetString().Should().Be("learnstack-account-removal"); + payload.RootElement.GetProperty("resource_access").EnumerateObject().Select(value => value.Name).Should().Equal("realm-management"); + payload.RootElement.GetProperty("resource_access").GetProperty("realm-management").GetProperty("roles").EnumerateArray() + .Select(value => value.GetString()).Should().Equal("manage-users"); + (payload.RootElement.TryGetProperty("realm_access", out var realm) && realm.GetProperty("roles").GetArrayLength() != 0) + .Should().BeFalse("no realm role"); + var admin = AdminClient(access); + + // What manage-users does not reach: identity-provider brokers, clients and realm settings. + (await SendAsync(admin, HttpMethod.Get, "identity-provider/instances")).Should().Be(HttpStatusCode.Forbidden); + (await SendAsync(admin, HttpMethod.Get, "clients")).Should().Be(HttpStatusCode.Forbidden); + (await SendAsync(admin, HttpMethod.Put, "", JsonContent.Create(new { realm = "learnstack" }))).Should().Be(HttpStatusCode.Forbidden); + (await SendAsync(admin, HttpMethod.Get, "authentication/flows")).Should().Be(HttpStatusCode.Forbidden); + } + + [Fact] + public async Task The_client_can_also_create_update_and_reset_credentials_which_is_why_the_runbook_names_its_blast_radius() + { + // The accepted risk of ADR-0107 § 7, shown rather than asserted: manage-users is not deletion-only. + using var client = KeycloakHttp.Create(Keycloak.BaseAddress, Keycloak.RootCertificate); + var admin = AdminClient(await TokenAsync(client, "learnstack-account-removal", KeycloakFixture.AccountRemovalSecret)); + using var create = await KeycloakHttp.SendAsync(admin, HttpMethod.Post, "users", JsonContent.Create(new + { + username = "created-by-the-removal-client", + enabled = true, + email = "created@removal.test", + emailVerified = true, + })); + create.StatusCode.Should().Be(HttpStatusCode.Created, "manage-users creates users in the shared realm"); + var id = create.Headers.Location!.AbsolutePath.Split('/').Last(); + (await SendAsync(admin, HttpMethod.Put, "users/" + id + "/reset-password", + JsonContent.Create(new { type = "password", value = "an-attacker-chosen-password-1", temporary = false }))) + .Should().Be(HttpStatusCode.NoContent, "and resets credentials"); + (await SendAsync(admin, HttpMethod.Put, "users/" + id, JsonContent.Create(new { enabled = false }))) + .Should().Be(HttpStatusCode.NoContent, "and updates them"); + using var adapter = Adapter(); + (await adapter.RemoveAsync(id)).Should().Be(AccountRemovalOutcome.Removed, "the adapter cleans up what the control created"); + } + + [Fact] + public async Task The_federation_client_cannot_delete_a_user_so_the_two_confined_clients_do_not_overlap() + { + using var admin = await Keycloak.CreateAdminClientAsync(); + var user = await CreateUserAsync(admin, "federation-cannot-delete"); + using var client = KeycloakHttp.Create(Keycloak.BaseAddress, Keycloak.RootCertificate); + var federation = AdminClient(await TokenAsync(client, "learnstack-federation-admin", KeycloakFixture.FederationAdminSecret)); + (await SendAsync(federation, HttpMethod.Delete, "users/" + user)).Should().Be(HttpStatusCode.Forbidden); + (await admin.GetAsync("users/" + user)).GetProperty("id").GetString().Should().Be(user, "nothing was deleted"); + // Dirty control: the removal client's own deletion of the same account succeeds. + using var adapter = Adapter(); + (await adapter.RemoveAsync(user)).Should().Be(AccountRemovalOutcome.Removed); + } + + private KeycloakAccountRemoval Adapter(string secret = KeycloakFixture.AccountRemovalSecret) => + new(new KeycloakAccountRemovalOptions(Keycloak.Issuer), new Secrets(secret), new Resilience(), NullLogger.Instance, + KeycloakHttp.CreateHandler(Keycloak.RootCertificate)); + + private HttpClient AdminClient(string access) + { + var client = KeycloakHttp.Create(new Uri(Keycloak.BaseAddress, "admin/realms/learnstack/"), Keycloak.RootCertificate); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", access); + return client; + } + + private static async Task SendAsync(HttpClient client, HttpMethod method, string path, HttpContent? content = null) + { + using var response = await KeycloakHttp.SendAsync(client, method, path, content); + return response.StatusCode; + } + + private static async Task TokenAsync(HttpClient client, string clientId, string secret) + { + using var issued = await KeycloakHttp.JsonAsync(client, HttpMethod.Post, "realms/learnstack/protocol/openid-connect/token", + new FormUrlEncodedContent(new Dictionary + { + ["grant_type"] = "client_credentials", + ["client_id"] = clientId, + ["client_secret"] = secret, + })); + return issued.RootElement.GetProperty("access_token").GetString()!; + } + + private static async Task CreateUserAsync(KeycloakAdminClient admin, string username) + { + // The realm uses the e-mail address as the user name, so the name the provider stores is the address. + var address = username + "@removal.test"; + (await admin.PostAsync("users", new { username = address, enabled = true, email = address, emailVerified = true })) + .Should().Be(HttpStatusCode.Created); + return (await admin.UserAsync(address)).GetProperty("id").GetString()!; + } + + private static async Task AssertGoneAsync(KeycloakAdminClient admin, string id) + { + var act = () => admin.GetAsync("users/" + id); + await act.Should().ThrowAsync("the provider answers 404 for a deleted user"); + } + + private sealed class Secrets(string value) : ISecretProvider + { + public string? GetSecret(string key) => key == "AccountRemoval:ClientSecret" ? value : null; + } + + private sealed class Resilience : IProviderResilience + { + public ResiliencePipeline Pipeline => ResiliencePipeline.Empty; + public string PortName => "accountRemoval"; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakFixture.Federation.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakFixture.Federation.cs index 55cd0e307..e7ba14df8 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakFixture.Federation.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakFixture.Federation.cs @@ -149,8 +149,8 @@ private async Task CreateRealmAsync(JsonObject realm) } /// - /// The committed export as it stood before P03-8 Step 3, for warm-upgrade proofs: no federation admin client or its - /// service account, no link-only first-broker flow or declared required actions (so idp_link is the stock enabled + /// The committed export as it stood before P03-8 Step 3, for warm-upgrade proofs: no federation admin or account-removal + /// client or their service accounts, no link-only first-broker flow or declared required actions (so idp_link is the stock enabled /// action), no idp mapper, and the stock account self-service (enabled console, manage-account in the default role and /// on each persona). /// @@ -158,6 +158,8 @@ internal static void ToPreStepThree(JsonObject realm) { var clients = realm["clients"]!.AsArray(); clients.Remove(clients.Single(client => client!["clientId"]!.GetValue() == "learnstack-federation-admin")); + // ADR-0107 § 7 added the account-removal client later still: the pre-Step-3 realm has neither machine client. + clients.Remove(clients.Single(client => client!["clientId"]!.GetValue() == "learnstack-account-removal")); foreach (var client in clients) { var name = client!["clientId"]!.GetValue(); diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakFixture.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakFixture.cs index a3747579a..3c24df599 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakFixture.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/KeycloakFixture.cs @@ -22,6 +22,7 @@ public sealed partial class KeycloakFixture : IAsyncLifetime, IAsyncDisposable internal const string WebClientSecret = "keycloak-fixture-web-secret"; internal const string EventReaderSecret = "keycloak-fixture-event-reader-secret"; internal const string FederationAdminSecret = "keycloak-fixture-federation-admin-secret"; + internal const string AccountRemovalSecret = "keycloak-fixture-account-removal-secret"; internal const string DemoPassword = "demo-dev-secret"; private const string AdminUsername = "fixture-admin"; private readonly string _adminPassword = Guid.NewGuid().ToString("N"); @@ -176,6 +177,7 @@ private IContainer BuildProvider(string tenantImport, byte[] hubImport, bool cal .WithEnvironment("KC_BOOTSTRAP_ADMIN_PASSWORD", _adminPassword) .WithEnvironment("KEYCLOAK_WEB_CLIENT_SECRET", WebClientSecret) .WithEnvironment("KEYCLOAK_FEDERATION_ADMIN_SECRET", FederationAdminSecret) + .WithEnvironment("KEYCLOAK_ACCOUNT_REMOVAL_SECRET", AccountRemovalSecret) // byte[] destinations are files. Testcontainers' string/string overload treats the target as a directory. .WithResourceMapping(Encoding.UTF8.GetBytes(tenantImport), "/opt/keycloak/data/import/learnstack-realm.json") .WithResourceMapping(hubImport, "/opt/keycloak/data/import/learnstack-hub-realm.json") @@ -311,6 +313,7 @@ internal async Task WriteReconciliationInputAsync(Stream destination, string sce adminPassword = _adminPassword, webSecret = WebClientSecret, federationSecret = FederationAdminSecret, + accountRemovalSecret = AccountRemovalSecret, manifest = SeedIdentityManifest.Create(), desired = desired.RootElement, ca = RootCertificate.ExportCertificatePem(), diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantBffSessionTests.Pages.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantBffSessionTests.Pages.cs index 5cdf98fc3..9475dfe24 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantBffSessionTests.Pages.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantBffSessionTests.Pages.cs @@ -24,7 +24,8 @@ private static async Task AssertSelectedNativePagesAsync(IdentityPublicReadFixtu ("/studio/members", [("identity.membership.list", "Membership", null)]), ("/studio/members/" + memberId, [("identity.membership.read", "Membership", memberId), - ("identity.membership.custom_fields_read", "Membership", memberId), ("identity.role.list", "Role", null)]), + ("identity.membership.custom_fields_read", "Membership", memberId), ("identity.role.list", "Role", null), + ("identity.data_request.list", "DataSubjectRequest", null)]), ("/studio/roles", [("identity.role.list", "Role", null)]), ("/studio/roles/" + roleId, [("identity.role.read", "Role", roleId), ("identity.role.list_permissions", "Role", null)]), @@ -75,7 +76,7 @@ private static async Task AssertSelectedNativePagesAsync(IdentityPublicReadFixtu } var afterAudit = await AuditCountsAsync(database); afterAudit.Where((count, index) => count != beforeAudit[index] - + (SeedData.All[index] == identity.Tenant ? 7 : 0)).Any().Should().BeFalse(); + + (SeedData.All[index] == identity.Tenant ? 8 : 0)).Any().Should().BeFalse(); } private static async Task> SelectedPageAuditsAsync( diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantBffSessionTests.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantBffSessionTests.cs index df1857e97..300d030de 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantBffSessionTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantBffSessionTests.cs @@ -421,6 +421,9 @@ public async Task Reconciled_warm_realm_serves_both_native_hosts_with_real_refre extended.GetProperty("expiresAt").GetDouble().Should().BeGreaterThan(session.GetProperty("expiresAt").GetDouble(), "an explicit fresh-access extension must actually renew provider idle"); var otherAccount = SeedData.IdentityUsers.First(person => person.Tenant != tenant); + // The selected member page also reads the group's data requests, one more call + // under the same 60/min budget, so the first window ends before this journey. + await NextAnonymousWindowAsync(anonymousWindow); await AssertDifferentProviderAccountCannotReplaceLiveDestinationAsync(provider, native, api, identity, otherAccount, passwords.GetValueOrDefault(otherAccount.Username) ?? KeycloakFixture.DemoPassword, cookies, extended, database); @@ -581,8 +584,8 @@ await AssertLearnerMembershipRevocationAsync(database, provider, admin, native, "the actual BFF journey persists provider event type {0}", type); } (await AuditCountsAsync(database)).Should().Equal(SeedData.All.Select((site, index) => - auditBefore[index] + 12 + (site.MapHostToDefaultOrganization ? 0 : 1)), - "NULL-org administrator selections, seven selected-page read events and original profile write/receipt emit MUST events; learner admission follows its exact scope and pre-resolution revocation creates no invented policy event"); + auditBefore[index] + 13 + (site.MapHostToDefaultOrganization ? 0 : 1)), + "NULL-org administrator selections, eight selected-page read events and original profile write/receipt emit MUST events; learner admission follows its exact scope and pre-resolution revocation creates no invented policy event"); output.WriteLine("Real warm BFF proof: hosts=2; real refresh/maximum/logout/error/events/membership-revocation=true; zero-write rerun=true; fixture={0:F3}s; journey={1:F3}s.", provider.StartupElapsed.TotalSeconds, journey.Elapsed.TotalSeconds); } diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantRealmApiTests.WarmQualification.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantRealmApiTests.WarmQualification.cs index ef6143ee1..6f5d407d2 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantRealmApiTests.WarmQualification.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantRealmApiTests.WarmQualification.cs @@ -93,8 +93,8 @@ public async Task Historical_automatic_upgrade_preserves_live_password_and_MFA_t var first = await KeycloakReconciliationDriver.RunAsync(warm); first.Success.Should().BeTrue("closed historical reconciliation outcome: {0}/{1}", first.Stage, first.Reason); first.PreparationDispatched.Should().BeTrue(); - first.Mutations.Should().Be(39, "one preparation, sixteen prior ordinary writes, one event-policy PUT and the additional native scope creation; " - + "plus eighteen ADR-0099 writes (twenty-one federation-invariant writes and three console-retirement edges, less the retired console normalization and grant), plus the two ADR-0099 Amendment 6 writes (the test-record scope and its optional attachment)"); + first.Mutations.Should().Be(44, "one preparation, sixteen prior ordinary writes, one event-policy PUT and the additional native scope creation; " + + "plus eighteen ADR-0099 writes (twenty-one federation-invariant writes and three console-retirement edges, less the retired console normalization and grant), plus the two ADR-0099 Amendment 6 writes (the test-record scope and its optional attachment), plus the five ADR-0107 § 7 writes that create the account-removal client (the client, its automatic scope detach, its default-role detach, its role grant and its scope allowance)"); output.WriteLine("Historical journey stage: automatic reconciliation completed."); var accountsAfter = await WarmAccountsAsync(admin, usernames); WarmSame(expectedProfile, WarmNode(await admin.GetAsync("users/profile"))).Should().BeTrue( @@ -330,7 +330,8 @@ private static async Task WarmAssertGraphAsync(KeycloakAdminClient admin, Dictio oldIds.IsSubsetOf(currentIds).Should().BeTrue("no preexisting client or scope is deleted or recreated"); if (path == "clients") current.EnumerateArray().Where(client => !oldIds.Contains(WarmId(client))).Select(client => client.GetProperty("clientId").GetString()) - .Should().Equal(["learnstack-federation-admin"], "the only new client is ADR-0099's federation admin client"); + .Order(StringComparer.Ordinal).Should().Equal(["learnstack-account-removal", "learnstack-federation-admin"], + "the only new clients are ADR-0099's federation admin client and ADR-0107's account-removal client"); else current.EnumerateArray().Where(scope => !oldIds.Contains(WarmId(scope))) .Select(scope => scope.GetProperty("name").GetString()).Order(StringComparer.Ordinal) .Should().Equal(desired["clientScopes"]!.AsArray().Select(scope => scope!["name"]!.GetValue()) diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantRealmExportTests.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantRealmExportTests.cs index c76c54b0f..5bc0316a1 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantRealmExportTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantRealmExportTests.cs @@ -120,8 +120,19 @@ public void Export_controls_reject_unsafe_mapper_profile_client_and_identity_var ("federation browser flow", realm => Client(realm, "learnstack-federation-admin")["standardFlowEnabled"] = true), ("federation default scope", realm => Client(realm, "learnstack-federation-admin")["defaultClientScopes"]!.AsArray().Add("roles")), ("federation extra role", realm => FederationUser(realm)["clientRoles"]!["realm-management"]!.AsArray().Add("manage-users")), - ("federation extra scope role", realm => realm["clientScopeMappings"]!["realm-management"]![0]!["roles"]!.AsArray().Add("manage-users")), + ("federation extra scope role", realm => ScopeAllowance(realm, "learnstack-federation-admin")["roles"]!.AsArray().Add("manage-users")), ("federation password", realm => FederationUser(realm)["credentials"] = new JsonArray()), + ("missing account removal client", realm => realm["clients"]!.AsArray().Remove(Client(realm, "learnstack-account-removal"))), + ("literal account removal secret", realm => Client(realm, "learnstack-account-removal")["secret"] = "unowned-removal-source"), + ("account removal sharing the federation secret", realm => Client(realm, "learnstack-account-removal")["secret"] = "${KEYCLOAK_FEDERATION_ADMIN_SECRET}"), + ("account removal full scope", realm => Client(realm, "learnstack-account-removal")["fullScopeAllowed"] = true), + ("account removal browser flow", realm => Client(realm, "learnstack-account-removal")["standardFlowEnabled"] = true), + ("account removal default scope", realm => Client(realm, "learnstack-account-removal")["defaultClientScopes"]!.AsArray().Add("roles")), + ("account removal federation role", realm => ServiceUser(realm, "learnstack-account-removal")["clientRoles"]!["realm-management"]!.AsArray().Add("manage-identity-providers")), + ("account removal realm admin role", realm => ServiceUser(realm, "learnstack-account-removal")["clientRoles"]!["realm-management"]!.AsArray().Add("realm-admin")), + ("account removal extra scope role", realm => ScopeAllowance(realm, "learnstack-account-removal")["roles"]!.AsArray().Add("view-users")), + ("account removal password", realm => ServiceUser(realm, "learnstack-account-removal")["credentials"] = new JsonArray()), + ("federation holding the removal role", realm => ServiceUser(realm, "learnstack-federation-admin")["clientRoles"]!["realm-management"] = new JsonArray("manage-users")), ("enabled idp_link", realm => RequiredAction(realm, "idp_link")["enabled"] = true), ("missing stock required action", realm => realm["requiredActions"]!.AsArray().Remove(RequiredAction(realm, "UPDATE_PASSWORD"))), ("missing first broker flow", realm => realm["authenticationFlows"]!.AsArray().Remove(Flow(realm, "learnstack-first-broker-login"))), @@ -432,26 +443,13 @@ private static void ValidateAccountDeclaration(JsonObject realm, ActionADR-0099 § Realm invariants as the committed export declares them. private static void ValidateFederationDeclaration(JsonObject realm, Action require) { - var client = Client(realm, "learnstack-federation-admin"); - require(client["enabled"]!.GetValue() && !client["publicClient"]!.GetValue() && !client["bearerOnly"]!.GetValue() - && client["serviceAccountsEnabled"]!.GetValue() && !client["standardFlowEnabled"]!.GetValue() - && !client["implicitFlowEnabled"]!.GetValue() && !client["directAccessGrantsEnabled"]!.GetValue() - && !client["fullScopeAllowed"]!.GetValue() && Strings(client["redirectUris"]).Length == 0 - && Strings(client["webOrigins"]).Length == 0 && Strings(client["defaultClientScopes"]).Length == 0 - && Strings(client["optionalClientScopes"]).Length == 0, "federation admin machine client modes"); - require(Text(client["secret"]) == "${KEYCLOAK_FEDERATION_ADMIN_SECRET}", "federation secret placeholder only"); - var mappers = client["protocolMappers"]!.AsArray(); - require(mappers.Count == 1 && Text(mappers[0]?["protocolMapper"]) == "oidc-usermodel-client-role-mapper" - && Text(mappers[0]?["config"]?["usermodel.clientRoleMapping.clientId"]) == "realm-management" - && Text(mappers[0]?["config"]?["id.token.claim"]) == "false", "one admin-role emitter"); + ValidateMachineClient(realm, "learnstack-federation-admin", "${KEYCLOAK_FEDERATION_ADMIN_SECRET}", "manage-identity-providers", require); + // ADR-0107 § 7: the closure's account-removal client has the same shape and its own, different, role. + ValidateMachineClient(realm, "learnstack-account-removal", "${KEYCLOAK_ACCOUNT_REMOVAL_SECRET}", "manage-users", require); var serviceAccounts = realm["users"]!.AsArray().Where(user => user?["serviceAccountClientId"] is not null).ToArray(); - var user = FederationUser(realm); - require(serviceAccounts.Length == 1 && user["credentials"] is null && user["realmRoles"] is null - && user["clientRoles"]!.AsObject().Count == 1 - && Strings(user["clientRoles"]!["realm-management"]).SequenceEqual(["manage-identity-providers"]), "manage-identity-providers only"); + require(serviceAccounts.Length == 2, "exactly the federation and account-removal service accounts"); var allowance = realm["clientScopeMappings"]!["realm-management"]!.AsArray(); - require(allowance.Count == 1 && Text(allowance[0]?["client"]) == "learnstack-federation-admin" - && Strings(allowance[0]?["roles"]).SequenceEqual(["manage-identity-providers"]), "admin role scope only"); + require(allowance.Count == 2, "exactly two admin role scope allowances"); var actions = realm["requiredActions"]!.AsArray(); require(actions.Count == 14 && actions.All(action => Text(action?["alias"]) == Text(action?["providerId"])), "complete stock required actions"); require(!RequiredAction(realm, "idp_link")["enabled"]!.GetValue(), "idp_link application action disabled"); @@ -487,8 +485,34 @@ static string Step(JsonNode? step) => step?["authenticatorFlow"]!.GetValue "idp ID-token claim from the session note only"); } - private static JsonObject FederationUser(JsonObject realm) => realm["users"]!.AsArray() - .Single(user => Text(user?["serviceAccountClientId"]) == "learnstack-federation-admin")!.AsObject(); + private static JsonObject FederationUser(JsonObject realm) => ServiceUser(realm, "learnstack-federation-admin"); + private static JsonObject ServiceUser(JsonObject realm, string clientId) => realm["users"]!.AsArray() + .Single(user => Text(user?["serviceAccountClientId"]) == clientId)!.AsObject(); + /// One confined realm-management service client: machine modes, a placeholder secret, one role emitter and one role. + private static void ValidateMachineClient(JsonObject realm, string clientId, string placeholder, string role, Action require) + { + var client = Client(realm, clientId); + require(client["enabled"]!.GetValue() && !client["publicClient"]!.GetValue() && !client["bearerOnly"]!.GetValue() + && client["serviceAccountsEnabled"]!.GetValue() && !client["standardFlowEnabled"]!.GetValue() + && !client["implicitFlowEnabled"]!.GetValue() && !client["directAccessGrantsEnabled"]!.GetValue() + && !client["fullScopeAllowed"]!.GetValue() && Strings(client["redirectUris"]).Length == 0 + && Strings(client["webOrigins"]).Length == 0 && Strings(client["defaultClientScopes"]).Length == 0 + && Strings(client["optionalClientScopes"]).Length == 0, clientId + " machine client modes"); + require(Text(client["secret"]) == placeholder, clientId + " secret placeholder only"); + var mappers = client["protocolMappers"]!.AsArray(); + require(mappers.Count == 1 && Text(mappers[0]?["protocolMapper"]) == "oidc-usermodel-client-role-mapper" + && Text(mappers[0]?["config"]?["usermodel.clientRoleMapping.clientId"]) == "realm-management" + && Text(mappers[0]?["config"]?["id.token.claim"]) == "false", clientId + " one admin-role emitter"); + var user = ServiceUser(realm, clientId); + require(user["credentials"] is null && user["realmRoles"] is null && user["clientRoles"]!.AsObject().Count == 1 + && Strings(user["clientRoles"]!["realm-management"]).SequenceEqual([role]), clientId + " holds " + role + " only"); + var allowance = ScopeAllowance(realm, clientId); + require(Strings(allowance["roles"]).SequenceEqual([role]), clientId + " admin role scope only"); + } + + private static JsonObject ScopeAllowance(JsonObject realm, string clientId) => realm["clientScopeMappings"]!["realm-management"]!.AsArray() + .Single(entry => Text(entry?["client"]) == clientId)!.AsObject(); + private static JsonObject RequiredAction(JsonObject realm, string alias) => realm["requiredActions"]!.AsArray() .Single(action => Text(action?["alias"]) == alias)!.AsObject(); private static JsonObject Flow(JsonObject realm, string alias) => realm["authenticationFlows"]!.AsArray() diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantRealmFederationReconciliationTests.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantRealmFederationReconciliationTests.cs index 70e91ca04..5c7267df1 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantRealmFederationReconciliationTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantRealmFederationReconciliationTests.cs @@ -38,6 +38,7 @@ public async Task A_pre_step_three_realm_converges_to_every_federation_invariant using var admin = await fixture.CreateAdminClientAsync(); // Dirty control: the warm realm really lacks the invariants before reconciliation. (await admin.GetAsync("clients?clientId=learnstack-federation-admin")).GetArrayLength().Should().Be(0); + (await admin.GetAsync("clients?clientId=learnstack-account-removal")).GetArrayLength().Should().Be(0); (await admin.GetAsync("authentication/required-actions/idp_link")).GetProperty("enabled").GetBoolean().Should().BeTrue(); (await admin.ClientAsync("account-console")).GetProperty("enabled").GetBoolean().Should().BeTrue(); var persona = await admin.UserAsync(SeedData.IdentityUsers[0].Username); @@ -85,38 +86,64 @@ public async Task An_existing_federation_secret_mismatch_refuses_rather_than_rot .Should().Be(rotated, "the reconciler never rotates an existing secret"); } - private static async Task AssertInvariantsAsync(KeycloakFixture fixture, KeycloakAdminClient admin) + [Fact] + public async Task An_existing_account_removal_secret_mismatch_refuses_rather_than_rotating() { - // (1) the federation admin client holds manage-identity-providers only. - var client = await admin.ClientAsync("learnstack-federation-admin"); + await using var fixture = await KeycloakFixture.StartAsync(); + using var admin = await fixture.CreateAdminClientAsync(); + var client = await admin.ClientAsync("learnstack-account-removal"); + (await admin.PostAsync("clients/" + client.GetProperty("id").GetString() + "/client-secret", new { })) + .Should().Be(HttpStatusCode.OK); + var rotated = (await admin.GetAsync("clients/" + client.GetProperty("id").GetString() + "/client-secret")).GetProperty("value").GetString(); + rotated.Should().NotBe(KeycloakFixture.AccountRemovalSecret); + var result = await KeycloakReconciliationDriver.RunAsync(fixture); + result.Success.Should().BeFalse(); + result.Stage.Should().Be("plan"); + result.Reason.Should().Be("secret_conflict"); + result.Mutations.Should().Be(0); + (await admin.GetAsync("clients/" + client.GetProperty("id").GetString() + "/client-secret")).GetProperty("value").GetString() + .Should().Be(rotated, "the reconciler never rotates an existing secret"); + } + + private static async Task AssertMachineClientAsync(KeycloakFixture fixture, KeycloakAdminClient admin, string clientId, string secret, string role) + { + var client = await admin.ClientAsync(clientId); var id = client.GetProperty("id").GetString(); client.GetProperty("fullScopeAllowed").GetBoolean().Should().BeFalse(); client.GetProperty("standardFlowEnabled").GetBoolean().Should().BeFalse(); client.GetProperty("implicitFlowEnabled").GetBoolean().Should().BeFalse(); client.GetProperty("directAccessGrantsEnabled").GetBoolean().Should().BeFalse(); - (await admin.GetAsync("clients/" + id + "/client-secret")).GetProperty("value").GetString().Should().Be(KeycloakFixture.FederationAdminSecret); + (await admin.GetAsync("clients/" + id + "/client-secret")).GetProperty("value").GetString().Should().Be(secret); var user = await admin.GetAsync("clients/" + id + "/service-account-user"); var roles = await admin.GetAsync("users/" + user.GetProperty("id").GetString() + "/role-mappings"); (!roles.TryGetProperty("realmMappings", out var realmRoles) || realmRoles.GetArrayLength() == 0).Should().BeTrue("no realm role"); var management = roles.GetProperty("clientMappings").EnumerateObject().Should().ContainSingle().Subject; management.Name.Should().Be("realm-management"); - management.Value.GetProperty("mappings").EnumerateArray().Select(role => role.GetProperty("name").GetString()) - .Should().Equal("manage-identity-providers"); + management.Value.GetProperty("mappings").EnumerateArray().Select(granted => granted.GetProperty("name").GetString()) + .Should().Equal(role); using (var token = KeycloakHttp.Create(fixture.BaseAddress, fixture.RootCertificate)) { using var issued = await KeycloakHttp.JsonAsync(token, HttpMethod.Post, "realms/learnstack/protocol/openid-connect/token", new FormUrlEncodedContent(new Dictionary { ["grant_type"] = "client_credentials", - ["client_id"] = "learnstack-federation-admin", - ["client_secret"] = KeycloakFixture.FederationAdminSecret, + ["client_id"] = clientId, + ["client_secret"] = secret, })); var access = issued.RootElement.GetProperty("access_token").GetString()!; using var payload = JsonDocument.Parse(Microsoft.IdentityModel.Tokens.Base64UrlEncoder.DecodeBytes(access.Split('.')[1])); payload.RootElement.GetProperty("resource_access").EnumerateObject().Select(value => value.Name).Should().Equal("realm-management"); payload.RootElement.GetProperty("resource_access").GetProperty("realm-management").GetProperty("roles").EnumerateArray() - .Select(value => value.GetString()).Should().Equal("manage-identity-providers"); + .Select(value => value.GetString()).Should().Equal(role); } + } + + private static async Task AssertInvariantsAsync(KeycloakFixture fixture, KeycloakAdminClient admin) + { + // (1) each confined machine client holds its one realm-management role only. + await AssertMachineClientAsync(fixture, admin, "learnstack-federation-admin", KeycloakFixture.FederationAdminSecret, "manage-identity-providers"); + // ADR-0107 § 7: the closure's account-removal client, manage-users only. + await AssertMachineClientAsync(fixture, admin, "learnstack-account-removal", KeycloakFixture.AccountRemovalSecret, "manage-users"); // (2) the link-only first-broker flow, exactly. var executions = await admin.GetAsync("authentication/flows/learnstack-first-broker-login/executions"); executions.EnumerateArray().Select(execution => execution.GetProperty("level").GetInt32() + ":" diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantRealmReconciliationTests.Preparation.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantRealmReconciliationTests.Preparation.cs index 137144d17..50fc22f29 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantRealmReconciliationTests.Preparation.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantRealmReconciliationTests.Preparation.cs @@ -38,7 +38,7 @@ public Task Historical_stock_upgrade_prepares_once_and_counts_the_named_event_po var first = await KeycloakReconciliationDriver.RunAsync(fixture); first.Success.Should().BeTrue("the automatic historical path reports {0}/{1}", first.Stage, first.Reason); first.PreparationDispatched.Should().BeTrue(); - first.Mutations.Should().Be(39, "one preparation, sixteen prior stock-upgrade writes, one event-policy PUT and the additional native scope; plus eighteen ADR-0099 writes (twenty-one federation-invariant writes and three console-retirement edges, less the retired console normalization and grant), plus the two ADR-0099 Amendment 6 writes (the test-record scope and its optional attachment)"); + first.Mutations.Should().Be(44, "one preparation, sixteen prior stock-upgrade writes, one event-policy PUT and the additional native scope; plus eighteen ADR-0099 writes (twenty-one federation-invariant writes and three console-retirement edges, less the retired console normalization and grant), plus the two ADR-0099 Amendment 6 writes (the test-record scope and its optional attachment), plus the five ADR-0107 § 7 writes that create the account-removal client (the client, its automatic scope detach, its default-role detach, its role grant and its scope allowance)"); AssertPreparationProfile(expectedProfile, await admin.GetAsync("users/profile")); foreach (var identity in SeedData.IdentityUsers) await AssertStoredIdentityAsync(admin, identity); foreach (var (username, original) in originalUsers) @@ -54,7 +54,8 @@ public Task Historical_stock_upgrade_prepares_once_and_counts_the_named_event_po var priorClients = clientsBefore.EnumerateArray().Select(Id).ToHashSet(StringComparer.Ordinal); priorClients.IsSubsetOf(clientsAfter.EnumerateArray().Select(Id)).Should().BeTrue("all existing clients retain their provider IDs"); clientsAfter.EnumerateArray().Where(client => !priorClients.Contains(Id(client))).Select(client => client.GetProperty("clientId").GetString()) - .Should().Equal(["learnstack-federation-admin"], "the only new client is ADR-0099's federation admin client"); + .Order(StringComparer.Ordinal).Should().Equal(["learnstack-account-removal", "learnstack-federation-admin"], + "the only new clients are ADR-0099's federation admin client and ADR-0107's account-removal client"); foreach (var (path, before) in scopesBefore) AssertSame(before, await admin.GetAsync(path), "preparation and normalization preserve each preexisting global scope definition"); AssertSame(apiSecret, await admin.GetAsync("clients/" + Id(api) + "/client-secret"), "the API credential survives the automatic path"); @@ -148,7 +149,7 @@ public Task Interrupted_historical_preparation_counts_the_dispatched_write_and_r var resumed = await KeycloakReconciliationDriver.RunAsync(fixture); resumed.Success.Should().BeTrue("an explicit fresh invocation reports {0}/{1}", resumed.Stage, resumed.Reason); - resumed.Mutations.Should().Be(38, "the durable preparation is reused; sixteen prior stock writes, one event-policy PUT and the additional native scope remain; plus eighteen ADR-0099 writes (twenty-one federation-invariant writes and three console-retirement edges, less the retired console normalization and grant), plus the two ADR-0099 Amendment 6 writes (the test-record scope and its optional attachment)"); + resumed.Mutations.Should().Be(43, "the durable preparation is reused; sixteen prior stock writes, one event-policy PUT and the additional native scope remain; plus eighteen ADR-0099 writes (twenty-one federation-invariant writes and three console-retirement edges, less the retired console normalization and grant), plus the two ADR-0099 Amendment 6 writes (the test-record scope and its optional attachment), plus the five ADR-0107 § 7 writes that create the account-removal client (the client, its automatic scope detach, its default-role detach, its role grant and its scope allowance)"); resumed.PreparationDispatched.Should().BeFalse(); var completed = await KeycloakReconciliationDriver.RunAsync(fixture); completed.Success.Should().BeTrue(); @@ -184,8 +185,8 @@ public Task Partial_admin_view_only_definition_is_preserved_by_preparation_then_ var resumed = await KeycloakReconciliationDriver.RunAsync(fixture); resumed.Success.Should().BeTrue("the separate ordinary plan reports {0}/{1}", resumed.Stage, resumed.Reason); resumed.PreparationDispatched.Should().BeFalse(); - resumed.Mutations.Should().Be(39, "sixteen prior stock writes, separate profile normalization, one event-policy PUT and the additional native scope; " - + "plus eighteen ADR-0099 writes (twenty-one federation-invariant writes and three console-retirement edges, less the retired console normalization and grant), plus the two ADR-0099 Amendment 6 writes (the test-record scope and its optional attachment)"); + resumed.Mutations.Should().Be(44, "sixteen prior stock writes, separate profile normalization, one event-policy PUT and the additional native scope; " + + "plus eighteen ADR-0099 writes (twenty-one federation-invariant writes and three console-retirement edges, less the retired console normalization and grant), plus the two ADR-0099 Amendment 6 writes (the test-record scope and its optional attachment), plus the five ADR-0107 § 7 writes that create the account-removal client (the client, its automatic scope detach, its default-role detach, its role grant and its scope allowance)"); var expectedFinal = expectedPreparation.DeepClone(); var definitions = expectedFinal["attributes"]!.AsArray(); var index = definitions.IndexOf(definitions.Single(value => value!["name"]!.GetValue() == "user_id")); diff --git a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantRealmStockBaselineTests.cs b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantRealmStockBaselineTests.cs index 299782299..35ef8d426 100644 --- a/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantRealmStockBaselineTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/TenancyIdentity/TenantRealmStockBaselineTests.cs @@ -171,8 +171,8 @@ public async Task Historical_stock_ordinary_reconciliation_retires_the_console_a var first = await KeycloakReconciliationDriver.RunAsync(fixture); first.Success.Should().BeTrue("closed ordinary reconciliation outcome: {0}/{1} after {2} writes", first.Stage, first.Reason, first.Mutations); - first.Mutations.Should().Be(38, "thirteen prior approved mutations, three console assignment DELETEs, one ADR-0070 event-policy PUT and one ADR-0078 native scope creation; " - + "plus eighteen ADR-0099 writes (twenty-one federation-invariant writes and three console-retirement edges, less the retired console normalization and grant), plus the two ADR-0099 Amendment 6 writes (the test-record scope and its optional attachment)"); + first.Mutations.Should().Be(43, "thirteen prior approved mutations, three console assignment DELETEs, one ADR-0070 event-policy PUT and one ADR-0078 native scope creation; " + + "plus eighteen ADR-0099 writes (twenty-one federation-invariant writes and three console-retirement edges, less the retired console normalization and grant), plus the two ADR-0099 Amendment 6 writes (the test-record scope and its optional attachment), plus the five ADR-0107 § 7 writes that create the account-removal client (the client, its automatic scope detach, its default-role detach, its role grant and its scope allowance)"); var after = await CaptureAsync(admin, historicalAssignments: false); // ADR-0099: the retired console keeps its stock assignments; both account clients are only disabled. Names(after[consolePath + "/default-client-scopes"]).Should().Equal(DefaultScopes); @@ -238,7 +238,8 @@ public async Task Historical_stock_ordinary_reconciliation_retires_the_console_a var priorClients = before["clients"].EnumerateArray().Select(Id).ToHashSet(StringComparer.Ordinal); priorClients.IsSubsetOf(after["clients"].EnumerateArray().Select(Id)).Should().BeTrue("no client is deleted or recreated"); after["clients"].EnumerateArray().Where(client => !priorClients.Contains(Id(client))).Select(client => Text(client, "clientId")) - .Should().Equal(["learnstack-federation-admin"], "the only new client is ADR-0099's federation admin client"); + .Order(StringComparer.Ordinal).Should().Equal(["learnstack-account-removal", "learnstack-federation-admin"], + "the only new clients are ADR-0099's federation admin client and ADR-0107's account-removal client"); var oldScopeIds = before["client-scopes"].EnumerateArray().Select(Id).ToHashSet(StringComparer.Ordinal); var newScopes = after["client-scopes"].EnumerateArray().Where(scope => !oldScopeIds.Contains(Id(scope))).ToArray(); oldScopeIds.Except(after["client-scopes"].EnumerateArray().Select(Id), StringComparer.Ordinal).Should().BeEmpty( 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 000000000..b6829ae3d --- /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/Api/Authentication/OwnDataRequestEntryInputTests.cs b/backend/tests/LearnStack.Tests.Unit/Api/Authentication/OwnDataRequestEntryInputTests.cs new file mode 100644 index 000000000..317e2aac2 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Api/Authentication/OwnDataRequestEntryInputTests.cs @@ -0,0 +1,211 @@ +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("erasures", "POST", nameof(DataRequestEntryController.CreateErasure))] + [InlineData("closures", "POST", nameof(DataRequestEntryController.CreateClosure))] + [InlineData("cancellations", "POST", nameof(DataRequestEntryController.Cancel))] + [InlineData("revocations", "POST", nameof(DataRequestEntryController.RevokeExport))] + [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("erasures", "?group=tenant", "{\"x\":1}")] + [InlineData("erasures", "", "{}")] + [InlineData("revocations", "?group=tenant", "{}")] + [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("erasures", true, false)] + [InlineData("cancellations", true, true)] + [InlineData("revocations", 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" or "erasures" => "{}", + "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)); + } + + /// + /// The creation purpose has three routes; each route's own request type decides what is filed, so neither the erasure + /// nor the closure route files another kind. The revocation binds the artifact version its If-Match carries. + /// + [Fact] + public async Task Each_creation_route_files_its_own_kind_and_a_revocation_binds_its_artifact_version() + { + var erasure = await OwnDataRequestHttpInput.ReadAsync(Http(Root + "erasures", "?group=" + Organization, "{}"), + OwnDataRequestOperation.ForPath(Root + "erasures")!); + Assert.Equal(new CreateRetainedDataErasureCommand(OrganizationId.From(Guid.Parse(Organization))), erasure!.Request); + var closure = await OwnDataRequestHttpInput.ReadAsync(Http(Root + "closures", "?group=" + Organization, "{}"), + OwnDataRequestOperation.ForPath(Root + "closures")!); + Assert.Equal(new CreateRetainedAccountClosureCommand(OrganizationId.From(Guid.Parse(Organization))), closure!.Request); + Assert.Null(await OwnDataRequestHttpInput.ReadAsync(Http(Root + "closures", "?group=tenant", "{\"requestId\":\"" + Request + "\"}"), + OwnDataRequestOperation.ForPath(Root + "closures")!)); + var export = await OwnDataRequestHttpInput.ReadAsync(Http(Root + "exports", "?group=tenant", "{}"), + OwnDataRequestOperation.ForPath(Root + "exports")!); + Assert.Equal(new CreateRetainedDataExportCommand(null), export!.Request); + + var http = Http(Root + "revocations", "?group=tenant", "{\"requestId\":\"" + Request + "\"}"); + http.Request.Headers.IfMatch = "\"4\""; + var revocation = await OwnDataRequestHttpInput.ReadAsync(http, OwnDataRequestOperation.ForPath(Root + "revocations")!); + Assert.Equal(new RevokeRetainedDataExportCommand(null, Guid.Parse(Request), 4), revocation!.Request); + Assert.True(revocation.IsCurrent(http)); + http.Request.Headers.IfMatch = "\"5\""; + Assert.False(revocation.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/Api/Common/AdministrationHttpInputTests.cs b/backend/tests/LearnStack.Tests.Unit/Api/Common/AdministrationHttpInputTests.cs index 0b861bf29..a42562381 100644 --- a/backend/tests/LearnStack.Tests.Unit/Api/Common/AdministrationHttpInputTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Api/Common/AdministrationHttpInputTests.cs @@ -161,6 +161,49 @@ public async Task Role_arrays_and_cursors_have_nonvacuous_upper_bounds() Assert.False(AdministrationHttpInput.TryPage(http.Request, out _, out _)); } + /// + /// The ticket and chunk routes read their body through a buffer that is overwritten once the body is disposed, and a + /// refused shape clears it before returning; the document parses the buffer in place, so no other copy is made here. + /// + [Theory] + [InlineData("{\"ticket\":\"secret-ticket-canary\",\"index\":0}", true)] + [InlineData("{\"ticket\":\"secret-ticket-canary\",\"index\":0,\"extra\":1}", false)] + public async Task A_sensitive_body_buffer_is_cleared_on_disposal_and_on_refusal(string json, bool valid) + { + var http = Http(json); + var captured = new List(); + var reader = new CapturingStream(Encoding.UTF8.GetBytes(json), captured); + http.Request.Body = reader; + + var body = await AdministrationHttpInput.ReadSensitiveObjectAsync(http, "ticket", "index"); + + Assert.Equal(valid, body is not null); + var buffer = Assert.Single(captured); + if (body is not null) + { + Assert.True(System.Runtime.InteropServices.MemoryMarshal.TryGetArray(body.Buffer, out var segment)); + Assert.Same(buffer, segment.Array); + Assert.Equal("secret-ticket-canary", body.RootElement.GetProperty("ticket").GetString()); + Assert.Contains("secret-ticket-canary", Encoding.UTF8.GetString(buffer), StringComparison.Ordinal); + body.Dispose(); + } + + Assert.All(buffer, value => Assert.Equal(0, value)); + Assert.Equal(0, http.Request.Body.Position); + } + + /// A body stream that records the destination array it was read into. + private sealed class CapturingStream(byte[] content, List captured) : MemoryStream(content) + { + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + if (System.Runtime.InteropServices.MemoryMarshal.TryGetArray(buffer, out var segment) && segment.Array is { } array + && !captured.Contains(array)) + captured.Add(array); + return await base.ReadAsync(buffer, cancellationToken); + } + } + private static DefaultHttpContext Http(string body) { var http = new DefaultHttpContext(); diff --git a/backend/tests/LearnStack.Tests.Unit/Api/Composition/AccountRemovalCompositionTests.cs b/backend/tests/LearnStack.Tests.Unit/Api/Composition/AccountRemovalCompositionTests.cs new file mode 100644 index 000000000..f3491c1a0 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Api/Composition/AccountRemovalCompositionTests.cs @@ -0,0 +1,145 @@ +using FluentAssertions; +using LearnStack.Api.Composition; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Resilience; +using LearnStack.SharedKernel.Secrets; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.FileProviders; +using Microsoft.Extensions.Hosting; +using Xunit; + +namespace LearnStack.Tests.Unit.Api.Composition; + +/// ADR-0107 § 7: the confined adapter replaces the refusing default only when its own client secret is configured. +public sealed class AccountRemovalCompositionTests +{ + private const string Issuer = "https://keycloak.example.com/realms/learnstack"; + + [Fact] + public void The_identity_foundation_registers_the_refusing_default_as_a_singleton() + { + var services = new ServiceCollection(); + LearnStack.Modules.Identity.Infrastructure.Bindings.IdentityFoundationRegistration.AddIdentityContextualFoundation(services); + var descriptor = services.Single(registered => registered.ServiceType == typeof(IIdentityProviderAccountRemoval)); + descriptor.ImplementationType.Should().Be(); + descriptor.Lifetime.Should().Be(ServiceLifetime.Singleton); + } + + [Fact] + public async Task Without_the_client_secret_the_port_keeps_its_refusing_default() + { + await using var provider = Build(new Dictionary { ["Authentication:Tenant:Issuer"] = Issuer }); + var port = provider.GetRequiredService(); + port.Should().BeOfType(); + (await port.RemoveAsync("0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d")).Should().Be(AccountRemovalOutcome.Refused); + } + + [Fact] + public async Task With_the_client_secret_the_confined_adapter_is_selected_under_its_own_resilience_pipeline() + { + await using var provider = Build(new Dictionary + { + ["AccountRemoval:ClientSecret"] = "account-removal-secret", + ["Authentication:Tenant:Issuer"] = Issuer, + }); + provider.GetRequiredService().GetType().Name.Should().Be("KeycloakAccountRemoval"); + provider.GetRequiredService>().PortName.Should().Be("accountRemoval"); + } + + [Theory] + [InlineData("Federation:ClientSecret")] + [InlineData("IdentityEvents:ClientSecret")] + public async Task Another_clients_secret_never_selects_the_adapter(string key) + { + await using var provider = Build(new Dictionary { [key] = "another-clients-secret", ["Authentication:Tenant:Issuer"] = Issuer }); + provider.GetRequiredService().Should().BeOfType(); + } + + [Fact] + public void Plain_http_issuer_is_admitted_only_for_development_loopback() + { + var configuration = new Dictionary + { + ["AccountRemoval:ClientSecret"] = "account-removal-secret", + ["Authentication:Tenant:Issuer"] = "http://localhost:8080/realms/learnstack", + }; + using (var development = Build(configuration, Environments.Development)) + development.GetRequiredService().GetType().Name.Should().Be("KeycloakAccountRemoval"); + using var production = Build(configuration, Environments.Production); + FluentActions.Invoking(() => production.GetRequiredService()).Should().Throw(); + } + + [Theory] + [InlineData("Resilience:accountRemoval:Retry:Enabled", "true")] + [InlineData("Resilience:accountRemoval:Retry:MaxRetryAttempts", "1")] + [InlineData("Resilience:accountRemoval:Timeout:Enabled", "false")] + [InlineData("Resilience:accountRemoval:Timeout:TotalSeconds", "30")] + [InlineData("Resilience:accountRemoval:Timeout:TotalSeconds", "2.5")] + [InlineData("Resilience:accountRemoval:CircuitBreaker:Enabled", "false")] + [InlineData("Resilience:accountRemoval:Bulkhead:MaxConcurrency", "2")] + [InlineData("Resilience:accountRemoval:Bulkhead:MaxConcurrency", "0")] + [InlineData("Resilience:accountRemoval:Bulkhead:QueueLength", "1")] + public void A_retry_an_unbounded_timeout_a_disabled_breaker_or_another_bulkhead_refuses_at_composition(string key, string value) + { + var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary { [key] = value }).Build(); + FluentActions.Invoking(() => new ServiceCollection().AddLearnStackAccountRemovalAdapter(configuration)).Should().Throw(); + } + + [Theory] + [InlineData("Resilience:accountRemoval:CircuitBreaker:FailureRatio", "0")] + [InlineData("Resilience:accountRemoval:CircuitBreaker:FailureRatio", "1.01")] + [InlineData("Resilience:accountRemoval:CircuitBreaker:MinimumThroughput", "1")] + [InlineData("Resilience:accountRemoval:CircuitBreaker:SamplingDurationSeconds", "61")] + [InlineData("Resilience:accountRemoval:CircuitBreaker:BreakDurationSeconds", "301")] + public void An_enabled_breaker_outside_its_fixed_range_refuses_at_composition(string key, string value) + { + var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary { [key] = value }).Build(); + FluentActions.Invoking(() => new ServiceCollection().AddLearnStackAccountRemovalAdapter(configuration)).Should().Throw(); + } + + [Fact] + public void The_federation_pipeline_values_do_not_configure_this_port_and_the_fixed_shape_is_the_dirty_control() + { + // The federation section is another port's: its bulkhead of four does not leak into this one. + var other = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + { ["Resilience:federation:Bulkhead:MaxConcurrency"] = "4", ["Resilience:federation:Timeout:TotalSeconds"] = "2.5" }).Build(); + FluentActions.Invoking(() => new ServiceCollection().AddLearnStackAccountRemovalAdapter(other)).Should().NotThrow(); + + var fixedShape = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + { + ["Resilience:accountRemoval:Timeout:TotalSeconds"] = "5", + ["Resilience:accountRemoval:Bulkhead:MaxConcurrency"] = "1", + ["Resilience:accountRemoval:Retry:Enabled"] = "false", + }).Build(); + FluentActions.Invoking(() => new ServiceCollection().AddLearnStackAccountRemovalAdapter(fixedShape)).Should().NotThrow(); + } + + private static ServiceProvider Build(Dictionary values, string environment = "Production") + { + var configuration = new ConfigurationBuilder().AddInMemoryCollection(values).Build(); + var services = new ServiceCollection(); + services.AddSingleton(configuration); + services.AddSingleton(new ConfigurationSecrets(configuration)); + services.AddSingleton(new Environment(environment)); + services.AddLogging(); + // The module's default is registered first, exactly as the Identity foundation does. + services.TryAddSingleton(); + services.AddLearnStackAccountRemovalAdapter(configuration); + return services.BuildServiceProvider(validateScopes: true); + } + + private sealed class ConfigurationSecrets(IConfiguration configuration) : ISecretProvider + { + public string? GetSecret(string key) => configuration[key]; + } + + private sealed class Environment(string name) : IHostEnvironment + { + public string EnvironmentName { get; set; } = name; + public string ApplicationName { get; set; } = "LearnStack.Api"; + public string ContentRootPath { get; set; } = AppContext.BaseDirectory; + public IFileProvider ContentRootFileProvider { get; set; } = new NullFileProvider(); + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperationClauseWitnessTests.cs b/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperationClauseWitnessTests.cs index ad20c10a7..71351cd71 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 920971a88..704f9c389 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,10 +37,34 @@ 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(170, 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(68, catalog.All.Count(policy => policy.Kind == OperationPolicyKind.Protected)); + // ADR-0106 § 4, ADR-0107 § 7: ten 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(10, catalog.All.Count(policy => policy.Kind == OperationPolicyKind.OwnDataRequest)); + // ADR-0106 § 9, ADR-0107 § 7: the retained own-scope entry's nine 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(CreateRetainedDataErasureCommand), typeof(CreateRetainedAccountClosureCommand), typeof(CancelRetainedDataRequestCommand), + typeof(RevokeRetainedDataExportCommand), + 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) } @@ -64,7 +89,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(58, 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); @@ -119,6 +144,7 @@ public void Operator_acts_accept_only_the_operator_source_and_seed_acts_never_ac typeof(LearnStack.Modules.Identity.Application.Contracts.OperatorActs.OperatorInitializeRoleCommand), typeof(LearnStack.Modules.Identity.Application.Contracts.OperatorActs.OperatorCreateFirstAdminCommand), typeof(LearnStack.Modules.Identity.Application.Contracts.OperatorActs.OperatorRecoverAdminCommand), + typeof(LearnStack.Modules.Identity.Application.Contracts.OperatorActs.FanOutClosureCommand), ]; foreach (var act in operatorActs) diff --git a/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperatorActGuardTests.cs b/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperatorActGuardTests.cs index 85b693eb1..aaf715125 100644 --- a/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperatorActGuardTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Application/Authorization/OperatorActGuardTests.cs @@ -4,6 +4,7 @@ using LearnStack.Application.Authorization; using LearnStack.Infrastructure.Audit; using LearnStack.Modules.Identity.Application; +using LearnStack.Modules.Identity.Application.Contracts.OperatorActs; using LearnStack.Modules.Tenancy.Application.Authorization; using LearnStack.Modules.Tenancy.Application.Contracts.Seeding; using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; @@ -159,6 +160,7 @@ private static void Apply(Rig rig, string change) [InlineData("announced_elsewhere")] [InlineData("not_announced")] [InlineData("global_identity")] + [InlineData("announced_with_an_organization")] public async Task A_Transaction_That_Is_Not_The_Ordinary_Announced_Owner_Is_Refused(string change) { using var rig = new Rig(); @@ -176,6 +178,11 @@ await rig.ExpectRefusalAsync(request, () => .Returns(new TenantContextAnnouncement(1, TenantId.From(Guid.CreateVersion7()), null)); break; case "not_announced": rig.Unit.GetTenantContextAnnouncement(Arg.Any()).Returns((TenantContextAnnouncement?)null); break; + case "announced_with_an_organization": + // The tenant's ambient context with no organization, on a transaction that announced one: not its owner. + rig.Unit.GetTenantContextAnnouncement(Arg.Any()) + .Returns(new TenantContextAnnouncement(1, Tenant, OrganizationId.From(Guid.CreateVersion7()))); + break; default: rig.GlobalUnit.IsGlobalIdentityTransaction.Returns(true); break; } @@ -299,6 +306,68 @@ Task> Refuse(object request) => rig.RunAsync(request, () => (rig.EvidenceWrites().Length > 0).Should().Be(writes); } + /// + /// ADR-0102 Amendment 2: a closure's fan-out runs in its participant group's organization. The guard admits a context + /// that names an organization only for that operation, by reference, and only on a transaction that announced the same + /// tenant and organization; the tenant-wide group of the same act announces none. + /// + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task A_Closure_Fan_Out_Is_Admitted_In_Its_Announced_Group(bool organization) + { + using var rig = new Rig { Operation = PlatformOperations.ClosureFanOut }; + var group = organization ? OrganizationId.From(Guid.CreateVersion7()) : (OrganizationId?)null; + rig.Announce(group); + var request = new FanOutClosureCommand(UserId.From(Guid.CreateVersion7()), group); + + await rig.RunAsync(request, async () => + { + rig.Guard.RequireLiveAct(request).IsSuccess.Should().BeTrue(); + var admission = await rig.Guard.AdmitAsync(request, Plan(), default); + admission.IsSuccess.Should().BeTrue(); + rig.Guard.RequireCurrent(admission.Value!).IsSuccess.Should().BeTrue(); + return Result.Ok(None.Value); + }); + + await rig.Locks.Received(1).AcquireAsync(Arg.Any(), Arg.Any()); + } + + /// + /// The organization's admission is the fan-out's alone, and only for the group its transaction announced: an onboarding + /// act in an organization context, and a fan-out whose transaction announced another organization or none, are each + /// refused before a lock. + /// + [Theory] + [InlineData("onboarding_operation")] + [InlineData("announced_another_organization")] + [InlineData("announced_no_organization")] + public async Task An_Organization_Is_Admitted_Only_For_The_Fan_Out_On_Its_Own_Announcement(string variant) + { + using var rig = new Rig + { + Operation = variant == "onboarding_operation" ? PlatformOperations.TenantProvision : PlatformOperations.ClosureFanOut, + }; + var group = OrganizationId.From(Guid.CreateVersion7()); + rig.Announce(group); + if (variant == "announced_another_organization") + rig.Unit.GetTenantContextAnnouncement(Arg.Any()) + .Returns(new TenantContextAnnouncement(1, Tenant, OrganizationId.From(Guid.CreateVersion7()))); + else if (variant == "announced_no_organization") + rig.Unit.GetTenantContextAnnouncement(Arg.Any()).Returns(new TenantContextAnnouncement(1, Tenant, null)); + var request = new FanOutClosureCommand(UserId.From(Guid.CreateVersion7()), group); + var live = true; + + await rig.RunAsync(request, () => + { + live = rig.Guard.RequireLiveAct(request).IsSuccess; + return Task.FromResult(Result.Ok(None.Value)); + }); + await rig.ExpectRefusalAsync(request, () => request); + + live.Should().BeFalse(); + } + [Fact] public async Task A_Plan_For_Another_Tenant_Is_Not_Held_For_This_Act() { @@ -378,6 +447,16 @@ public string[] EvidenceWrites() => [.. Store.ReceivedCalls() public AuthorizationSourceKind SourceKind { get; set; } = AuthorizationSourceKind.PlatformOperator; + /// The operation the operator descriptor is minted for. + public PlatformOperation Operation { get; set; } = PlatformOperations.TenantProvision; + + /// The context and its transaction's announcement, for 's group of the tenant. + public void Announce(OrganizationId? organization) + { + Context.OrganizationId.Returns(organization); + Unit.GetTenantContextAnnouncement(Arg.Any()).Returns(new TenantContextAnnouncement(1, Tenant, organization)); + } + public Task> RunAsync(TRequest request, Func>> body) where TRequest : notnull => _coordinator.ExecuteRequestAsync>(request, body); @@ -412,7 +491,7 @@ private sealed class OperatorSource(Rig rig) : TrustedOperationDescriptor.Mintin return rig.SourceKind == AuthorizationSourceKind.PlatformOperator ? ForOperation( AuthorizationSourceKind.PlatformOperator, requestType, context, null, - PlatformOperatorAttribution.From(TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now))) + PlatformOperatorAttribution.From(TestPlatformAdmissions.Admission(rig.Operation, issuedAt: Now))) : ForOperation(AuthorizationSourceKind.Seed, requestType, context); } 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 000000000..22cdb11a0 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Application/DataProtection/DataExportBundleBuilderTests.cs @@ -0,0 +1,422 @@ +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 At_the_smallest_ceiling_the_audit_cap_is_clamped_to_half_of_it_so_the_section_truncates_instead_of_failing() + { + var options = new DataExportOptions(DataRequestLimits.MinimumBundleBytes); + var record = "{\"padding\":\"" + new string('a', 1_000) + "\"}"; + long included = 0; + var builder = Builder(options, new Participant("audit", async writer => + { + while (true) + { + var outcome = await Append(writer, "entries", record); + if (outcome != UserDataExportAppend.Appended) + { + outcome.Should().Be(UserDataExportAppend.SectionCapReached, "the clamped cap is reached before the ceiling"); + writer.DeclareTruncated("entries", included, 100_000); + return; + } + + included++; + } + }, cap: DataRequestLimits.AuditSectionBytes), new Participant("later", writer => Append(writer, "items", "1"))); + + var result = await builder.BuildAsync(Subject(), GeneratedAt, CancellationToken.None); + + result.IsTooLarge.Should().BeFalse("an unclamped 8 MiB cap would never apply under a 1 MiB ceiling"); + using var bundle = result.Bundle!; + bundle.ByteCount.Should().BeLessThanOrEqualTo(options.MaxBytes); + included.Should().BeGreaterThan(0); + (included * (record.Length + 1L)).Should().BeLessThanOrEqualTo(options.MaxBytes / 2); + bundle.Truncations.Should().ContainSingle().Which.Should().Be(new DataExportTruncation("audit.entries", included, 100_000)); + using var document = await Read(bundle); + document.RootElement.GetProperty("sections").GetProperty("later").GetProperty("items").GetArrayLength().Should().Be(1, + "the sections after a truncated one are still written"); + } + + [Fact] + public async Task A_collection_cap_truncates_only_its_collection_and_is_clamped_to_half_the_ceiling() + { + var options = new DataExportOptions(DataRequestLimits.MinimumBundleBytes); + var record = "{\"padding\":\"" + new string('i', 500) + "\"}"; + var outcomes = new List(); + long issued = 0; + var builder = Builder(options, new Participant("identity", async writer => + { + for (var index = 0; index < 100; index++) + { + (await Append(writer, "accepted", record)).Should().Be(UserDataExportAppend.Appended); + } + + while (true) + { + var outcome = await Append(writer, "issued", record); + outcomes.Add(outcome); + if (outcome != UserDataExportAppend.Appended) + { + writer.DeclareTruncated("issued", issued, issued + 1); + return; + } + + issued++; + } + }, collectionCaps: new Dictionary { ["issued"] = DataRequestLimits.IssuedInvitationsCollectionBytes })); + + var result = await builder.BuildAsync(Subject(), GeneratedAt, CancellationToken.None); + + result.IsTooLarge.Should().BeFalse(); + using var bundle = result.Bundle!; + outcomes[^1].Should().Be(UserDataExportAppend.SectionCapReached); + (issued * (record.Length + 1L)).Should().BeLessThanOrEqualTo(options.MaxBytes / 2, + "the 4 MiB collection cap is clamped to half of the 1 MiB ceiling"); + using var document = await Read(bundle); + var section = document.RootElement.GetProperty("sections").GetProperty("identity"); + section.GetProperty("accepted").GetArrayLength().Should().Be(100, "an uncapped collection of the same section is whole"); + section.GetProperty("issued").GetArrayLength().Should().Be((int)issued); + bundle.Truncations.Should().ContainSingle().Which.Collection.Should().Be("identity.issued"); + } + + [Fact] + public async Task A_collection_cap_below_the_ceiling_applies_unclamped() + { + var builder = Builder(DataExportOptions.Default, new Participant("identity", async writer => + { + (await Append(writer, "issued", "\"" + new string('s', 4_000) + "\"")).Should().Be(UserDataExportAppend.Appended); + (await Append(writer, "issued", "\"" + new string('s', 4_000) + "\"")).Should().Be(UserDataExportAppend.SectionCapReached); + (await Append(writer, "other", "\"" + new string('s', 4_000) + "\"")).Should().Be(UserDataExportAppend.Appended); + }, collectionCaps: new Dictionary { ["issued"] = 6_000 })); + + using var bundle = (await builder.BuildAsync(Subject(), GeneratedAt, CancellationToken.None)).Bundle!; + + bundle.ByteCount.Should().BeGreaterThan(8_000); + } + + [Theory] + [InlineData(DataRequestLimits.AuditSectionBytes, DataRequestLimits.DefaultMaximumBundleBytes, DataRequestLimits.AuditSectionBytes)] + [InlineData(DataRequestLimits.AuditSectionBytes, DataRequestLimits.MinimumBundleBytes, DataRequestLimits.MinimumBundleBytes / 2)] + [InlineData(DataRequestLimits.IssuedInvitationsCollectionBytes, DataRequestLimits.DefaultMaximumBundleBytes, + DataRequestLimits.IssuedInvitationsCollectionBytes)] + [InlineData(4_096L, DataRequestLimits.MaximumBundleBytes, 4_096L)] + public void A_declared_cap_is_clamped_to_half_the_ceiling(long declared, long ceiling, long expected) => + DataExportBundleBuilder.EffectiveCap(declared, ceiling).Should().Be(expected); + + [Theory] + [InlineData("section")] + [InlineData("collection_value")] + [InlineData("collection_name")] + public async Task A_cap_outside_the_bundle_range_or_on_a_malformed_collection_is_a_programming_error(string misuse) + { + var builder = Builder(DataExportOptions.Default, new Participant("capped", _ => Task.CompletedTask, + cap: misuse == "section" ? 0 : null, + collectionCaps: misuse switch + { + "collection_value" => new Dictionary { ["items"] = DataRequestLimits.MaximumBundleBytes + 1 }, + "collection_name" => new Dictionary { ["Bad-Name"] = 1_024 }, + _ => null, + })); + + await FluentActions.Invoking(() => builder.BuildAsync(Subject(), GeneratedAt, CancellationToken.None)) + .Should().ThrowAsync(); + } + + [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, + IReadOnlyDictionary? collectionCaps = null) : IUserDataParticipant + { + public string Key => key; + + public long? ExportSectionCapBytes => cap; + + public IReadOnlyDictionary ExportCollectionCapBytes => collectionCaps ?? new Dictionary(); + + 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/Application/DataProtection/PlaintextSegmentBufferTests.cs b/backend/tests/LearnStack.Tests.Unit/Application/DataProtection/PlaintextSegmentBufferTests.cs new file mode 100644 index 000000000..78f3e0e48 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Application/DataProtection/PlaintextSegmentBufferTests.cs @@ -0,0 +1,128 @@ +using System.Buffers; +using System.Reflection; +using FluentAssertions; +using LearnStack.Application.DataProtection; +using LearnStack.SharedKernel.DataProtection; +using Xunit; + +namespace LearnStack.Tests.Unit.Application.DataProtection; + +/// +/// The bundle's plaintext segments are rented, not allocated per chunk: exactly one chunk of each rented array is used, +/// and every rented array is overwritten in full before it goes back to the pool, on every path. The buffer is internal +/// to LearnStack.Application, which has no friend assembly, so it is reached through its declared constructor. +/// +public sealed class PlaintextSegmentBufferTests +{ + [Theory] + [InlineData("completed")] + [InlineData("overflowed")] + [InlineData("disposed_twice")] + [InlineData("disposed_while_reading")] + public void Every_rented_segment_is_cleared_in_full_before_it_is_returned(string path) + { + var pool = new RecordingPool(); + var limit = path == "overflowed" ? DataRequestLimits.ChunkPlaintextBytes + 10 : 3L * DataRequestLimits.ChunkPlaintextBytes; + var buffer = Create(limit, pool); + var writer = (IBufferWriter)buffer; + var written = 0; + while (written < 2 * DataRequestLimits.ChunkPlaintextBytes + 5) + { + var span = writer.GetSpan(4096); + var count = Math.Min(4096, 2 * DataRequestLimits.ChunkPlaintextBytes + 5 - written); + span[..count].Fill(0x5a); + writer.Advance(count); + written += count; + } + + Overflowed(buffer).Should().Be(path == "overflowed"); + if (path is "completed" or "disposed_twice" or "disposed_while_reading") + { + var chunks = Chunks(buffer).ToArray(); + chunks.Select(chunk => chunk.Length).Should().Equal(DataRequestLimits.ChunkPlaintextBytes, DataRequestLimits.ChunkPlaintextBytes, 5); + chunks.Should().OnlyContain(chunk => Only(chunk, 0x5a), "only the bytes written are handed out"); + } + + if (path == "disposed_while_reading") + { + var reading = Chunks(buffer).GetEnumerator(); + reading.MoveNext().Should().BeTrue(); + ((IDisposable)buffer).Dispose(); + FluentActions.Invoking(() => reading.MoveNext()).Should().Throw("a reader stops at disposal"); + } + else + { + ((IDisposable)buffer).Dispose(); + } + + if (path == "disposed_twice") + { + ((IDisposable)buffer).Dispose(); + } + + pool.Rented.Should().NotBeEmpty().And.OnlyContain(array => array.Length >= DataRequestLimits.ChunkPlaintextBytes); + pool.Returned.Should().HaveSameCount(pool.Rented); + pool.Rented.Should().OnlyContain(array => pool.Returned.Count(returned => ReferenceEquals(returned, array)) == 1, + "every rented array goes back exactly once"); + pool.ClearedOnReturn.Should().OnlyContain(cleared => cleared, "each array was overwritten in full before its return"); + pool.Returned.Should().OnlyContain(array => Only(array, 0)); + } + + [Fact] + public void A_rented_array_larger_than_a_chunk_and_holding_a_former_renters_bytes_hands_out_only_what_was_written() + { + var pool = new RecordingPool(oversize: 4096, stale: 0xee); + var buffer = Create(DataRequestLimits.ChunkPlaintextBytes * 2L, pool); + var writer = (IBufferWriter)buffer; + var written = 0; + while (written < DataRequestLimits.ChunkPlaintextBytes + 3) + { + writer.GetSpan(3)[..3].Fill(0x11); + writer.Advance(3); + written += 3; + } + + var chunks = Chunks(buffer).ToArray(); + chunks.Select(chunk => chunk.Length).Should().Equal(DataRequestLimits.ChunkPlaintextBytes, written - DataRequestLimits.ChunkPlaintextBytes); + chunks.Should().OnlyContain(chunk => Only(chunk, 0x11), "no stale byte of a former renter is read"); + ((IDisposable)buffer).Dispose(); + pool.Returned.Should().OnlyContain(array => array.Length == DataRequestLimits.ChunkPlaintextBytes + 4096 + && Only(array, 0), "the whole rented array is cleared, its unused tail included"); + } + + private static bool Only(ReadOnlyMemory bytes, byte value) => bytes.Span.IndexOfAnyExcept(value) < 0; + + private static readonly Type BufferType = typeof(DataExportBundleBuilder).Assembly + .GetType("LearnStack.Application.DataProtection.PlaintextSegmentBuffer", throwOnError: true)!; + + private static object Create(long limit, ArrayPool pool) => + BufferType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, [typeof(long), typeof(ArrayPool)])! + .Invoke([limit, pool]); + + private static bool Overflowed(object buffer) => (bool)BufferType.GetProperty("Overflowed")!.GetValue(buffer)!; + + private static IEnumerable> Chunks(object buffer) => + (IEnumerable>)BufferType.GetMethod("Chunks")!.Invoke(buffer, [])!; + + /// A pool that records what it lent and whether each array came back cleared. + private sealed class RecordingPool(int oversize = 0, byte stale = 0) : ArrayPool + { + public List Rented { get; } = []; + public List Returned { get; } = []; + public List ClearedOnReturn { get; } = []; + + public override byte[] Rent(int minimumLength) + { + var array = new byte[minimumLength + oversize]; + array.AsSpan().Fill(stale); + Rented.Add(array); + return array; + } + + public override void Return(byte[] array, bool clearArray = false) + { + ClearedOnReturn.Add(array.AsSpan().IndexOfAnyExcept((byte)0) < 0); + Returned.Add(array); + } + } +} 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 000000000..1903690c3 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Audit/AuditUserDataParticipantTests.cs @@ -0,0 +1,211 @@ +using System.Reflection; +using System.Text.Json; +using System.Text.RegularExpressions; +using FluentAssertions; +using LearnStack.Modules.Audit.Infrastructure.DataRequests; +using LearnStack.Modules.Audit.Infrastructure.Persistence.Migrations; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using Microsoft.EntityFrameworkCore.Migrations.Operations; +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); + } + + [Fact] + public void Rewritten_property_names_stay_distinct_deterministically_within_one_object() + { + var own = AuditUserDataParticipant.Own(Request()); + var payload = "{\"" + OtherPerson + "\":1,\"" + Subject + "\":2,\"" + OtherMembership + "\":3,\"third_party_2\":4,\"" + + Subject.ToString("D").ToUpperInvariant() + "\":5,\"nested\":{\"" + OtherPerson + "\":6,\"" + OtherMembership + "\":7}}"; + + string Project() + { + using var stream = new MemoryStream(); + using (var json = new Utf8JsonWriter(stream)) + { + AuditPayloadProjection.Write(json, payload, own); + } + + return System.Text.Encoding.UTF8.GetString(stream.ToArray()); + } + + var projected = Project(); + + var root = JsonDocument.Parse(projected).RootElement; + root.EnumerateObject().Select(property => property.Name).Should() + .Equal("third_party", "self", "third_party_2", "third_party_2_2", "self_2", "nested"); + root.EnumerateObject().Select(property => property.Value.ValueKind == JsonValueKind.Number ? property.Value.GetInt32() : 0) + .Should().Equal([1, 2, 3, 4, 5, 0], "every value is kept under its own name"); + root.GetProperty("nested").EnumerateObject().Select(property => property.Name).Should().Equal(["third_party", "third_party_2"], + "each object numbers its own names"); + Project().Should().Be(projected, "the numbering follows document order alone"); + AnyIdentifier().IsMatch(projected).Should().BeFalse(); + } + + [Fact] + public void The_metadata_window_seeks_each_branch_of_the_reach_on_the_index_the_migration_builds_for_it() + { + var indexes = new index_audit_log_data_request_selection().UpOperations.OfType() + .Select(operation => Normalize(operation.Sql)).Where(sql => sql.Contains("person_reference", StringComparison.Ordinal)) + .ToList(); + var keys = Normalize(Statement("PersonReferenceKeys")); + var metadata = Normalize(Statement("MetadataSql")); + + indexes.Should().Equal( + [ + "CREATE INDEX ix_audit_log_tenant_id_organization_id_person_reference ON public.audit_log " + + "(tenant_id, organization_id, \"timestamp\" DESC) WHERE organization_id IS NOT NULL AND " + keys + ";", + "CREATE INDEX ix_audit_log_tenant_id_tenant_level_person_reference ON public.audit_log " + + "(tenant_id, \"timestamp\" DESC) WHERE organization_id IS NULL AND " + keys + ";", + ], + "each branch has an index in newest-first order whose predicate the statement repeats literally, so the " + + "planner proves it applies and stops at the window; an IS NULL index condition yields no order"); + metadata.Should().Contain("WHERE tenant_id = @tenant AND organization_id = @organization AND " + keys + + " ORDER BY \"timestamp\" DESC LIMIT @window", "the organization branch is a limited seek on the group's organization"); + metadata.Should().Contain("WHERE tenant_id = @tenant AND organization_id IS NULL AND (NOT @scoped OR @organization IS NULL) AND " + + keys + " ORDER BY \"timestamp\" DESC LIMIT @window", + "the tenant-level branch is a limited seek, an administrator's only in the tenant-wide group"); + AuditUserDataParticipant.ReachIsComplete.Should().BeFalse("no current reach is the person's whole audit trail in the tenant"); + } + + private static string Statement(string name) => (string)typeof(AuditUserDataParticipant) + .GetField(name, BindingFlags.Static | BindingFlags.NonPublic)!.GetRawConstantValue()!; + + private static string Normalize(string sql) => WhiteSpace().Replace(sql, " ").Replace("( ", "(", StringComparison.Ordinal) + .Replace(" )", ")", StringComparison.Ordinal).Trim(); + + 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(@"\s+")] + private static partial Regex WhiteSpace(); + + [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/AccountClosureOperatorOperationsTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/AccountClosureOperatorOperationsTests.cs new file mode 100644 index 000000000..8a8ceb504 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Identity/AccountClosureOperatorOperationsTests.cs @@ -0,0 +1,120 @@ +using FluentAssertions; +using LearnStack.Modules.Identity.Application.DataRequests; +using LearnStack.Modules.Identity.Infrastructure.DataRequests; +using LearnStack.Modules.Tenancy.Application.Contracts.IdentityLifecycle; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.Tests.Fixtures; +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using Xunit; + +namespace LearnStack.Tests.Unit.Identity; + +/// +/// The closure owner's refusals before it reaches the database (ADR-0107 § 7): a deployment with no single fan-out +/// registered never enters the platform scope for a Begin, so it never moves a person to Closing, and an admission for +/// another act or a request that names nothing is refused by Begin and by Finalize before the admission is spent and +/// before the provider is asked anything. +/// +public sealed class AccountClosureOperatorOperationsTests +{ + [Theory] + [InlineData(0)] + [InlineData(2)] + public async Task A_Begin_without_exactly_one_fan_out_refuses_before_it_enters_the_scope(int registered) + { + var scope = Substitute.For(); + var owner = Owner(scope, [.. Enumerable.Range(0, registered).Select(_ => Substitute.For())]); + var admission = TestPlatformAdmissions.Admission(PlatformOperations.ClosureBegin); + + var act = () => owner.BeginAsync(admission, Guid.CreateVersion7()); + + (await act.Should().ThrowAsync()).Which.Message.Should().Contain("fan-out"); + await scope.DidNotReceiveWithAnyArgs().EnterAsync(default!, default, default, default, default); + admission.TryConsume().Should().BeTrue("the refused act did not spend the admission"); + } + + [Fact] + public async Task A_Begin_refuses_another_act_s_admission_and_a_request_that_names_nothing_before_anything_runs() + { + var scope = Substitute.For(); + var owner = Owner(scope, [Substitute.For()]); + + foreach (var operation in PlatformOperations.All.Where(operation => !ReferenceEquals(operation, PlatformOperations.ClosureBegin))) + { + var foreign = () => owner.BeginAsync(TestPlatformAdmissions.Admission(operation), Guid.CreateVersion7()); + (await foreign.Should().ThrowAsync(operation.AuditSlug)).Which.ParamName.Should().Be("admission"); + } + + var empty = () => owner.BeginAsync(TestPlatformAdmissions.Admission(PlatformOperations.ClosureBegin), Guid.Empty); + (await empty.Should().ThrowAsync()).Which.ParamName.Should().Be("closureRequestId"); + await scope.DidNotReceiveWithAnyArgs().EnterAsync(default!, default, default, default, default); + } + + [Fact] + public async Task A_Finalize_refuses_another_act_s_admission_and_a_request_that_names_nothing_before_anything_runs() + { + var scope = Substitute.For(); + var removal = Substitute.For(); + var owner = Owner(scope, [Substitute.For()], removal); + + foreach (var operation in PlatformOperations.All.Where(operation => !ReferenceEquals(operation, PlatformOperations.ClosureFinalize))) + { + var admission = TestPlatformAdmissions.Admission(operation); + var foreign = () => owner.FinalizeAsync(admission, Guid.CreateVersion7()); + (await foreign.Should().ThrowAsync(operation.AuditSlug)).Which.ParamName.Should().Be("admission"); + admission.TryConsume().Should().BeTrue("the refused act did not spend the admission"); + } + + var empty = () => owner.FinalizeAsync(TestPlatformAdmissions.Admission(PlatformOperations.ClosureFinalize), Guid.Empty); + (await empty.Should().ThrowAsync()).Which.ParamName.Should().Be("closureRequestId"); + await scope.DidNotReceiveWithAnyArgs().EnterAsync(default!, default, default, default, default); + await removal.DidNotReceiveWithAnyArgs().RemoveAsync(default!, default); + } + + /// + /// One bound governs every step of a closure: the participant groups Begin admits are what the fan-out takes in one call + /// and what one lifecycle read answers, and the Memberships one tenant may hold are what one group's snapshot freezes and + /// one redaction pass compares, which the plan factory itself refuses past. + /// + [Fact] + public void One_bound_governs_the_closure_s_participant_read_fan_out_snapshot_and_redaction_pass() + { + ClosureLimits.MaximumParticipantGroups.Should().Be(256); + ClosureFanOut.MaximumGroups.Should().Be(ClosureLimits.MaximumParticipantGroups); + ClosureLimits.MaximumParticipantGroups.Should().BeLessThanOrEqualTo(IClosureGroupLifecycleReader.MaximumGroups, + "one lifecycle read answers every participant group"); + ClosureLimits.MaximumTenantMemberships.Should().Be(DataRequestLimits.MaximumSnapshotMemberships); + ClosureLimits.MaximumMemberships.Should().Be(ClosureLimits.MaximumParticipantGroups * ClosureLimits.MaximumTenantMemberships); + + ClosureLimits.Admits(ClosureLimits.MaximumParticipantGroups, ClosureLimits.MaximumTenantMemberships).Should().BeTrue(); + ClosureLimits.Admits(ClosureLimits.MaximumParticipantGroups + 1, 1).Should().BeFalse(); + ClosureLimits.Admits(1, ClosureLimits.MaximumTenantMemberships + 1).Should().BeFalse(); + + var tenant = TenantId.From(Guid.CreateVersion7()); + var subject = LearnStack.SharedKernel.Identifiers.UserId.From(Guid.CreateVersion7()); + Guid[] Memberships(int count) => [.. Enumerable.Range(0, count).Select(_ => Guid.CreateVersion7())]; + LearnStack.SharedKernel.Audit.AuditRedactionPlan.ForClosureTenant(tenant, subject, Memberships(ClosureLimits.MaximumTenantMemberships)) + .MembershipIds.Should().HaveCount(ClosureLimits.MaximumTenantMemberships, "exactly the tenant bound is one pass"); + FluentActions.Invoking(() => LearnStack.SharedKernel.Audit.AuditRedactionPlan.ForClosureTenant( + tenant, subject, Memberships(ClosureLimits.MaximumTenantMemberships + 1))) + .Should().Throw("one Membership past it is no pass, which is why Begin refuses such a person"); + } + + [Theory] + [InlineData(0, 0, true)] + [InlineData(1, 0, false)] + [InlineData(0, 1, false)] + public void A_tally_is_complete_only_when_no_served_group_is_waiting_or_failed(int waiting, int failed, bool complete) => + new ClosureBeginTally(Served: 3, Started: 3 - waiting - failed, Adopted: 0, Waiting: waiting, Failed: failed, Unserved: 1) + .Complete.Should().Be(complete); + + private static AccountClosureOperatorOperations Owner( + IPlatformAdminScope scope, IReadOnlyList fanOuts, IIdentityProviderAccountRemoval? removal = null) => new( + scope, Substitute.For(), new NoHoldSource(), fanOuts, + removal ?? Substitute.For(), NullLogger.Instance); +} diff --git a/backend/tests/LearnStack.Tests.Unit/Identity/ClosureFanOutUnitTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/ClosureFanOutUnitTests.cs new file mode 100644 index 000000000..efdb8350b --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Identity/ClosureFanOutUnitTests.cs @@ -0,0 +1,214 @@ +using FluentAssertions; +using LearnStack.Application.Authorization; +using LearnStack.Infrastructure.PlatformOperator; +using LearnStack.Modules.Identity.Application; +using LearnStack.Modules.Identity.Application.Contracts.OperatorActs; +using LearnStack.Modules.Identity.Infrastructure.DataRequests; +using LearnStack.Modules.Tenancy.Application.Authorization; +using LearnStack.SharedKernel.Errors; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Localization; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Platform; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using LearnStack.Tests.Fixtures; +using MediatR; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using Xunit; + +namespace LearnStack.Tests.Unit.Identity; + +/// +/// ADR-0107 § 7: what the closure's fan-out decides around each group's act, with the real operator act executor and a +/// sender double in place of the pipeline. One admission per group from the gate; groups in one deterministic order; every +/// group answered, a refused admission, a refusal and an exception each that group's failure; only the operator's +/// cancellation stops the loop; and a request that is not a closing person's bounded set of distinct groups is refused +/// before any act. +/// +public sealed class ClosureFanOutUnitTests +{ + private static readonly UserId Person = UserId.From(Guid.CreateVersion7()); + private static readonly TenantId First = TenantId.From(Guid.Parse("01930000-0000-7000-8000-000000000001")); + private static readonly TenantId Second = TenantId.From(Guid.Parse("01930000-0000-7000-8000-000000000002")); + private static readonly OrganizationId Branch = OrganizationId.From(Guid.Parse("01930000-0000-7000-8000-0000000000b1")); + private static readonly OrganizationId OtherBranch = OrganizationId.From(Guid.Parse("01930000-0000-7000-8000-0000000000b2")); + + [Fact] + public async Task Every_group_is_one_admitted_act_in_its_own_tenant_and_organization_in_a_deterministic_order() + { + using var rig = new Rig(); + // Listed out of order on purpose: the fan-out sorts by tenant, the tenant-wide group first, then each organization. + ClosureParticipantGroup[] groups = [new(Second, null), new(First, OtherBranch), new(First, null), new(First, Branch)]; + + var reports = await rig.FanOut.FanOutAsync(TestPlatformAdmissions.Witness(), "CHG-107", new ClosureFanOutRequest(Person, groups)); + + reports.Select(report => report.Group).Should().Equal(new ClosureParticipantGroup(First, null), new ClosureParticipantGroup(First, Branch), + new ClosureParticipantGroup(First, OtherBranch), new ClosureParticipantGroup(Second, null)); + reports.Should().OnlyContain(report => report.Outcome == ClosureGroupOutcome.Started); + rig.Acts.Select(act => (act.Tenant, act.Organization, act.Command.OrganizationId)).Should().Equal( + (First, (OrganizationId?)null, (OrganizationId?)null), (First, Branch, Branch), (First, OtherBranch, OtherBranch), + (Second, null, null)); + rig.Acts.Should().OnlyContain(act => act.Command.SubjectUserId == Person && act.Operation == PlatformOperations.ClosureFanOut); +#pragma warning disable CA2012 // NSubstitute checks the call; nothing is awaited. + _ = rig.Gate.Received(4).AdmitAsync(Arg.Any(), PlatformOperations.ClosureFanOut, "CHG-107", + Arg.Any()); +#pragma warning restore CA2012 + } + + [Fact] + public async Task A_refused_admission_a_refusal_and_an_exception_are_each_their_groups_failure_and_the_others_still_run() + { + using var rig = new Rig(); + rig.RefuseAdmissionAt.Add(1); // the second group in the fan-out's order: (First, Branch) + rig.Refuse.Add(new(First, OtherBranch)); + rig.Throw.Add(new(Second, null)); + rig.Answer[new(First, null)] = ClosureGroupOutcome.Adopted; + ClosureParticipantGroup[] groups = [new(First, null), new(First, Branch), new(First, OtherBranch), new(Second, null)]; + + var reports = await rig.FanOut.FanOutAsync(TestPlatformAdmissions.Witness(), null, new ClosureFanOutRequest(Person, groups)); + + reports.Select(report => report.Outcome).Should().Equal(ClosureGroupOutcome.Adopted, ClosureGroupOutcome.Failed, + ClosureGroupOutcome.Failed, ClosureGroupOutcome.Failed); + rig.Acts.Select(act => act.Organization).Should().Equal([null, OtherBranch, null], + "the refused admission ran no act; the refusal and the exception each ran theirs"); + } + + [Fact] + public async Task The_operators_cancellation_stops_the_loop_by_throwing() + { + using var rig = new Rig(); + using var cancellation = new CancellationTokenSource(); + rig.OnAct = () => cancellation.Cancel(); + ClosureParticipantGroup[] groups = [new(First, null), new(First, Branch)]; + + var act = () => rig.FanOut.FanOutAsync(TestPlatformAdmissions.Witness(), null, new ClosureFanOutRequest(Person, groups), cancellation.Token); + + await act.Should().ThrowAsync(); + rig.Acts.Should().ContainSingle("the second group is never started once the operator cancelled"); + } + + /// + /// Exactly the closure's group bound, which Begin admits, is fanned out in one call: every group is one act. The bound is + /// the shared constant Begin judges, so no person Begin admits is refused here. + /// + [Fact] + public async Task Exactly_the_closure_s_group_bound_is_fanned_out_in_one_call() + { + using var rig = new Rig(); + ClosureFanOut.MaximumGroups.Should().Be(LearnStack.SharedKernel.DataProtection.ClosureLimits.MaximumParticipantGroups); + var groups = Enumerable.Range(0, ClosureFanOut.MaximumGroups) + .Select(_ => new ClosureParticipantGroup(TenantId.From(Guid.CreateVersion7()), null)).ToArray(); + + var reports = await rig.FanOut.FanOutAsync(TestPlatformAdmissions.Witness(), null, new ClosureFanOutRequest(Person, groups)); + + reports.Should().HaveCount(ClosureFanOut.MaximumGroups).And.OnlyContain(report => report.Outcome == ClosureGroupOutcome.Started); + rig.Acts.Should().HaveCount(ClosureFanOut.MaximumGroups); + } + + [Theory] + [InlineData("system_actor")] + [InlineData("duplicate_group")] + [InlineData("sentinel_tenant")] + [InlineData("too_many_groups")] + public async Task A_request_that_is_not_a_closing_persons_bounded_distinct_groups_is_refused_before_any_act(string variant) + { + using var rig = new Rig(); + var request = variant switch + { + "system_actor" => new ClosureFanOutRequest(UserId.SystemActor, [new(First, null)]), + "duplicate_group" => new ClosureFanOutRequest(Person, [new(First, Branch), new(First, Branch)]), + "sentinel_tenant" => new ClosureFanOutRequest(Person, [new(TenantId.PlatformSentinel, null)]), + _ => new ClosureFanOutRequest(Person, Enumerable.Range(0, ClosureFanOut.MaximumGroups + 1) + .Select(_ => new ClosureParticipantGroup(TenantId.From(Guid.CreateVersion7()), null)).ToArray()), + }; + + var act = () => rig.FanOut.FanOutAsync(TestPlatformAdmissions.Witness(), null, request); + + await act.Should().ThrowAsync(); + rig.Acts.Should().BeEmpty(); +#pragma warning disable CA2012 // NSubstitute checks the call; nothing is awaited. + _ = rig.Gate.DidNotReceiveWithAnyArgs().AdmitAsync(default!, default!, default, default); +#pragma warning restore CA2012 + } + + private sealed record Act(PlatformOperation Operation, TenantId Tenant, OrganizationId? Organization, FanOutClosureCommand Command); + + private sealed class Rig : IDisposable + { + private static readonly DateTimeOffset Now = new(2026, 11, 23, 9, 0, 0, TimeSpan.Zero); + private readonly ServiceProvider _provider; + private int _admissions; + + public Rig() + { + var clock = Substitute.For(); + clock.UtcNow.Returns(Now); +#pragma warning disable CA2012 // NSubstitute configures the call; each execution returns a fresh ValueTask. + Gate.AdmitAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(call => ValueTask.FromResult(RefuseAdmissionAt.Contains(_admissions++) + ? PlatformAdmissionResult.Refuse(PlatformRefusal.MissingPermission) + : PlatformAdmissionResult.Admit(TestPlatformAdmissions.Admission(call.Arg(), call.Arg(), + issuedAt: Now)))); +#pragma warning restore CA2012 + var services = new ServiceCollection(); + services.AddSingleton(Accessor); + services.AddSingleton( + new OperationPolicyCatalog([new TenancyOperationPolicySource(), new IdentityOperationPolicySource()])); + services.AddSingleton(clock); + services.AddSingleton(typeof(ILogger<>), typeof(NullLogger<>)); + services.AddScoped(_ => new OperatorActGuard( + Substitute.For(), Substitute.For(), + Substitute.For(), Substitute.For())); + services.AddPlatformOperatorActs(new PlatformOperatorActCatalog( + [new(typeof(FanOutClosureCommand), new(PlatformOperations.ClosureFanOut))])); + services.AddScoped(_ => + { + var sender = Substitute.For(); + sender.Send(Arg.Any>>(), Arg.Any()).Returns(call => + { + var context = Accessor.Current!; + var command = (FanOutClosureCommand)call.Arg>>(); + var group = new ClosureParticipantGroup(context.TenantId, context.OrganizationId); + Acts.Add(new Act(PlatformOperations.ClosureFanOut, context.TenantId, context.OrganizationId, command)); + OnAct?.Invoke(); + if (Throw.Contains(group)) + return Task.FromException>(new InvalidOperationException("act failed")); + return Task.FromResult(Refuse.Contains(group) + ? Result.Fail(new Error(new LocalizedMessage("lockey_not_found"))) + : Result.Ok(Answer.GetValueOrDefault(group, ClosureGroupOutcome.Started))); + }); + return sender; + }); + _provider = services.BuildServiceProvider(); + FanOut = new ClosureFanOut(Gate, _provider.GetRequiredService(), NullLogger.Instance); + } + + public IPlatformOperatorGate Gate { get; } = Substitute.For(); + + public StaticTenantContextAccessor Accessor { get; } = new(null); + + public ClosureFanOut FanOut { get; } + + public List Acts { get; } = []; + + /// The gate calls, counted from zero in the fan-out's order, that the gate refuses. + public HashSet RefuseAdmissionAt { get; } = []; + + public HashSet Refuse { get; } = []; + + public HashSet Throw { get; } = []; + + public Dictionary Answer { get; } = []; + + public Action? OnAct { get; set; } + + public void Dispose() => _provider.Dispose(); + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Identity/DataErasureDomainTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/DataErasureDomainTests.cs new file mode 100644 index 000000000..1b65d500e --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Identity/DataErasureDomainTests.cs @@ -0,0 +1,201 @@ +using FluentAssertions; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Permissions; +using Xunit; + +namespace LearnStack.Tests.Unit.Identity; + +/// +/// ADR-0107 § 5: the erasure domain operations accept the system actor and any status, are idempotent, run only under a +/// live witness minted from a fulfilling erasure of exactly the row's tenant, group and person, and leave the ordinary +/// methods' rules unchanged. A Revoked tombstone's own row is never stamped, because the database admits no UPDATE of it. +/// +public sealed class DataErasureDomainTests +{ + 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 Branch = OrganizationId.From(Guid.CreateVersion7()); + private static readonly UserId Subject = UserId.From(Guid.CreateVersion7()); + private static readonly UserId Administrator = UserId.From(Guid.CreateVersion7()); + + [Theory] + [InlineData(MembershipStatus.Active)] + [InlineData(MembershipStatus.Suspended)] + public void A_current_Membership_is_erased_to_a_Revoked_tombstone_by_the_system_actor_and_a_second_run_changes_nothing( + MembershipStatus status) + { + var membership = Member(null); + membership.SetProfile("Ada", "en", At, Administrator).IsSuccess.Should().BeTrue(); + if (status == MembershipStatus.Suspended) + { + membership.Suspend(At, Administrator).IsSuccess.Should().BeTrue(); + } + + using var source = new Source(Erasure(null, Subject)); + var witness = source.Mint(); + var later = At.AddDays(2); + + membership.RemoveAssignmentsForErasure(witness, later, UserId.SystemActor).IsSuccess.Should().BeTrue(); + membership.ClearProfileForErasure(witness, later, UserId.SystemActor).IsSuccess.Should().BeTrue(); + membership.RevokeForErasure(witness, later, UserId.SystemActor).IsSuccess.Should().BeTrue(); + + membership.Status.Should().Be(MembershipStatus.Revoked); + membership.UserId.Should().Be(Subject, "the tombstone keeps its pseudonymous person"); + membership.RoleAssignments.Should().BeEmpty(); + membership.Profile.DisplayName.Should().BeNull(); + membership.Profile.PreferredLocale.Should().BeNull(); + membership.Profile.CustomFieldsJson.Should().Be("[]"); + membership.DeletedBy.Should().Be(UserId.SystemActor); + membership.UpdatedBy.Should().Be(UserId.SystemActor); + membership.IsErased.Should().BeTrue(); + + var version = membership.Version; + membership.RemoveAssignmentsForErasure(witness, later.AddMinutes(1), UserId.SystemActor).IsSuccess.Should().BeTrue(); + membership.ClearProfileForErasure(witness, later.AddMinutes(1), UserId.SystemActor).IsSuccess.Should().BeTrue(); + membership.RevokeForErasure(witness, later.AddMinutes(1), UserId.SystemActor).IsSuccess.Should().BeTrue(); + membership.Version.Should().Be(version, "an erased Membership is left exactly as it is"); + membership.UpdatedAt.Should().Be(later); + } + + /// + /// An earlier-revoked Membership keeps its assignments and profile under the ordinary rules; the erasure clears them + /// without touching the tombstone's own row, which the contextual guard admits no UPDATE of. + /// + [Fact] + public void An_earlier_revoked_Membership_loses_its_assignments_and_profile_without_its_root_being_stamped() + { + var membership = Member(Branch); + membership.SetProfile("Ada", "tr", At, Administrator).IsSuccess.Should().BeTrue(); + membership.Revoke(At.AddHours(1), Administrator).IsSuccess.Should().BeTrue(); + membership.SetProfile(null, null, At.AddHours(2), Administrator).IsFailure.Should().BeTrue("the ordinary method keeps its rule"); + var version = membership.Version; + var stamped = (membership.UpdatedAt, membership.UpdatedBy, membership.DeletedAt, membership.DeletedBy); + using var source = new Source(Erasure(Branch, Subject)); + + membership.RemoveAssignmentsForErasure(source.Mint(), At.AddDays(2), UserId.SystemActor).IsSuccess.Should().BeTrue(); + membership.ClearProfileForErasure(source.Mint(), At.AddDays(2), UserId.SystemActor).IsSuccess.Should().BeTrue(); + membership.RevokeForErasure(source.Mint(), At.AddDays(2), UserId.SystemActor).IsSuccess.Should().BeTrue(); + + membership.IsErased.Should().BeTrue(); + membership.Version.Should().Be(version); + (membership.UpdatedAt, membership.UpdatedBy, membership.DeletedAt, membership.DeletedBy).Should().Be(stamped, + "the tombstone records who revoked it; the erasure is on the audit row instead"); + } + + [Theory] + [InlineData("no_witness")] + [InlineData("closed_witness")] + [InlineData("other_person")] + [InlineData("other_group")] + [InlineData("other_tenant")] + [InlineData("request_ended")] + public void Without_a_live_witness_for_exactly_the_rows_person_and_group_nothing_is_erased(string variant) + { + var membership = Member(null); + var erasure = variant switch + { + "other_person" => Erasure(null, Administrator), + "other_group" => Erasure(Branch, Subject), + "other_tenant" => Erasure(null, Subject, TenantId.From(Guid.CreateVersion7())), + _ => Erasure(null, Subject), + }; + var source = new Source(erasure); + var witness = variant == "no_witness" ? null : source.Mint(); + if (variant == "closed_witness") + { + source.Dispose(); + } + + if (variant == "request_ended") + { + erasure.AwaitPrivilegedStep(At.AddDays(2), UserId.SystemActor).IsSuccess.Should().BeTrue(); + } + + membership.RemoveAssignmentsForErasure(witness!, At.AddDays(2), UserId.SystemActor).IsFailure.Should().BeTrue(); + membership.ClearProfileForErasure(witness!, At.AddDays(2), UserId.SystemActor).IsFailure.Should().BeTrue(); + membership.RevokeForErasure(witness!, At.AddDays(2), UserId.SystemActor).IsFailure.Should().BeTrue(); + membership.Status.Should().Be(MembershipStatus.Active); + membership.RoleAssignments.Should().ContainSingle(); + membership.Version.Should().Be(0); + source.Dispose(); + } + + [Theory] + [InlineData(DataRequestKind.Export)] + [InlineData(DataRequestKind.Erasure)] + public void A_witness_is_captured_only_from_a_fulfilling_erasure(DataRequestKind kind) + { + var request = DataSubjectRequest.FileForSelf(DataSubjectRequestId.From(Guid.CreateVersion7()), kind, Subject, + new DataRequestScopeGroup(Tenant, null), [MembershipId.From(Guid.CreateVersion7())], At).Value!; + using var source = new Source(request); + + FluentActions.Invoking(source.Mint).Should().Throw(kind == DataRequestKind.Export + ? "an export never erases" : "a scheduled erasure has not reached its execution yet"); + } + + [Fact] + public void A_pending_invitation_the_subject_issued_is_revoked_with_the_subject_as_its_actor_and_nothing_else_is() + { + using var source = new Source(Erasure(null, Subject)); + var witness = source.Mint(); + var issued = Invite(Subject); + var later = At.AddDays(2); + + issued.RevokeForErasure(witness, later).IsSuccess.Should().BeTrue(); + + issued.Status.Should().Be(InvitationStatus.Revoked); + issued.UpdatedBy.Should().Be(Subject, "the aggregate refuses the system actor, so the subject is its actor"); + issued.VerifierDigest.Should().BeNull("a revoked offer can no longer be accepted"); + var version = issued.Version; + issued.RevokeForErasure(witness, later.AddMinutes(1)).IsSuccess.Should().BeTrue(); + issued.Version.Should().Be(version, "an offer no longer pending changes nothing"); + + var foreign = Invite(Administrator); + foreign.RevokeForErasure(witness, later).IsFailure.Should().BeTrue("another person's offer is not the subject's to erase"); + foreign.Status.Should().Be(InvitationStatus.Pending); + var branch = Invite(Subject, Branch); + branch.RevokeForErasure(witness, later).IsFailure.Should().BeTrue("another group's offer is outside the request"); + branch.Status.Should().Be(InvitationStatus.Pending); + } + + private static DataSubjectRequest Erasure(OrganizationId? organization, UserId subject, TenantId? tenant = null) + { + var request = DataSubjectRequest.FileForSelf(DataSubjectRequestId.From(Guid.CreateVersion7()), DataRequestKind.Erasure, subject, + new DataRequestScopeGroup(tenant ?? Tenant, organization), [MembershipId.From(Guid.CreateVersion7())], At).Value!; + request.StartFulfilling(At + DataRequestLimits.CancellationWindow, UserId.SystemActor).IsSuccess.Should().BeTrue(); + return request; + } + + /// An Active Membership of the subject with one role; a test moves it on itself. + private static Membership Member(OrganizationId? organization) + { + var role = Role.Create(RoleId.From(Guid.CreateVersion7()), Tenant, BuiltInRoleKey.Learner, + organization is null ? PermissionScope.Tenant : PermissionScope.Organization, At, Administrator).Value!; + return Membership.Create(MembershipId.From(Guid.CreateVersion7()), Tenant, organization, Subject, role, At, + Administrator).Value!; + } + + private static Invitation Invite(UserId inviter, OrganizationId? organization = null) + { + var role = Role.Create(RoleId.From(Guid.CreateVersion7()), Tenant, BuiltInRoleKey.Learner, + organization is null ? PermissionScope.Tenant : PermissionScope.Organization, At, inviter).Value!; + return Invitation.Create(InvitationId.From(Guid.CreateVersion7()), Tenant, organization, "recipient@example.invalid", role, + new InvitationDelivery(InvitationGenerationId.From(Guid.CreateVersion7()), BackgroundJobId.From(Guid.CreateVersion7()), + new string('a', 64), "https://manage.school.invalid", "en", 14), At, inviter).Value!; + } + + /// A test minter over one request: live until disposed, like the production source. + private sealed class Source(DataSubjectRequest request) : DataErasureWitness.MintingSource, IDisposable + { + private bool _closed; + + protected override bool IsEvidenceCurrent => !_closed && request.Status == DataRequestStatus.Fulfilling; + + public DataErasureWitness Mint() => Capture(request); + + public void Dispose() => _closed = true; + } +} 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 000000000..68d06d8fe --- /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/DataExportCustodyRefusalsTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/DataExportCustodyRefusalsTests.cs new file mode 100644 index 000000000..426232139 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Identity/DataExportCustodyRefusalsTests.cs @@ -0,0 +1,40 @@ +using FluentAssertions; +using LearnStack.Modules.Identity.Infrastructure.DataRequests; +using Xunit; + +namespace LearnStack.Tests.Unit.Identity; + +/// +/// The custody refusal memory behind the critical-once log of the data export runbook: one critical report per +/// artifact and key label, repeats as warnings, and a bounded memory that forgets rather than grows. +/// +public sealed class DataExportCustodyRefusalsTests +{ + [Fact] + public void The_first_refusal_of_an_artifact_under_a_label_is_reported_once_and_another_pair_is_its_own_first() + { + var refusals = new DataExportCustodyRefusals(); + var artifact = Guid.CreateVersion7(); + + refusals.IsFirst(artifact, "v1").Should().BeTrue(); + refusals.IsFirst(artifact, "v1").Should().BeFalse("every further chunk of the same artifact and label is a repeat"); + refusals.IsFirst(artifact, "v2").Should().BeTrue("another key label is another custody problem"); + refusals.IsFirst(Guid.CreateVersion7(), "v1").Should().BeTrue("another artifact is reported in its own right"); + } + + [Fact] + public void The_memory_is_bounded_and_forgets_everything_when_a_new_pair_would_pass_the_bound() + { + var refusals = new DataExportCustodyRefusals(); + var first = Guid.CreateVersion7(); + refusals.IsFirst(first, "v1").Should().BeTrue(); + for (var index = 1; index < DataExportCustodyRefusals.Capacity; index++) + { + refusals.IsFirst(Guid.CreateVersion7(), "v1").Should().BeTrue(); + } + + refusals.IsFirst(first, "v1").Should().BeFalse("a full memory still knows what it holds"); + refusals.IsFirst(Guid.CreateVersion7(), "v1").Should().BeTrue("a new pair past the bound clears the memory and is remembered"); + refusals.IsFirst(first, "v1").Should().BeTrue("a cleared memory reports an old refusal at critical severity again"); + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Identity/DataExportTelemetryTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/DataExportTelemetryTests.cs new file mode 100644 index 000000000..6e6dd45fe --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Identity/DataExportTelemetryTests.cs @@ -0,0 +1,82 @@ +using System.Collections.Concurrent; +using System.Diagnostics.Metrics; +using FluentAssertions; +using LearnStack.Modules.Identity.Application.DataRequests; +using Xunit; + +namespace LearnStack.Tests.Unit.Identity; + +/// Standard 10: the export workflow's instruments carry one closed outcome label and nothing else. +public sealed class DataExportTelemetryTests +{ + [Fact] + public void Each_export_and_purge_outcome_is_one_closed_label_and_only_a_stored_bundle_records_its_size() + { + var measurements = new ConcurrentQueue<(string Instrument, double Value, string[] Tags)>(); + using var listener = new MeterListener + { + InstrumentPublished = (instrument, meter) => + { + if (instrument.Meter.Name == DataExportTelemetry.MeterName) + { + meter.EnableMeasurementEvents(instrument); + } + }, + }; + listener.SetMeasurementEventCallback((instrument, value, tags, _) => + measurements.Enqueue((instrument.Name, value, [.. Tags(tags)]))); + listener.SetMeasurementEventCallback((instrument, value, tags, _) => + measurements.Enqueue((instrument.Name, value, [.. Tags(tags)]))); + listener.Start(); + + DataExportTelemetry.Export(DataExportOutcome.Completed, TimeSpan.FromSeconds(2), 4_321, 2); + DataExportTelemetry.Export(DataExportOutcome.FailedTooLarge, TimeSpan.FromSeconds(1), 9_999, 1); + DataExportTelemetry.Export(DataExportOutcome.NoOp, TimeSpan.Zero); + DataExportTelemetry.Export(DataExportOutcome.Failed, TimeSpan.Zero); + DataExportTelemetry.Purge(DataExportPurgeOutcome.Purged); + DataExportTelemetry.Purge(DataExportPurgeOutcome.NoOp); + DataExportTelemetry.Purge(DataExportPurgeOutcome.NotDue); + DataExportTelemetry.Purge(DataExportPurgeOutcome.Failed); + + var recorded = measurements.ToList(); + recorded.Where(entry => entry.Instrument == DataExportTelemetry.ExportCounterName).Select(entry => entry.Tags.Single()) + .Should().Equal("outcome=completed", "outcome=failed_too_large", "outcome=noop", "outcome=failed"); + recorded.Where(entry => entry.Instrument == DataExportTelemetry.DurationHistogramName).Select(entry => entry.Value) + .Should().Equal(2d, 1d, 0d, 0d); + recorded.Where(entry => entry.Instrument == DataExportTelemetry.BundleBytesHistogramName) + .Should().ContainSingle("a refused bundle stores nothing and records no size").Which.Value.Should().Be(4_321); + recorded.Where(entry => entry.Instrument == DataExportTelemetry.TruncationCounterName) + .Should().ContainSingle().Which.Value.Should().Be(2); + recorded.Where(entry => entry.Instrument == DataExportTelemetry.PurgeCounterName).Select(entry => entry.Tags.Single()) + .Should().Equal("outcome=purged", "outcome=noop", "outcome=not_due", "outcome=failed"); + recorded.Where(entry => entry.Instrument is DataExportTelemetry.BundleBytesHistogramName or DataExportTelemetry.TruncationCounterName) + .Should().OnlyContain(entry => entry.Tags.Length == 0, "the size and truncations carry no label at all"); + DataExportTelemetry.MeterName.Should().StartWith("learnstack.", "the host subscribes to learnstack.*"); + } + + /// + /// The download counter's two labels are closed words, one per enumeration member and distinct; the service-level + /// recording of each outcome is in DataRequestServiceTests, the one class that mints and reads chunks. + /// + [Fact] + public void Each_download_operation_and_outcome_is_one_distinct_closed_label() + { + Enum.GetValues().Select(DataExportTelemetry.Label).Should().Equal("mint", "chunk"); + Enum.GetValues().Select(DataExportTelemetry.Label) + .Should().Equal("served", "refused", "limit", "custody_failed"); + Enum.GetValues().Select(DataExportTelemetry.Label) + .Should().Equal("purged", "noop", "not_due", "failed"); + DataExportTelemetry.DownloadCounterName.Should().MatchRegex("^learnstack_data_export_[a-z_]+_total$"); + } + + private static List Tags(ReadOnlySpan> tags) + { + var labels = new List(); + foreach (var tag in tags) + { + labels.Add(tag.Key + "=" + tag.Value); + } + + return labels; + } +} 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 000000000..466ad413b --- /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/DataRequestCodecTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/DataRequestCodecTests.cs new file mode 100644 index 000000000..25519856f --- /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 new file mode 100644 index 000000000..0a2e0c0d7 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Identity/DataRequestFulfillmentSchedulerTests.cs @@ -0,0 +1,198 @@ +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, § 7: the fulfilment job of a request's kind and group (an export's at once, an erasure's at the end of +/// its window, a closure's fan-out erasure's at once, a closure's none), 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(Fulfillment(request), CancellationToken.None); + + jobs.Submitted.Should().ContainSingle().Which.Should().Be((key, (object)new DataExportJobParameters(request.Id.Value), (DateTimeOffset?)null)); + } + + [Theory] + [InlineData("tenant", "identity.data_erasure_tenant.v1")] + [InlineData("organization", "identity.data_erasure_organization.v1")] + public async Task A_scheduled_erasure_schedules_the_erasure_definition_of_its_group_at_the_end_of_its_window(string scope, string key) + { + var organization = scope == "tenant" ? (OrganizationId?)null : Organization; + var jobs = new RecordingScheduler(); + var request = Request(DataRequestKind.Erasure, organization); + + await new DataRequestFulfillmentScheduler(jobs, new Context(organization)).SubmitAsync(Fulfillment(request), CancellationToken.None); + + jobs.Submitted.Should().ContainSingle().Which.Should().Be((key, (object)new DataErasureJobParameters(request.Id.Value), + (DateTimeOffset?)(At + DataRequestLimits.CancellationWindow)), "the job is due when the cancellable window ends, never before"); + } + + /// + /// ADR-0107 § 7: a closure has no job. Its execution is the operator's Begin, an act in the platform scope no job holds + /// the authority for, so a scheduled closure is an accepted fulfilment that submits nothing. + /// + [Theory] + [InlineData("tenant")] + [InlineData("organization")] + public async Task A_scheduled_closure_is_accepted_and_submits_no_job(string scope) + { + var organization = scope == "tenant" ? (OrganizationId?)null : Organization; + var jobs = new RecordingScheduler(); + var request = Request(DataRequestKind.Closure, organization); + request.ExecuteAt.Should().Be(At + DataRequestLimits.CancellationWindow); + + await new DataRequestFulfillmentScheduler(jobs, new Context(organization)).SubmitAsync(Fulfillment(request), CancellationToken.None); + + jobs.Submitted.Should().BeEmpty("a closure is executed by the operator's Begin, never by a job"); + } + + /// + /// ADR-0107 § 7: a closure's fan-out erasure is born fulfilling with no window, so its job is enqueued at once, + /// on the producer transaction that created or adopted it, as the erasure definition of its own group. + /// + [Theory] + [InlineData("tenant", "identity.data_erasure_tenant.v1")] + [InlineData("organization", "identity.data_erasure_organization.v1")] + public async Task A_closures_fulfilling_fan_out_erasure_enqueues_the_erasure_definition_of_its_group_now(string scope, string key) + { + var organization = scope == "tenant" ? (OrganizationId?)null : Organization; + var jobs = new RecordingScheduler(); + var request = FanOut(organization); + request.Status.Should().Be(DataRequestStatus.Fulfilling); + + await new DataRequestFulfillmentScheduler(jobs, new Context(organization)).SubmitAsync(Fulfillment(request), CancellationToken.None); + + jobs.Submitted.Should().ContainSingle().Which.Should().Be((key, (object)new DataErasureJobParameters(request.Id.Value), (DateTimeOffset?)null), + "the fan-out's job runs now, never at a window's end"); + } + + [Theory] + [InlineData("other_group")] + [InlineData("fulfilling")] + [InlineData("erasure_without_due_time")] + [InlineData("export_with_due_time")] + [InlineData("closure_without_due_time")] + [InlineData("closure_fulfilling")] + [InlineData("closure_of_another_group")] + [InlineData("fan_out_with_due_time")] + [InlineData("fan_out_of_another_group")] + [InlineData("fan_out_origin_on_a_scheduled_erasure")] + [InlineData("person_erasure_fulfilling")] + public async Task Anything_but_a_requested_export_or_scheduled_erasure_or_closure_or_fulfilling_fan_out_of_the_announced_group_is_a_programming_error( + string variant) + { + var jobs = new RecordingScheduler(); + var request = variant switch + { + "erasure_without_due_time" or "fan_out_origin_on_a_scheduled_erasure" or "person_erasure_fulfilling" => Request(DataRequestKind.Erasure, null), + "closure_without_due_time" or "closure_fulfilling" or "closure_of_another_group" => Request(DataRequestKind.Closure, null), + "fan_out_with_due_time" or "fan_out_of_another_group" => FanOut(null), + _ => Request(DataRequestKind.Export, null), + }; + if (variant == "fulfilling") + { + request.StartFulfilling(At, UserId.SystemActor).IsSuccess.Should().BeTrue(); + } + else if (variant is "closure_fulfilling" or "person_erasure_fulfilling") + { + request.StartFulfilling(At + DataRequestLimits.CancellationWindow, UserId.SystemActor).IsSuccess.Should().BeTrue(); + } + + var context = new Context(variant is "other_group" or "closure_of_another_group" or "fan_out_of_another_group" ? Organization : null); + var fulfillment = variant switch + { + "erasure_without_due_time" or "closure_without_due_time" => Fulfillment(request) with { ExecuteAt = null }, + "export_with_due_time" or "fan_out_with_due_time" => Fulfillment(request) with { ExecuteAt = At }, + // A person's erasure the closure does not own: neither a scheduled one passing as a fan-out, nor a fulfilling + // one passing as anything but its own job's. + "fan_out_origin_on_a_scheduled_erasure" => Fulfillment(request) with { Origin = DataRequestOrigin.ClosureFanout }, + "person_erasure_fulfilling" => Fulfillment(request) with { ExecuteAt = null }, + _ => Fulfillment(request), + }; + + await FluentActions.Awaiting(() => new DataRequestFulfillmentScheduler(jobs, context).SubmitAsync(fulfillment, 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.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(Guid.NewGuid(), due, CancellationToken.None).AsTask()) + .Should().ThrowAsync("an artifact identity is a UUIDv7"); + } + + private static DataRequestFulfillment Fulfillment(DataSubjectRequest request) => + new(request.Id.Value, request.Kind, request.Status, request.Group, request.ExecuteAt, request.Origin); + + private static DataSubjectRequest FanOut(OrganizationId? organization) => + DataSubjectRequest.FanOutErasure(DataSubjectRequestId.From(Guid.CreateVersion7()), UserId.From(Guid.CreateVersion7()), + new DataRequestScopeGroup(Tenant, organization), [MembershipId.From(Guid.CreateVersion7())], At).Value!; + + 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/Identity/DataRequestServiceTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/DataRequestServiceTests.cs new file mode 100644 index 000000000..110b64ee7 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Identity/DataRequestServiceTests.cs @@ -0,0 +1,1198 @@ +using System.Collections.Concurrent; +using System.Diagnostics.Metrics; +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.Refusal = DataRequestInsertion.AlreadyActive; + } + + 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"); + } + + /// + /// ADR-0107 § 7: the request guard refuses a subject whose User is not in the one status the request's origin allows, + /// read under the User fence: a filing admitted while the person was Active and fenced after a closure's Begin, or an + /// administrator's filing for a person whose account is closing. Every kind each role files maps it to the one closed + /// refusal, writes nothing and submits nothing. + /// + [Theory] + [InlineData("export", DataRequestRole.Subject)] + [InlineData("erasure", DataRequestRole.Subject)] + [InlineData("closure", DataRequestRole.Subject)] + [InlineData("export", DataRequestRole.Administrator)] + [InlineData("erasure", DataRequestRole.Administrator)] + public async Task A_subject_the_request_guard_does_not_admit_is_a_closed_refusal_for_every_kind_and_role(string kind, DataRequestRole role) + { + var harness = new Harness(); + harness.Store.Refusal = DataRequestInsertion.SubjectNotAdmitted; + if (role == DataRequestRole.Administrator && kind == "erasure") + { + // An administrator erases only a person whose Membership of the group is Revoked (ADR-0106 § 3). + harness.Store.Current.Remove(Subject); + } + + var caller = harness.Caller(role == DataRequestRole.Subject ? Subject : Administrator, role); + var refused = (kind, role) switch + { + ("export", DataRequestRole.Subject) => await harness.Service.CreateExportAsync(caller, Subject, CancellationToken.None), + ("erasure", DataRequestRole.Subject) => await harness.Service.CreateErasureAsync(caller, Subject, CancellationToken.None), + ("closure", _) => await harness.Service.CreateClosureAsync(caller, Subject, CancellationToken.None), + ("export", _) => await harness.Service.CreateExportForMembershipAsync(caller, SubjectMembership.Value, CancellationToken.None), + _ => await harness.Service.CreateErasureForMembershipAsync(caller, SubjectMembership.Value, CancellationToken.None), + }; + + Code(refused).Should().Be("business_rule_violation"); + refused.Error!.Details!["$"].Single().Key.Should().Be("lockey_subject_not_admitted"); + harness.Store.Requests.Should().BeEmpty(); + harness.Scheduler.Submitted.Should().BeEmpty("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); + } + + /// + /// An administrator's export would withdraw the subject's own readable artifact when it stores its own, so it is + /// refused while the subject holds one in the group, whoever filed it; once that artifact is revoked or expired the + /// administrator may file. The subject's own new export still replaces their previous artifact. + /// + [Theory] + [InlineData(DataRequestOrigin.Self)] + [InlineData(DataRequestOrigin.Administrator)] + public async Task An_administrator_export_is_refused_while_the_subject_holds_a_readable_artifact(DataRequestOrigin earlier) + { + var harness = new Harness(); + var completed = harness.Completed(earlier); + var administrator = harness.Caller(Administrator, DataRequestRole.Administrator); + + var refused = await harness.Service.CreateExportForMembershipAsync(administrator, SubjectMembership.Value, CancellationToken.None); + + Code(refused).Should().Be("business_rule_violation"); + refused.Error!.Details!["$"].Single().Key.Should().Be("lockey_subject_export_available"); + harness.Store.Requests.Should().ContainSingle("nothing was filed").Which.Should().BeSameAs(completed); + harness.Scheduler.Submitted.Should().BeEmpty(); + + (await harness.Service.CreateExportAsync(harness.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None)) + .IsSuccess.Should().BeTrue("the subject's own export replaces their previous artifact"); + harness.Store.Requests.Remove(harness.Store.Requests[^1]); + + // Revoked or past its expiry, the artifact is no longer readable: the administrator may file. + harness.Store.Artifacts[completed.Id] = harness.Store.Artifacts[completed.Id] with { Readable = false }; + (await harness.Service.CreateExportForMembershipAsync(administrator, SubjectMembership.Value, CancellationToken.None)) + .IsSuccess.Should().BeTrue(); + } + + [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"); + } + + /// + /// A subject revokes only an artifact about them: another person's request, named with that artifact's real version, + /// answers exactly as an absent one and purges nothing; the owner's own revocation purges. + /// + [Fact] + public async Task A_subject_revokes_only_an_artifact_about_them_and_another_persons_is_not_found_and_purges_nothing() + { + var harness = new Harness(); + var request = harness.Completed(); + var artifact = harness.Store.Artifacts[request.Id].Artifact; + var other = UserId.From(Guid.CreateVersion7()); + + Code(await harness.Service.RevokeAsync(harness.Caller(other, DataRequestRole.Subject), request.Id.Value, artifact.Version, + CancellationToken.None)).Should().Be("not_found", "another person's artifact is no more reachable than an absent request"); + Code(await harness.Service.RevokeAsync(harness.Caller(Administrator, DataRequestRole.Administrator), request.Id.Value, + artifact.Version, CancellationToken.None)).Should().Be("not_found", "an administrator revokes only an export they filed"); + harness.Artifacts.Purged.Should().BeEmpty("a refused revocation deletes nothing"); + harness.Audit.Designated.Should().NotContain(artifact, "no artifact is named for the audit row of a request the caller does not reach"); + + (await harness.Service.RevokeAsync(harness.Caller(Subject, DataRequestRole.Subject), request.Id.Value, artifact.Version, + CancellationToken.None)).IsSuccess.Should().BeTrue(); + harness.Artifacts.Purged.Should().Equal(artifact.Id.Value); + } + + [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); + } + + /// + /// Ticket and MUST audit rows are permanent, so minting is bounded and a bound reached is its own refusal, + /// data_export_ticket_limit, never the data_export_unavailable of an artifact that is gone: at most + /// three open tickets per session binding (a consumed or expired one frees a slot, and a ticket left open by a + /// credential since refreshed does not block the new one), and at most twenty ever per artifact, which is final. + /// + [Fact] + public async Task Minting_is_bounded_per_session_binding_and_per_artifact_and_a_bound_is_refused_as_ticket_limit() + { + var harness = new Harness(); + var request = harness.Completed(); + var subject = harness.Caller(Subject, DataRequestRole.Subject); + var tickets = new List(); + for (var index = 0; index < DataRequestLimits.MaximumOpenTicketsPerBinding; index++) + { + tickets.Add((await harness.Download.MintTicketAsync(subject, request.Id.Value, CancellationToken.None)).Value!.Ticket); + } + + var refused = await harness.Download.MintTicketAsync(subject, request.Id.Value, CancellationToken.None); + Code(refused).Should().Be("business_rule_violation"); + refused.Error!.Details!["artifact"].Single().Key.Should().Be("lockey_data_export_ticket_limit", + "a bound reached is told apart from an artifact that is gone"); + harness.Store.Tickets.Should().HaveCount(3, "a refused mint stores nothing"); + + // A refreshed credential is another binding: the orphaned open tickets of the old one do not block it. + harness.Sessions.Binding = Binding('b'); + (await harness.Download.MintTicketAsync(subject, request.Id.Value, CancellationToken.None)).IsSuccess.Should().BeTrue(); + harness.Sessions.Binding = Binding('a'); + + // Reading the last chunk consumes the first ticket: one slot of its binding is free again. + (await harness.Download.ReadChunkAsync(subject, request.Id.Value, tickets[0], 1, CancellationToken.None)).IsSuccess.Should().BeTrue(); + (await harness.Download.MintTicketAsync(subject, request.Id.Value, CancellationToken.None)).IsSuccess.Should().BeTrue(); + Code(await harness.Download.MintTicketAsync(subject, request.Id.Value, CancellationToken.None)).Should().Be("business_rule_violation"); + + // Past their fifteen minutes the open tickets no longer count, but every minted ticket does, up to the hard bound. + var bindings = 0; + while (harness.Store.Tickets.Count < DataRequestLimits.MaximumTicketsPerArtifact) + { + harness.Sessions.Binding = (++bindings).ToString("x64", System.Globalization.CultureInfo.InvariantCulture); + (await harness.Download.MintTicketAsync(subject, request.Id.Value, CancellationToken.None)).IsSuccess.Should().BeTrue(); + } + + harness.Store.Now = () => At + DataRequestLimits.TicketLifetime; + harness.Sessions.Binding = Binding('f'); + var final = await harness.Download.MintTicketAsync(subject, request.Id.Value, CancellationToken.None); + final.Error!.Details!["artifact"].Single().Key.Should().Be("lockey_data_export_ticket_limit", + "twenty tickets ever per artifact is final, whatever their state or binding"); + harness.Store.Tickets.Should().HaveCount(DataRequestLimits.MaximumTicketsPerArtifact); + } + + [Fact] + public async Task A_ticket_is_refused_as_unavailable_when_the_ring_no_longer_holds_the_artifacts_key() + { + var harness = new Harness(); + var request = harness.Completed(); + harness.Artifacts.Ring.Clear(); + + var refused = await harness.Download.MintTicketAsync(harness.Caller(Subject, DataRequestRole.Subject), request.Id.Value, + CancellationToken.None); + + refused.Error!.Details!["artifact"].Single().Key.Should().Be("lockey_data_export_unavailable", + "a download that could never be served is refused before any ticket exists"); + harness.Store.Tickets.Should().BeEmpty(); + } + + [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"); + } + + /// + /// Only a stored requested export can be displayed failed, so only its job phase is read: a completed export, or + /// one stored failed or cancelled, never changes and costs no job read. + /// + [Fact] + public async Task Receipts_read_the_job_phase_only_of_stored_requested_exports() + { + var harness = new Harness(); + var completed = harness.Completed(); + await harness.Service.CreateExportAsync(harness.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None); + var requested = harness.Store.Requests.Single(request => request.Status == DataRequestStatus.Requested); + var subject = harness.Caller(Subject, DataRequestRole.Subject); + + (await harness.Service.GetAsync(subject, completed.Id.Value, CancellationToken.None)).IsSuccess.Should().BeTrue(); + harness.Phases.Read.Should().BeEmpty("a completed export's receipt reads no job"); + (await harness.Service.ListAsync(subject, "identity.data_request.list_own", null, 20, CancellationToken.None)).IsSuccess.Should().BeTrue(); + harness.Phases.Read.Should().Equal([requested.Id], "the page reads the phase of its one requested export only"); + + harness.Phases.Read.Clear(); + (await harness.Service.CancelAsync(subject, requested.Id.Value, requested.Version, CancellationToken.None)).IsSuccess.Should().BeTrue(); + (await harness.Service.GetAsync(subject, requested.Id.Value, CancellationToken.None)).Value!.Status.Should().Be("cancelled"); + harness.Phases.Read.Should().BeEmpty("a cancelled export never changes"); + } + + /// + /// A host whose clock lags the one that filed the request still stores the dead export failed: the reconciler stamps + /// its transitions no earlier than the request's own last stamp, which the aggregate and the guard both require. + /// + [Fact] + public async Task The_reconciler_orders_its_transitions_after_the_request_under_a_lagging_clock() + { + 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 lagging = new Harness(harness.Store, harness.Phases); + lagging.Clock.Now = At - TimeSpan.FromMinutes(3); + + (await lagging.Service.CreateExportAsync(lagging.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None)) + .IsSuccess.Should().BeTrue(); + + dead.Status.Should().Be(DataRequestStatus.Failed); + dead.UpdatedAt.Should().Be(At, "stamped at the request's own creation, not the lagging clock"); + } + + /// + /// Standard 10: every mint and chunk read records one download measurement with its closed operation and outcome; + /// a bound is limit, a key the ring no longer holds or a chunk the store cannot open custody_failed. + /// + [Fact] + public async Task Each_mint_and_chunk_read_records_one_closed_download_outcome() + { + var measurements = new ConcurrentQueue(); + using var listener = new MeterListener + { + InstrumentPublished = (instrument, meter) => + { + if (instrument.Meter.Name == DataExportTelemetry.MeterName && instrument.Name == DataExportTelemetry.DownloadCounterName) + { + meter.EnableMeasurementEvents(instrument); + } + }, + }; + listener.SetMeasurementEventCallback((_, value, tags, _) => + { + var labels = new List(); + foreach (var tag in tags) + { + labels.Add(tag.Key + "=" + tag.Value); + } + + measurements.Enqueue(value + ":" + string.Join(",", labels.Order(StringComparer.Ordinal))); + }); + listener.Start(); + 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; + await harness.Download.MintTicketAsync(subject, request.Id.Value, CancellationToken.None); + await harness.Download.MintTicketAsync(subject, request.Id.Value, CancellationToken.None); + await harness.Download.MintTicketAsync(subject, request.Id.Value, CancellationToken.None); + await harness.Download.MintTicketAsync(harness.Caller(Administrator, DataRequestRole.Administrator), request.Id.Value, + CancellationToken.None); + await harness.Download.ReadChunkAsync(subject, request.Id.Value, ticket, 0, CancellationToken.None); + await harness.Download.ReadChunkAsync(subject, request.Id.Value, ticket, 7, CancellationToken.None); + harness.Artifacts.Unopenable = true; + await harness.Download.ReadChunkAsync(subject, request.Id.Value, ticket, 1, CancellationToken.None); + harness.Artifacts.Ring.Clear(); + await harness.Download.MintTicketAsync(subject, request.Id.Value, CancellationToken.None); + listener.Dispose(); + + measurements.Should().Equal( + "1:operation=mint,outcome=served", "1:operation=mint,outcome=served", "1:operation=mint,outcome=served", + "1:operation=mint,outcome=limit", "1:operation=mint,outcome=refused", + "1:operation=chunk,outcome=served", "1:operation=chunk,outcome=refused", "1:operation=chunk,outcome=custody_failed", + "1:operation=mint,outcome=custody_failed"); + } + + [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_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.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); + } + + /// + /// ADR-0106 § 11, ADR-0107 § 2: an erasure is filed scheduled, its execution time the end of the 24-hour window, and its + /// job is submitted on the creation's transaction due exactly then; the fences are the export's. + /// + [Fact] + public async Task A_subject_files_an_erasure_scheduled_for_the_end_of_its_window_and_its_job_is_due_then() + { + var harness = new Harness(); + + var result = await harness.Service.CreateErasureAsync(harness.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None); + + result.IsSuccess.Should().BeTrue(); + var request = harness.Store.Requests.Should().ContainSingle().Subject; + request.Kind.Should().Be(DataRequestKind.Erasure); + request.Status.Should().Be(DataRequestStatus.Scheduled); + request.ExecuteAt.Should().Be(At + DataRequestLimits.CancellationWindow); + harness.Scheduler.Fulfillments.Should().ContainSingle().Which.Should().Be(new DataRequestFulfillment(request.Id.Value, + DataRequestKind.Erasure, DataRequestStatus.Scheduled, request.Group, At + DataRequestLimits.CancellationWindow, + DataRequestOrigin.Self)); + harness.Locks.Acquired.Should().ContainSingle().Which.UserIds.Should().Equal(Subject); + harness.Locks.Acquired[0].TenantMode.Should().Be(IdentityTenantLockMode.Shared); + harness.Audit.Designated.Should().Contain(request); + + var second = await harness.Service.CreateErasureAsync(harness.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None); + second.Error!.Details!["$"].Single().Key.Should().Be("lockey_request_already_active", "one active erasure per subject and group"); + (await harness.Service.CreateExportAsync(harness.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None)) + .IsSuccess.Should().BeTrue("the one-active rule is per kind"); + } + + /// + /// ADR-0106 § 3: an administrator erases only a person whose Membership of the group is Revoked; a working member is + /// revoked first by the separately audited act. Never for themselves, never as the subject's own role. + /// + [Fact] + public async Task An_administrator_erases_only_a_person_whose_Membership_of_the_group_is_revoked() + { + var harness = new Harness(); + var caller = harness.Caller(Administrator, DataRequestRole.Administrator); + + var working = await harness.Service.CreateErasureForMembershipAsync(caller, SubjectMembership.Value, CancellationToken.None); + Code(working).Should().Be("business_rule_violation"); + working.Error!.Details!["$"].Single().Key.Should().Be("lockey_subject_membership_current"); + Code(await harness.Service.CreateErasureForMembershipAsync(caller, AdministratorMembership.Value, CancellationToken.None)) + .Should().Be("business_rule_violation", "an administrator never files for themselves"); + Code(await harness.Service.CreateErasureForMembershipAsync(caller, Guid.CreateVersion7(), CancellationToken.None)) + .Should().Be("not_found"); + Code(await harness.Service.CreateErasureForMembershipAsync(harness.Caller(Subject, DataRequestRole.Subject), + SubjectMembership.Value, CancellationToken.None)).Should().Be("forbidden"); + harness.Store.Requests.Should().BeEmpty(); + harness.Scheduler.Submitted.Should().BeEmpty(); + + harness.Store.Current.Remove(Subject); + (await harness.Service.CreateErasureForMembershipAsync(caller, SubjectMembership.Value, CancellationToken.None)).IsSuccess.Should().BeTrue(); + var request = harness.Store.Requests.Should().ContainSingle().Subject; + request.Kind.Should().Be(DataRequestKind.Erasure); + request.Origin.Should().Be(DataRequestOrigin.Administrator); + request.RequesterUserId.Should().Be(Administrator); + request.SubjectUserId.Should().Be(Subject); + } + + /// + /// ADR-0106 § 7: a refusal at creation is a response and writes nothing: the subject as the tenant's only eligible + /// tenant-wide administrator, and a hold. An export is never refused for the administrator rule. + /// + [Theory] + [InlineData("sole_administrator", "lockey_blocked_last_administrator")] + [InlineData("hold", "lockey_blocked_hold")] + public async Task An_erasure_refused_at_creation_answers_its_closed_code_and_files_nothing(string variant, string reason) + { + var harness = new Harness(hold: variant == "hold"); + if (variant == "sole_administrator") + { + harness.Store.SoleAdministrators.Add(Subject); + } + + var refused = await harness.Service.CreateErasureAsync(harness.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None); + + Code(refused).Should().Be("business_rule_violation"); + refused.Error!.Details!["$"].Single().Key.Should().Be(reason); + harness.Store.Requests.Should().BeEmpty(); + harness.Scheduler.Submitted.Should().BeEmpty(); + if (variant == "sole_administrator") + { + (await harness.Service.CreateExportAsync(harness.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None)) + .IsSuccess.Should().BeTrue("the administrator rule is the erasure's alone"); + } + } + + /// + /// ADR-0106 § 8: a scheduled erasure whose job died is shown failed at once, and stored failed by the next creation once + /// its execution time has passed; before then the aggregate and the guard admit no start, so it keeps its slot. + /// + [Fact] + public async Task A_dead_erasure_job_is_shown_failed_and_stored_failed_only_once_its_window_has_ended() + { + var harness = new Harness(); + await harness.Service.CreateErasureAsync(harness.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None); + var dead = harness.Store.Requests.Single(); + harness.Phases.Phase[dead.Id] = DataRequestJobPhase.Dead; + + var view = (await harness.Service.GetAsync(harness.Caller(Subject, DataRequestRole.Subject), dead.Id.Value, CancellationToken.None)).Value!; + view.Status.Should().Be("failed"); + view.FailureReason.Should().Be("execution_failed"); + view.ExecuteAt.Should().Be(At + DataRequestLimits.CancellationWindow); + + var early = new Harness(harness.Store, harness.Phases); + early.Clock.Now = At.AddHours(1); + var refused = await early.Service.CreateErasureAsync(early.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None); + refused.Error!.Details!["$"].Single().Key.Should().Be("lockey_request_already_active"); + dead.Status.Should().Be(DataRequestStatus.Scheduled, "a scheduled erasure cannot start, so cannot fail, before its window ends"); + + var due = new Harness(harness.Store, harness.Phases); + due.Clock.Now = At + DataRequestLimits.CancellationWindow + TimeSpan.FromMinutes(1); + (await due.Service.CreateErasureAsync(due.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None)) + .IsSuccess.Should().BeTrue(); + dead.Status.Should().Be(DataRequestStatus.Failed); + dead.FailureReason.Should().Be(DataRequestFailureReason.ExecutionFailed); + due.Store.Requests.Should().HaveCount(2); + } + + /// + /// ADR-0106 § 7, ADR-0107 § 7: a closure is judged here only at its creation, by the structure of its originating group + /// and the hold port: a Membership of any status, one active closure per subject and group, and no hold. It is never + /// refused for the last administrator, which its Begin judges across every participant tenant; for the same reason its + /// execution is not answered here at all, rather than called eligible. + /// + [Fact] + public async Task Eligibility_judges_a_closure_at_creation_by_its_group_and_hold_and_refuses_to_judge_its_execution() + { + var store = new Store(); + store.SoleAdministrators.Add(Subject); + var context = new Context(Subject); + var group = new DataRequestScopeGroup(Tenant, null); + DataRequestEligibilityQuery Closure(UserId subject, DataRequestEligibilityStage stage = DataRequestEligibilityStage.Creation, Guid? id = null) => + new(DataRequestKind.Closure, DataRequestOrigin.Self, subject, group, stage, id); + var eligibility = new DataRequestEligibility(store, new NoHoldSource(), context); + + (await eligibility.EvaluateAsync(Closure(Subject), CancellationToken.None)).IsEligible + .Should().BeTrue("the tenant's only eligible administrator may file: the last-administrator check is the Begin's"); + (await eligibility.EvaluateAsync(Closure(UserId.From(Guid.CreateVersion7())), CancellationToken.None)).Reason + .Should().Be(DataRequestIneligibility.NoMembership); + (await new DataRequestEligibility(store, new FixedHold(), context).EvaluateAsync(Closure(Subject), CancellationToken.None)).Reason + .Should().Be(DataRequestIneligibility.BlockedHold); + + var erasure = DataSubjectRequest.FileForSelf(DataSubjectRequestId.From(Guid.CreateVersion7()), DataRequestKind.Erasure, Subject, group, + [SubjectMembership], At).Value!; + store.Requests.Add(erasure); + (await eligibility.EvaluateAsync(Closure(Subject), CancellationToken.None)).IsEligible + .Should().BeTrue("the one-active rule is per kind"); + var closure = DataSubjectRequest.FileForSelf(DataSubjectRequestId.From(Guid.CreateVersion7()), DataRequestKind.Closure, Subject, group, + [SubjectMembership], At).Value!; + store.Requests.Add(closure); + (await eligibility.EvaluateAsync(Closure(Subject), CancellationToken.None)).Reason + .Should().Be(DataRequestIneligibility.RequestAlreadyActive); + + await FluentActions.Awaiting(() => eligibility.EvaluateAsync(Closure(Subject, DataRequestEligibilityStage.Execution, closure.Id.Value), + CancellationToken.None)).Should().ThrowAsync("a closure's execution is its Begin's, across every participant tenant"); + } + + /// + /// ADR-0106 § 11, ADR-0107 § 7: the person files a closure scheduled, its execution time the end of the 24-hour window, + /// under the creation fences, and its fulfilment is the scheduler's explicit no-job case; one active closure per subject + /// and group, and it does not conflict with the person's erasure. + /// + [Fact] + public async Task A_subject_files_a_closure_scheduled_for_the_end_of_its_window_under_the_creation_fences() + { + var harness = new Harness(); + (await harness.Service.CreateErasureAsync(harness.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None)) + .IsSuccess.Should().BeTrue(); + var fresh = new Harness(harness.Store, harness.Phases); + + var result = await fresh.Service.CreateClosureAsync(fresh.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None); + + result.IsSuccess.Should().BeTrue("a closure and an erasure of the same group are different kinds"); + var request = fresh.Store.Requests.Should().ContainSingle(item => item.Kind == DataRequestKind.Closure).Subject; + result.Value!.RequestId.Should().Be(request.Id.Value); + request.Origin.Should().Be(DataRequestOrigin.Self); + request.RequesterUserId.Should().Be(Subject); + request.SubjectUserId.Should().Be(Subject); + request.Status.Should().Be(DataRequestStatus.Scheduled); + request.ExecuteAt.Should().Be(At + DataRequestLimits.CancellationWindow); + request.SnapshotMembershipIds.Should().Equal(SubjectMembership); + fresh.Scheduler.Fulfillments.Should().ContainSingle().Which.Should().Be(new DataRequestFulfillment(request.Id.Value, + DataRequestKind.Closure, DataRequestStatus.Scheduled, request.Group, At + DataRequestLimits.CancellationWindow, + DataRequestOrigin.Self)); + fresh.Locks.Acquired.Should().ContainSingle().Which.UserIds.Should().Equal(Subject); + fresh.Locks.Acquired[0].TenantMode.Should().Be(IdentityTenantLockMode.Shared); + fresh.Audit.Designated.Should().ContainSingle().Which.Should().BeSameAs(request); + fresh.Rechecks.Should().Be(1, "authority is re-evaluated once the fences are held"); + + var second = await fresh.Service.CreateClosureAsync(fresh.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None); + second.Error!.Details!["$"].Single().Key.Should().Be("lockey_request_already_active", "one active closure per subject and group"); + } + + /// + /// ADR-0106 § 3, ADR-0107 § 7: the person alone files a closure. An administrator's caller is refused before a fence + /// or a row is read, also for a subject who is not the administrator; the subject never files for another person. + /// + [Fact] + public async Task An_administrator_never_files_a_closure_and_a_subject_files_only_their_own() + { + var harness = new Harness(); + + Code(await harness.Service.CreateClosureAsync(harness.Caller(Administrator, DataRequestRole.Administrator), Subject, CancellationToken.None)) + .Should().Be("forbidden"); + Code(await harness.Service.CreateClosureAsync(harness.Caller(Administrator, DataRequestRole.Administrator), Administrator, + CancellationToken.None)).Should().Be("forbidden"); + harness.Locks.Acquired.Should().BeEmpty("the refusal precedes every fence"); + harness.Rechecks.Should().Be(0); + + Code(await harness.Service.CreateClosureAsync(harness.Caller(Subject, DataRequestRole.Subject), Administrator, CancellationToken.None)) + .Should().Be("business_rule_violation", "a person files a closure only for themselves"); + harness.Store.Requests.Should().BeEmpty(); + harness.Scheduler.Submitted.Should().BeEmpty(); + } + + /// + /// ADR-0106 § 7, ADR-0107 § 7: a closure's creation refusals are a response and write nothing: a hold, an active closure + /// and no Membership in the group. The tenant's only eligible administrator still files: that check is the Begin's. + /// + [Theory] + [InlineData("hold", "lockey_blocked_hold")] + [InlineData("no_membership", null)] + [InlineData("sole_administrator", null)] + public async Task A_closure_refused_at_creation_answers_its_closed_code_and_files_nothing(string variant, string? reason) + { + var harness = new Harness(hold: variant == "hold"); + harness.Store.SoleAdministrators.Add(Subject); + var person = variant == "no_membership" ? UserId.From(Guid.CreateVersion7()) : Subject; + + var result = await harness.Service.CreateClosureAsync(harness.Caller(person, DataRequestRole.Subject), person, CancellationToken.None); + + if (variant == "sole_administrator") + { + result.IsSuccess.Should().BeTrue("the last-administrator check is the Begin's, across every participant tenant"); + harness.Store.Requests.Should().ContainSingle().Which.Kind.Should().Be(DataRequestKind.Closure); + return; + } + + Code(result).Should().Be(reason is null ? "not_found" : "business_rule_violation"); + if (reason is not null) + { + result.Error!.Details!["$"].Single().Key.Should().Be(reason); + } + + harness.Store.Requests.Should().BeEmpty(); + harness.Scheduler.Submitted.Should().BeEmpty(); + } + + /// + /// ADR-0106 § 3, § 8, § 11: the subject cancels a scheduled closure before and after its execution time, until its Begin + /// commits; once it is fulfilling no cancellation is admitted. An administrator neither reads nor cancels it, and its + /// receipt never reads a job's phase, so a closure is never shown failed. + /// + [Fact] + public async Task A_closure_is_cancellable_until_its_Begin_and_unreachable_to_an_administrator() + { + var harness = new Harness(); + await harness.Service.CreateClosureAsync(harness.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None); + var request = harness.Store.Requests.Single(); + harness.Phases.Phase[request.Id] = DataRequestJobPhase.Dead; + var administrator = harness.Caller(Administrator, DataRequestRole.Administrator); + + Code(await harness.Service.GetAsync(administrator, request.Id.Value, CancellationToken.None)).Should().Be("not_found"); + Code(await harness.Service.CancelAsync(administrator, request.Id.Value, 0, CancellationToken.None)).Should().Be("not_found"); + Code(await harness.Service.ReadReceiptAsync(administrator, request.Id.Value, CancellationToken.None)).Should().Be("not_found"); + + var view = (await harness.Service.GetAsync(harness.Caller(Subject, DataRequestRole.Subject), request.Id.Value, CancellationToken.None)).Value!; + view.Kind.Should().Be("closure"); + view.Status.Should().Be("scheduled", "a closure has no job, so no job phase makes it failed"); + view.ExecuteAt.Should().Be(At + DataRequestLimits.CancellationWindow); + harness.Phases.Read.Should().NotContain(request.Id); + + harness.Clock.Now = At + DataRequestLimits.CancellationWindow + TimeSpan.FromHours(1); + var cancelled = await harness.Service.CancelAsync(harness.Caller(Subject, DataRequestRole.Subject), request.Id.Value, 0, CancellationToken.None); + cancelled.IsSuccess.Should().BeTrue("a closure stays cancellable after its execution time until its Begin commits"); + request.Status.Should().Be(DataRequestStatus.Cancelled); + + var begun = new Harness(new Store(), harness.Phases); + await begun.Service.CreateClosureAsync(begun.Caller(Subject, DataRequestRole.Subject), Subject, CancellationToken.None); + var started = begun.Store.Requests.Single(); + started.StartFulfilling(At + DataRequestLimits.CancellationWindow, UserId.SystemActor).IsSuccess.Should().BeTrue(); + var refused = await begun.Service.CancelAsync(begun.Caller(Subject, DataRequestRole.Subject), started.Id.Value, started.Version, + CancellationToken.None); + refused.Error!.Details!["$"].Single().Key.Should().Be("lockey_data_request_not_cancellable"); + started.Status.Should().Be(DataRequestStatus.Fulfilling); + } + + /// ADR-0106 § 7: an erasure of an organization group is never refused for the tenant-wide administrator rule. + [Fact] + public async Task Eligibility_asks_the_administrator_rule_only_of_a_tenant_wide_erasure() + { + var branch = OrganizationId.From(Guid.CreateVersion7()); + var store = new Store(); + store.SoleAdministrators.Add(Subject); + var tenantWide = new DataRequestEligibility(store, new NoHoldSource(), new Context(Subject)); + var organization = new DataRequestEligibility(store, new NoHoldSource(), new Context(Subject, branch)); + + (await tenantWide.EvaluateAsync(new DataRequestEligibilityQuery(DataRequestKind.Erasure, DataRequestOrigin.Self, Subject, + new DataRequestScopeGroup(Tenant, null), DataRequestEligibilityStage.Creation), CancellationToken.None)) + .Reason.Should().Be(DataRequestIneligibility.BlockedLastAdministrator); + (await organization.EvaluateAsync(new DataRequestEligibilityQuery(DataRequestKind.Erasure, DataRequestOrigin.Self, Subject, + new DataRequestScopeGroup(Tenant, branch), DataRequestEligibilityStage.Creation), CancellationToken.None)) + .IsEligible.Should().BeTrue("an organization's group holds no tenant-wide administrator Membership"); + (await tenantWide.EvaluateAsync(new DataRequestEligibilityQuery(DataRequestKind.Export, DataRequestOrigin.Self, Subject, + new DataRequestScopeGroup(Tenant, null), DataRequestEligibilityStage.Creation), CancellationToken.None)) + .IsEligible.Should().BeTrue("an export removes nobody"); + } + + 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, OrganizationId? organization = null) : ITenantContext + { + public bool IsResolved => true; + public TenantContextOrigin? Origin => TenantContextOrigin.HostAndClaim; + public TenantId TenantId => Tenant; + public OrganizationId? OrganizationId => organization; + 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 DataRequestInsertion? Refusal { 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> 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 HoldsCompletedFanOutAsync(UserId subject, CancellationToken cancellationToken) => + Task.FromResult(Requests.Any(request => request.SubjectUserId == subject && request.Kind == DataRequestKind.Erasure + && request.Origin == DataRequestOrigin.ClosureFanout && request.Status == DataRequestStatus.Completed)); + + 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 (Refusal is { } refusal) + { + return Task.FromResult(refusal); + } + + Requests.Add(request); + return Task.FromResult(DataRequestInsertion.Added); + } + + 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) + .Select(request => DataRequestReceiptRow.From(request) is var row && subject is null ? row : row with { MembershipSnapshotJson = null }) + .ToList()); + + public Task CountAsync(DataExportArtifactId artifactId, string sessionBindingDigest, + CancellationToken cancellationToken) => + Task.FromResult(new DataExportTicketCounts( + Tickets.Count(ticket => ticket.ArtifactId == artifactId && ticket.SessionBindingDigest == sessionBindingDigest + && ticket.ConsumedAt is null && ticket.ExpiresAt > Now()), + Tickets.Count(ticket => ticket.ArtifactId == artifactId))); + + public Task HoldsReadableArtifactAsync(UserId subject, CancellationToken cancellationToken) => + Task.FromResult(Artifacts.Values.Any(row => row.Readable && row.Artifact.SubjectUserId == subject)); + + /// The people who hold an Active or Suspended Membership of the group; both fixtures do by default. + public HashSet Current { get; } = [Subject, Administrator]; + + /// The people the group's tenant has as its only eligible tenant-wide administrator. + public HashSet SoleAdministrators { get; } = []; + + public Task HoldsCurrentMembershipAsync(UserId subject, CancellationToken cancellationToken) => + Task.FromResult(Current.Contains(subject)); + + public Task IsSoleEligibleTenantAdministratorAsync(UserId subject, CancellationToken cancellationToken) => + Task.FromResult(SoleAdministrators.Contains(subject)); + + public Task HoldsErasureFencesAsync(UserId subject, CancellationToken cancellationToken) => + throw new NotSupportedException("Only the erasure job's participant observes the fences."); + + public Func Now { get; set; } = () => At; + + 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; } = []; + + /// Every request whose phase a page or receipt read, in order. + public List Read { get; } = []; + + public Task ReadAsync(DataSubjectRequestId requestId, DataRequestKind kind, CancellationToken cancellationToken) => + Task.FromResult(kind is DataRequestKind.Export or DataRequestKind.Erasure + ? Phase.GetValueOrDefault(requestId, DataRequestJobPhase.Pending) : DataRequestJobPhase.Unavailable); + + public Task> ReadManyAsync( + IReadOnlyCollection requestIds, DataRequestKind kind, CancellationToken cancellationToken) + { + Read.AddRange(requestIds); + return Task.FromResult>( + requestIds.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 List Fulfillments { get; } = []; + + public ValueTask SubmitAsync(DataRequestFulfillment fulfillment, CancellationToken cancellationToken) + { + Submitted.Add(DataSubjectRequestId.From(fulfillment.RequestId)); + Fulfillments.Add(fulfillment); + 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 HashSet Ring { get; } = new(StringComparer.Ordinal) { "v1" }; + + /// The store answers every chunk as absent, as it does for a chunk it cannot open. + public bool Unopenable { get; set; } + + public bool CanOpen(string keyVersion) => Ring.Contains(keyVersion); + + 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) + { + if (Unopenable) + { + return Task.FromResult(null); + } + + var bytes = Enumerable.Repeat((byte)(index + 1), 16).ToArray(); + Served.Add(bytes); + return Task.FromResult(new DataExportPlaintextChunk(index, 2, bytes)); + } + + /// Every artifact the service asked the store to purge. + public List Purged { get; } = []; + + public Task PurgeAsync(DataExportArtifactLocator artifact, DataExportArtifactStatus outcome, + CancellationToken cancellationToken) + { + Purged.Add(artifact.ArtifactId); + return 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/backend/tests/LearnStack.Tests.Unit/Identity/DataRequestStorageLiteralTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/DataRequestStorageLiteralTests.cs new file mode 100644 index 000000000..71e0fef9d --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Identity/DataRequestStorageLiteralTests.cs @@ -0,0 +1,376 @@ +using System.Globalization; +using System.Reflection; +using FluentAssertions; +using LearnStack.Infrastructure.DataProtection; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Xunit; + +namespace LearnStack.Tests.Unit.Identity; + +/// +/// The storage of ADR-0106 and ADR-0107 repeats as SQL literals, and classifies the +/// receipt columns: both are read here from the real model and DDL, so a constant changed on one side fails the build +/// instead of drifting. +/// +public sealed class DataRequestStorageLiteralTests +{ + private const string ModelOnly = "Host=model-only;Database=model-only;Username=model-only"; + + [Fact] + public void Every_bound_the_checks_repeat_is_the_shared_constant() + { + using var identity = Identity(); + var model = identity.GetService().Model; + var invariant = CultureInfo.InvariantCulture; + + Check(model, typeof(DataExportArtifact), "ck_data_export_artifacts_size").Should().Be(string.Format(invariant, + "byte_count BETWEEN 1 AND {0} AND chunk_count BETWEEN 1 AND {1} AND chunk_count = (byte_count + {2}) / {3}", + DataRequestLimits.MaximumBundleBytes, DataRequestLimits.MaximumChunkCount, DataRequestLimits.ChunkPlaintextBytes - 1, + DataRequestLimits.ChunkPlaintextBytes)); + Check(model, typeof(DataExportArtifact), "ck_data_export_artifacts_times").Should().Contain(string.Format(invariant, + "expires_at = created_at + interval '{0} days'", DataRequestLimits.ArtifactLifetime.TotalDays)); + Check(model, typeof(DataExportArtifact), "ck_data_export_artifacts_key_version").Should().Contain(string.Format(invariant, + "{{1,{0}}}", DataRequestLimits.MaximumKeyVersionLength)); + var truncation = Check(model, typeof(DataExportArtifact), "ck_data_export_artifacts_truncation"); + truncation.Should().Contain(string.Format(invariant, "<= {0}", DataRequestLimits.MaximumTruncatedCollections)) + .And.Contain(DataRequestLimits.MaximumTruncationCount.ToString(invariant)) + .And.Contain(string.Format(invariant, "{{0,{0}}}", DataRequestLimits.MaximumParticipantKeyLength - 1)) + .And.Contain(string.Format(invariant, "{{0,{0}}}", DataRequestLimits.MaximumCollectionNameLength - 1)); + Check(model, typeof(DataExportTicket), "ck_data_export_tickets_times").Should().Contain(string.Format(invariant, + "expires_at = created_at + interval '{0} minutes'", DataRequestLimits.TicketLifetime.TotalMinutes)); + Check(model, typeof(DataSubjectRequest), "ck_data_subject_requests_window").Should().Contain(string.Format(invariant, + "execute_at = created_at + interval '{0} hours'", DataRequestLimits.CancellationWindow.TotalHours)); + Check(model, typeof(DataSubjectRequest), "ck_data_subject_requests_snapshot").Should().Contain(string.Format(invariant, + "BETWEEN 1 AND {0}", DataRequestLimits.MaximumSnapshotMemberships)); + Check(model, typeof(DataSubjectRequest), "ck_data_subject_requests_progress").Should() + .Contain(string.Format(invariant, "<= {0}", DataRequestLimits.MaximumParticipants)) + .And.Contain(string.Format(invariant, "{{0,{0}}}", DataRequestLimits.MaximumParticipantKeyLength - 1)); + Check(model, typeof(DataSubjectRequest), "ck_data_subject_requests_result").Should() + .Contain(DataRequestLimits.MaximumTruncationCount.ToString(invariant)); + + var chunks = Ddl("ChunkTable"); + chunks.Should().Contain(string.Format(invariant, "chunk_index >= 0 AND chunk_index < {0}", DataRequestLimits.MaximumChunkCount)) + .And.Contain(string.Format(invariant, "octet_length(nonce) = {0}", DataRequestLimits.NonceBytes)) + .And.Contain(string.Format(invariant, "octet_length(tag) = {0}", DataRequestLimits.TagBytes)) + .And.Contain(string.Format(invariant, "octet_length(ciphertext) BETWEEN 1 AND {0}", DataRequestLimits.ChunkPlaintextBytes)); + } + + [Theory] + [InlineData(nameof(DataSubjectRequest), nameof(DataSubjectRequest.ResultJson))] + [InlineData(nameof(DataExportArtifact), nameof(DataExportArtifact.ByteCount))] + [InlineData(nameof(DataExportArtifact), nameof(DataExportArtifact.ChunkCount))] + [InlineData(nameof(DataExportArtifact), nameof(DataExportArtifact.TruncationJson))] + public void The_receipts_counts_and_sizes_are_audit_records_of_the_person(string entity, string property) + { + using var identity = Identity(); + var type = entity == nameof(DataSubjectRequest) ? typeof(DataSubjectRequest) : typeof(DataExportArtifact); + + identity.Model.FindEntityType(type)!.FindProperty(property)!.FindAnnotation(PersonalDataClassificationExtensions.CategoryAnnotation)! + .Value.Should().Be(PersonalDataCategory.Audit, + "how many of a person's records a group holds, and how large their bundle is, describe the person"); + } + + [Fact] + public void The_platform_arm_precedes_the_application_arms_which_stay_byte_for_byte_those_of_Step_1() + { + const string End = "END $guard$;"; + const string ApplicationArms = " IF (session_user <> 'learnstack_app'"; + var original = Ddl("RequestGuard"); + var replaced = Ddl("RequestGuard", "DataRequestOperatorDdl"); + original = original[..(original.IndexOf(End, StringComparison.Ordinal) + End.Length)]; + replaced = replaced[..(replaced.IndexOf(End, StringComparison.Ordinal) + End.Length)]; + + replaced.Should().StartWith("CREATE OR REPLACE FUNCTION public.fn_identity_data_request_guard() RETURNS trigger"); + var header = original[..original.IndexOf(ApplicationArms, StringComparison.Ordinal)]; + var applicationArms = original[original.IndexOf(ApplicationArms, StringComparison.Ordinal)..]; + var platformArm = replaced[ + (header.Length + "OR REPLACE ".Length)..replaced.IndexOf(ApplicationArms, StringComparison.Ordinal)]; + replaced.Should().Be(header.Replace("CREATE FUNCTION", "CREATE OR REPLACE FUNCTION", StringComparison.Ordinal) + + platformArm + applicationArms, + "the function's header and every application arm are Step 1's, character for character, after the platform arm"); + platformArm.Should().Contain("IF session_user = 'learnstack_platform' AND current_user = 'learnstack_platform' THEN") + .And.Contain("OLD.kind = 'erasure' AND OLD.origin <> 'closure_fanout' AND OLD.status = 'awaiting_privileged_step'") + .And.Contain("NEW.status = 'completed'") + .And.EndWith(" RETURN NEW;\n END IF;\n", "the arm returns before the application's arms are reached"); + + // The result may change only in the audit log's retained kinds (ADR-0107 § 6): each list the arm names is exactly + // those four codes of the closed vocabulary. + var auditKinds = new[] + { + RetainedReferenceKind.AuditActorReference, RetainedReferenceKind.AuditEntityReference, + RetainedReferenceKind.AuditMetadataReference, RetainedReferenceKind.UnscopedAuditRows, + }.Select(DataRequestCodes.RetainedKinds.ToCode).Order(StringComparer.Ordinal); + var lists = System.Text.RegularExpressions.Regex.Matches(platformArm, @"ARRAY\[(?[^\]]+)\]"); + lists.Should().HaveCount(2); + foreach (System.Text.RegularExpressions.Match list in lists) + { + list.Groups["codes"].Value.Split(',').Select(code => code.Trim().Trim('\'')).Order(StringComparer.Ordinal) + .Should().Equal(auditKinds); + } + } + + /// + /// Step 1's INSERT arm refused every request born fulfilling and read no User. Step 3 admits exactly one born + /// fulfilling, a closure's fan-out erasure, and admits every request only for a subject in the status its origin + /// allows (ADR-0107 § 7). This block is the whole of the change to the application arms. + /// + private const string Step1InitialState = """ + -- A request is never born fulfilling until a closure's fan-out has its own witness (ADR-0107 § 7): such a row + -- would stand in for the erasure the profile clearing of a Revoked Membership requires, with no window. + 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 NULL 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; + + """; + + private const string ClosureInitialState = """ + -- A request is born fulfilling only as a closure's fan-out erasure, with no window and no requester + -- (ADR-0107 § 7): such a row stands in for the erasure the profile clearing of a Revoked Membership requires. + 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.origin = 'closure_fanout' AND (NEW.kind IS DISTINCT FROM 'erasure' OR NEW.execute_at IS NOT NULL + OR NEW.requester_user_id IS NOT NULL)) + 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 subject is admitted in the one status its origin allows, read here under the User fence held above: + -- Closing for a closure's fan-out, Active for every other request (ADR-0107 § 7). A filing admitted while + -- the person was Active and fenced only after a Begin or a Finalize committed inserts nothing. + IF (public.fn_identity_user_status(NEW.subject_user_id) + IS DISTINCT FROM (CASE WHEN NEW.origin = 'closure_fanout' THEN 'Closing' ELSE 'Active' END)) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request subject is not admitted.' USING ERRCODE = '23514'; END IF; + + """; + + [Fact] + public void The_closure_guard_keeps_Step_1_s_application_arms_but_for_the_one_INSERT_witness_block() + { + const string End = "END $guard$;"; + const string ApplicationArms = " IF (session_user <> 'learnstack_app'"; + var original = Ddl("RequestGuard"); + var closure = Ddl("RequestGuard", "AccountClosureStorageDdl"); + original = original[..(original.IndexOf(End, StringComparison.Ordinal) + End.Length)]; + closure = closure[..(closure.IndexOf(End, StringComparison.Ordinal) + End.Length)]; + + var header = original[..original.IndexOf(ApplicationArms, StringComparison.Ordinal)]; + var applicationArms = original[original.IndexOf(ApplicationArms, StringComparison.Ordinal)..]; + var before = Step1InitialState.ReplaceLineEndings("\n"); + var after = ClosureInitialState.ReplaceLineEndings("\n"); + applicationArms.IndexOf(before, StringComparison.Ordinal).Should().BeGreaterThan(0) + .And.Be(applicationArms.LastIndexOf(before, StringComparison.Ordinal), "Step 1's initial-state block is replaced exactly once"); + closure.Should().StartWith("CREATE OR REPLACE FUNCTION public.fn_identity_data_request_guard() RETURNS trigger"); + var platformArm = closure[(header.Length + "OR REPLACE ".Length)..closure.IndexOf(ApplicationArms, StringComparison.Ordinal)]; + closure.Should().Be(header.Replace("CREATE FUNCTION", "CREATE OR REPLACE FUNCTION", StringComparison.Ordinal) + + platformArm + applicationArms.Replace(before, after, StringComparison.Ordinal), + "the header and every application arm are Step 1's, character for character, but for the INSERT arm's one block"); + + // The platform arm: the erasure completion of Step 2 and the closure's four arrows, then its return. + platformArm.Should().Contain("IF session_user = 'learnstack_platform' AND current_user = 'learnstack_platform' THEN") + .And.Contain("OLD.kind = 'erasure' AND OLD.origin <> 'closure_fanout' AND OLD.status = 'awaiting_privileged_step'") + .And.Contain("OLD.kind = 'closure' AND OLD.status = 'scheduled' AND NEW.status = 'scheduled'") + .And.Contain("OLD.kind = 'closure' AND OLD.status = 'scheduled' AND NEW.status = 'fulfilling'") + .And.Contain("OLD.kind = 'closure' AND OLD.status = 'fulfilling' AND NEW.status = 'completed'") + .And.Contain("OLD.kind = 'erasure' AND OLD.origin = 'closure_fanout' AND OLD.status = 'awaiting_privileged_step'") + .And.EndWith(" RETURN NEW;\n END IF;\n", "the arm returns before the application's arms are reached"); + + // The refusal record takes exactly the closed refusal codes. + var refusals = System.Text.RegularExpressions.Regex.Match(platformArm, @"NEW\.last_refusal NOT IN \((?[^)]+)\)"); + refusals.Success.Should().BeTrue(); + refusals.Groups["codes"].Value.Split(',').Select(code => code.Trim().Trim('\'')).Order(StringComparer.Ordinal).Should() + .Equal(Enum.GetValues().Select(DataRequestCodes.Refusals.ToCode).Order(StringComparer.Ordinal)); + + // The result changes only in the audit log's four retained kinds (ADR-0107 § 6), and a closure's Finalize also in + // the unserved groups: three arrows each name their list twice, and only Finalize's names the unserved kind. + var auditKinds = new[] + { + RetainedReferenceKind.AuditActorReference, RetainedReferenceKind.AuditEntityReference, + RetainedReferenceKind.AuditMetadataReference, RetainedReferenceKind.UnscopedAuditRows, + }.Select(DataRequestCodes.RetainedKinds.ToCode).Order(StringComparer.Ordinal).ToArray(); + var finalizeKinds = auditKinds.Append(DataRequestCodes.RetainedKinds.ToCode(RetainedReferenceKind.UnservedGroup)) + .Order(StringComparer.Ordinal).ToArray(); + var lists = System.Text.RegularExpressions.Regex.Matches(platformArm, @"ARRAY\[(?[^\]]+)\]") + .Select(list => list.Groups["codes"].Value.Split(',').Select(code => code.Trim().Trim('\'')).Order(StringComparer.Ordinal).ToArray()) + .ToArray(); + lists.Should().HaveCount(6); + lists.Count(list => list.SequenceEqual(auditKinds)).Should().Be(4); + lists.Count(list => list.SequenceEqual(finalizeKinds)).Should().Be(2); + + // Begin and Finalize require the same participant fences as the users trigger exception: every tenant of a + // Membership of any status, read on the writing connection. + const string Participants = "GROUP BY member.tenant_id\n"; + const string Held = "HAVING public.fn_identity_lock_held('tenant', member.tenant_id, true) IS NOT TRUE"; + CountOf(platformArm, Participants).Should().Be(2); + CountOf(platformArm, Held).Should().Be(2); + var users = Ddl("UserGuard", "AccountClosureStorageDdl"); + CountOf(users, Participants).Should().Be(1); + CountOf(users, Held).Should().Be(1); + } + + /// + /// A1's Finalize arm, as 20261123100000_admit_account_closure applied it: a closure completes from + /// fulfilling only. + /// + private const string BegunClosureCompletion = """ + ELSIF OLD.kind = 'closure' AND OLD.status = 'fulfilling' AND NEW.status = 'completed' THEN + -- A closure's Finalize (ADR-0107 § 7, ADR-0108 § 8): with the subject already Closed, under the fences + -- of Begin. The result records the redaction's four audit kinds and the unserved groups, nothing else. + + """; + + /// + /// The same arm as 20261123120000_admit_closure_finalize replaces it: a closure of the subject that was never + /// begun completes too, under exactly the same witnesses, because the arm's body is unchanged. + /// + private const string EveryOpenClosureCompletion = """ + ELSIF OLD.kind = 'closure' AND OLD.status IN ('scheduled', 'fulfilling') AND NEW.status = 'completed' THEN + -- A closure's Finalize (ADR-0107 § 7, ADR-0108 § 8): with the subject already Closed, under the fences + -- of Begin, the closure it finalizes from fulfilling and every other closure of the subject from where + -- it stands, begun or not. The result records the redaction's four audit kinds and the unserved groups, + -- nothing else. + + """; + + [Fact] + public void The_Finalize_guard_is_the_closure_guard_but_for_the_one_arm_condition_that_admits_a_never_begun_closure() + { + const string End = "END $guard$;"; + var closure = Ddl("RequestGuard", "AccountClosureStorageDdl"); + var finalize = Ddl("FinalizeRequestGuard", "AccountClosureStorageDdl"); + closure = closure[..(closure.IndexOf(End, StringComparison.Ordinal) + End.Length)]; + finalize = finalize[..(finalize.IndexOf(End, StringComparison.Ordinal) + End.Length)]; + var before = BegunClosureCompletion.ReplaceLineEndings("\n"); + var after = EveryOpenClosureCompletion.ReplaceLineEndings("\n"); + + CountOf(closure, before).Should().Be(1, "A1's arm is replaced exactly once"); + finalize.Should().Be(closure.Replace(before, after, StringComparison.Ordinal), + "every arm, every witness and the application's arms are A1's, character for character, but for the one condition"); + CountOf(finalize, "NEW.status = 'completed'").Should().Be(CountOf(closure, "NEW.status = 'completed'"), + "no arm is added: the never-begun closure takes the Finalize arm's own witnesses"); + Ddl("FinalizeGrants", "AccountClosureStorageDdl").Trim().Should().Be( + "GRANT SELECT (updated_at) ON public.data_subject_requests TO learnstack_platform;", + "the platform role gains the request's update stamp, a begun closure's Begin moment, and nothing else"); + } + + /// The INSERT arm's status witness as the closure guard and its Finalize replacement place it, before the snapshot. + private const string StatusBeforeSnapshot = """ + -- The subject is admitted in the one status its origin allows, read here under the User fence held above: + -- Closing for a closure's fan-out, Active for every other request (ADR-0107 § 7). A filing admitted while + -- the person was Active and fenced only after a Begin or a Finalize committed inserts nothing. + IF (public.fn_identity_user_status(NEW.subject_user_id) + IS DISTINCT FROM (CASE WHEN NEW.origin = 'closure_fanout' THEN 'Closing' ELSE 'Active' END)) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request subject is not admitted.' USING ERRCODE = '23514'; END IF; + + """; + + private const string SnapshotEnd = """ + THEN RAISE EXCEPTION 'Data request snapshot refused.' USING ERRCODE = '23514'; END IF; + + """; + + /// The same witness as the hardening places it, after the snapshot, so no refusal message reveals a status. + private const string StatusAfterSnapshot = """ + -- The subject is admitted in the one status its origin allows, read here under the User fence held above: + -- Closing for a closure's fan-out, Active for every other request (ADR-0107 § 7). A filing admitted while + -- the person was Active and fenced only after a Begin or a Finalize committed inserts nothing. It is asked + -- after the snapshot, so a refused snapshot says nothing about the subject's status. + IF (public.fn_identity_user_status(NEW.subject_user_id) + IS DISTINCT FROM (CASE WHEN NEW.origin = 'closure_fanout' THEN 'Closing' ELSE 'Active' END)) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request subject is not admitted.' USING ERRCODE = '23514'; END IF; + + """; + + private const string TerminalCheck = """ + IF (OLD.status IN ('completed','blocked','failed','cancelled')) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request is terminal.' USING ERRCODE = '23514'; END IF; + + """; + + /// The application UPDATE arm's one new refusal: a closure is the application's only while it is scheduled. + private const string ClosureIsTheApplicationsOnlyWhileScheduled = """ + -- A closure is the application's only while it is scheduled (ADR-0107 § 7): the person cancels it, and once it + -- leaves scheduled every write of its row is the platform's arrows, so its Begin moment, its result and its + -- version change only as Finalize reads them. + IF (OLD.kind = 'closure' AND NOT (OLD.status = 'scheduled' AND NEW.status IN ('scheduled','cancelled'))) IS NOT FALSE + THEN RAISE EXCEPTION 'Data request transition refused.' USING ERRCODE = '23514'; END IF; + + """; + + /// + /// 20261123130000_harden_closure_request_guard: the guard Finalize installed but for exactly two changes to the + /// application arms. The INSERT arm's status witness moves after the snapshot check, and the UPDATE arm gains one + /// refusal right after the terminal check, so a closure the platform made fulfilling takes no application write. + /// Every platform arrow, every other witness and every message is Finalize's, character for character. + /// + [Fact] + public void The_hardened_guard_is_the_Finalize_guard_but_for_the_status_witness_s_place_and_the_closure_s_application_arm() + { + const string End = "END $guard$;"; + var finalize = Ddl("FinalizeRequestGuard", "AccountClosureStorageDdl"); + var hardened = Ddl("HardenedRequestGuard", "AccountClosureStorageDdl"); + finalize = finalize[..(finalize.IndexOf(End, StringComparison.Ordinal) + End.Length)]; + hardened = hardened[..(hardened.IndexOf(End, StringComparison.Ordinal) + End.Length)]; + var statusBefore = StatusBeforeSnapshot.ReplaceLineEndings("\n"); + var snapshotEnd = SnapshotEnd.ReplaceLineEndings("\n"); + var statusAfter = StatusAfterSnapshot.ReplaceLineEndings("\n"); + var terminal = TerminalCheck.ReplaceLineEndings("\n"); + var closureArm = ClosureIsTheApplicationsOnlyWhileScheduled.ReplaceLineEndings("\n"); + + CountOf(finalize, statusBefore).Should().Be(1, "Finalize's guard asks the status once, before the snapshot"); + CountOf(finalize, snapshotEnd).Should().Be(1); + CountOf(finalize, terminal).Should().Be(1); + var expected = finalize.Replace(statusBefore, string.Empty, StringComparison.Ordinal) + .Replace(snapshotEnd, snapshotEnd + statusAfter, StringComparison.Ordinal) + .Replace(terminal, terminal + closureArm, StringComparison.Ordinal); + hardened.Should().Be(expected, + "every arm, witness and message is Finalize's, character for character, but for the witness's place and the one refusal"); + hardened.IndexOf("'Data request snapshot refused.'", StringComparison.Ordinal).Should().BeLessThan( + hardened.IndexOf("'Data request subject is not admitted.'", StringComparison.Ordinal), + "a refused snapshot is answered before the status is asked, so its message reveals no status"); + var platformArm = hardened[..hardened.IndexOf(" IF (session_user <> 'learnstack_app'", StringComparison.Ordinal)]; + platformArm.Should().NotContain(closureArm.Trim(), "the new refusal is the application's arm alone"); + DdlMethodSql("InstallHardening").Should().Equal([Ddl("HardenedRequestGuard", "AccountClosureStorageDdl")], + "the hardening's migration replaces the guard and changes nothing else"); + } + + /// The statements an AccountClosureStorageDdl installer hands the migration builder, in order. + private static List DdlMethodSql(string method) + { + var builder = new Microsoft.EntityFrameworkCore.Migrations.MigrationBuilder("Npgsql.EntityFrameworkCore.PostgreSQL"); + typeof(IdentityDbContext).Assembly + .GetType("LearnStack.Modules.Identity.Infrastructure.Persistence.AccountClosureStorageDdl", throwOnError: true)! + .GetMethod(method, BindingFlags.Static | BindingFlags.NonPublic)!.Invoke(null, [builder]); + return [.. builder.Operations.Cast().Select(operation => operation.Sql)]; + } + + private static int CountOf(string text, string value) => + System.Text.RegularExpressions.Regex.Count(text, System.Text.RegularExpressions.Regex.Escape(value)); + + private static string Check(IModel model, Type entity, string name) => + model.FindEntityType(entity)!.GetCheckConstraints().SingleOrDefault(check => check.Name == name)?.Sql + ?? throw new InvalidOperationException("The constraint is not in the model: " + name); + + private static string Ddl(string name, string type = "DataRequestStorageDdl") => (string)typeof(IdentityDbContext).Assembly + .GetType("LearnStack.Modules.Identity.Infrastructure.Persistence." + type, throwOnError: true)! + .GetField(name, BindingFlags.Static | BindingFlags.NonPublic)!.GetRawConstantValue()!; + + private static IdentityDbContext Identity() => new(new DbContextOptionsBuilder().UseNpgsql(ModelOnly).Options, + StaticTenantContextAccessor.Unresolved, EmptyIdentityScope.Instance); +} 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 000000000..37ed98ab5 --- /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/Identity/OwnDataRequestPolicyTests.cs b/backend/tests/LearnStack.Tests.Unit/Identity/OwnDataRequestPolicyTests.cs new file mode 100644 index 000000000..a34cba7f9 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Identity/OwnDataRequestPolicyTests.cs @@ -0,0 +1,521 @@ +using FluentAssertions; +using LearnStack.Application.Audit; +using LearnStack.Application.Authorization; +using LearnStack.Infrastructure.Audit; +using LearnStack.Modules.Identity.Application; +using LearnStack.Modules.Identity.Application.Authorization; +using LearnStack.Modules.Identity.Application.Contracts.Authorization; +using LearnStack.Modules.Identity.Application.Contracts.DataRequests; +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 CreateOwnDataExportCommand()); + + 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 CreateOwnDataExportCommand()); + + 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 CreateOwnDataExportCommand()); + + result.IsFailure.Should().BeTrue(); + result.Error.Should().BeSameAs(TenantContextFactory.Refused); + if (label == "retained-origin") + await rig.Reader.DidNotReceive().ReadAsync(Arg.Any(), Arg.Any()); + } + + /// + /// The arm is pinned to the ten live request types and their own ids: a type outside the set under a well-formed + /// identity.data_request. id, and a live type under another id, are not covered although the Membership is. + /// + [Theory] + [InlineData("probe-type-prefixed-id")] + [InlineData("live-type-foreign-id")] + public async Task Own_data_request_admits_only_its_ten_live_types_under_their_own_ids(string label) + { + using var rig = new Rig(TenantContextOrigin.HostAndClaim, Branch); + rig.Reader.ReadAsync(Arg.Any(), Arg.Any()) + .Returns(new IdentityAuthorizationResult(IdentityAuthorizationOutcome.Covered, Actor, Tenant, Branch, + [new AuthorizationMembershipFacts(Member, Branch, [])])); + + var result = label == "probe-type-prefixed-id" + ? await rig.RunAsync(new CreateProbe()) + : await rig.RunAsync(new ListOwnDataRequestsQuery(null, 20)); + + result.IsFailure.Should().BeTrue(); + result.Error.Should().BeSameAs(TenantContextFactory.Refused); + new IdentityOperationPolicySource().Policies.Where(policy => policy.Kind == OperationPolicyKind.OwnDataRequest) + .Should().HaveCount(10, "the production catalog registers exactly the pinned set"); + (await rig.RunAsync(new CreateOwnDataExportCommand())).IsSuccess.Should().BeTrue("the pinned type under its own id is admitted"); + } + + // ---- 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 CreateOwnDataExportCommand()); + + 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.ForOwnDataRequest(IdentityOperationPolicySource.OwnDataExportCreateOperation), + OperationPolicy.ForOwnDataRequest("identity.data_request.list_probe"), + 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/backend/tests/LearnStack.Tests.Unit/Infrastructure/Audit/AuditRedactionExecutorTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Audit/AuditRedactionExecutorTests.cs new file mode 100644 index 000000000..ec13c4bde --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Audit/AuditRedactionExecutorTests.cs @@ -0,0 +1,221 @@ +using System.Data; +using System.Data.Common; +using System.Diagnostics.CodeAnalysis; +using FluentAssertions; +using LearnStack.Api.Composition; +using LearnStack.Infrastructure.Audit; +using LearnStack.Modules.Customization.Infrastructure.DataRequests; +using LearnStack.Modules.Education.Infrastructure.DataRequests; +using LearnStack.Modules.Identity.Infrastructure.DataRequests; +using LearnStack.Modules.Tenancy.Infrastructure.DataRequests; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Hosting; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Platform; +using LearnStack.Tests.Fixtures; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Xunit; + +namespace LearnStack.Tests.Unit.Infrastructure.Audit; + +/// +/// ADR-0108 §§ 1–2: the executor's refusals, each before any statement, and the API composition's one registration of it +/// over every module's locator. The statements themselves are proved against PostgreSQL by the integration canaries. +/// +public sealed class AuditRedactionExecutorTests +{ + private static readonly AuditRedactionExecutor Executor = new([new IdentityUserReferenceLocator(), new TenancyUserReferenceLocator(), + new CustomizationUserReferenceLocator(), new EducationUserReferenceLocator()]); + + private static readonly AuditRedactionPlan Erasure = Plan(DataRequestKind.Erasure); + + private static readonly AuditRedactionPlan ClosureTenant = AuditRedactionPlan.ForClosureTenant( + TenantId.From(Guid.CreateVersion7()), UserId.From(Guid.CreateVersion7()), [Guid.CreateVersion7(), Guid.CreateVersion7()]); + + private static readonly AuditRedactionPlan ClosureSentinel = AuditRedactionPlan.ForClosureSentinel( + UserId.From(Guid.CreateVersion7()), IdentitySubjectKey.FromBytes(new byte[32])); + + private static readonly Type[] Locators = + [ + typeof(IdentityUserReferenceLocator), typeof(TenancyUserReferenceLocator), + typeof(CustomizationUserReferenceLocator), typeof(EducationUserReferenceLocator), + ]; + + [Fact] + public async Task Only_the_sanctioned_operation_over_an_erasure_plan_is_admitted() + { + foreach (var operation in PlatformOperations.All.Where(operation => !ReferenceEquals(operation, PlatformOperations.ErasureComplete))) + { + await Refused(Erasure, Spent(operation), new StatementlessConnection(), SanctionRefusal, operation.AuditSlug); + } + + // The closure's Finalize is the other redacting operation, and still not this plan's. + await Refused(Erasure, Spent(PlatformOperations.ClosureFinalize), new StatementlessConnection(), SanctionRefusal, + "an erasure's plan is redacted only by its own privileged step, never by a closure's Finalize"); + + // The pairing admitted, the next check refuses: the sanction let it through. + await Refused(Erasure, Spent(PlatformOperations.ErasureComplete), new StatementlessConnection(), ConnectionRefusal, + "complete_erasure redacts an erasure's plan"); + } + + [Fact] + public async Task Only_the_closure_s_finalize_over_a_closure_pass_is_admitted() + { + // ADR-0107 § 7, ADR-0108 § 4: a closure's tenant and sentinel passes are the Finalize's alone; complete_erasure, + // the other redacting operation, is refused them like every other. + foreach (var (name, plan) in new[] { ("tenant pass", ClosureTenant), ("sentinel pass", ClosureSentinel) }) + { + foreach (var operation in PlatformOperations.All.Where(operation => !ReferenceEquals(operation, PlatformOperations.ClosureFinalize))) + { + await Refused(plan, Spent(operation), new StatementlessConnection(), SanctionRefusal, name + " under " + operation.AuditSlug); + } + + await Refused(plan, Spent(PlatformOperations.ClosureFinalize), new StatementlessConnection(), ConnectionRefusal, + "the closure's Finalize redacts its " + name); + } + } + + [Fact] + public async Task An_admission_no_scope_spent_is_refused_and_spent() + { + var admission = TestPlatformAdmissions.Admission(PlatformOperations.ErasureComplete); + + await Refused(Erasure, admission, new StatementlessConnection(), "*platform scope its admission opened*", + "the scope spends the admission it was opened with"); + + admission.TryConsume().Should().BeFalse("a refused unspent admission cannot open a scope afterwards"); + } + + [Fact] + public async Task A_connection_that_is_not_the_scopes_open_platform_connection_is_refused() + { + await Refused(Erasure, Spent(PlatformOperations.ErasureComplete), new StatementlessConnection(), + ConnectionRefusal, "the executor runs on the platform scope's Npgsql connection"); + } + + [Fact] + public async Task An_external_job_frame_is_refused() + { + using (JobApplicationSourceOwner.EnterExternal()) + { + await Refused(Erasure, Spent(PlatformOperations.ErasureComplete), new StatementlessConnection(), + "*refuses another acquisition or activation*", "an operator act never runs in an external job frame"); + } + } + + [Fact] + public void An_export_or_a_closure_request_is_never_a_request_redaction_plan() + { + FluentActions.Invoking(() => Plan(DataRequestKind.Export)).Should().Throw(); + FluentActions.Invoking(() => Plan(DataRequestKind.Closure)).Should().Throw( + "a closure's redaction is its Finalize's tenant and sentinel passes, never its one request's"); + } + + [Fact] + public void The_executor_refuses_to_exist_without_a_declaration() + { + FluentActions.Invoking(() => new AuditRedactionExecutor([])).Should().Throw(); + } + + [Fact] + public async Task The_api_composition_registers_one_executor_over_every_module_locator() + { + var builder = WebApplication.CreateBuilder([]); + builder.Configuration.Sources.Clear(); + builder.Configuration.AddInMemoryCollection(InvitationEmailFixtureConfiguration.Values); + builder.Configuration.AddInMemoryCollection(new Dictionary + { + ["ConnectionStrings:OutboxDispatcher"] = "Host=localhost;Port=1;Database=learnstack;Username=learnstack_outbox_admin;Maximum Pool Size=54", + }); + builder.AddLearnStackCrossCuttingFoundation(DeploymentMode.Development, + typeof(LearnStack.Modules.Tenancy.Application.AssemblyMarker).Assembly, + typeof(LearnStack.Modules.Customization.Application.AssemblyMarker).Assembly, + typeof(LearnStack.Modules.Education.Application.AssemblyMarker).Assembly); + builder.Services.AddLearnStackPersistence(builder.Configuration); + + builder.Services.Where(descriptor => descriptor.ServiceType == typeof(IAuditRedactor)).Should().ContainSingle() + .Which.Lifetime.Should().Be(ServiceLifetime.Singleton); + await using var services = builder.Services.BuildServiceProvider(); + services.GetRequiredService().Should().BeOfType(); + services.GetServices().Select(locator => locator.GetType()).Should().BeEquivalentTo(Locators); + } + + /// The refusal of an act that names an operation, or a plan, the sanctioned list does not pair. + private const string SanctionRefusal = "*does not name an operation that may redact*"; + + /// The refusal of the check after the sanction: a pairing that reaches it was admitted. + private const string ConnectionRefusal = "*open connection and its work transaction*"; + + /// Expects the named refusal, so a test cannot pass on a later check that also refuses. + /// + /// This proves which check refuses, not that no statement ran: the executor builds its NpgsqlCommands itself and + /// would never ask this double for one. That nothing runs before a refusal is proved against PostgreSQL by + /// AuditRedactionCanaryTests.A_refused_admission_or_plan_runs_no_statement (the transaction's JIT setting and + /// rows unchanged, and the same transaction still usable). + /// + private static async Task Refused(AuditRedactionPlan plan, PlatformAdmission admission, StatementlessConnection connection, + string message, string because) => + await FluentActions.Awaiting(() => Executor.RedactAsync(plan, admission, connection, connection.Transaction)) + .Should().ThrowAsync(because).WithMessage(message); + + private static PlatformAdmission Spent(PlatformOperation operation) + { + var admission = TestPlatformAdmissions.Admission(operation); + admission.TryConsume().Should().BeTrue(); + return admission; + } + + private static AuditRedactionPlan Plan(DataRequestKind kind) => + new(new UserDataSubject(Guid.CreateVersion7(), kind, DataRequestOrigin.Self, UserId.From(Guid.CreateVersion7()), + new DataRequestScopeGroup(TenantId.From(Guid.CreateVersion7()), null), [Guid.CreateVersion7()])); + + /// An open connection that is not the platform scope's: it runs nothing. + [SuppressMessage("Reliability", "CA2213:Disposable fields should be disposed", Justification = "The transaction owns nothing.")] + private sealed class StatementlessConnection : DbConnection + { + public StatementlessConnection() => Transaction = new StatementlessTransaction(this); + + public DbTransaction Transaction { get; } + + [AllowNull] + public override string ConnectionString { get; set; } = string.Empty; + + public override string Database => "statementless"; + + public override string DataSource => "statementless"; + + public override string ServerVersion => "18"; + + public override ConnectionState State => ConnectionState.Open; + + public override void ChangeDatabase(string databaseName) => throw new NotSupportedException(); + + public override void Close() + { + } + + public override void Open() + { + } + + protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) => throw new NotSupportedException(); + + protected override DbCommand CreateDbCommand() => throw new NotSupportedException("A refusal runs no statement."); + } + + private sealed class StatementlessTransaction(DbConnection connection) : DbTransaction + { + public override IsolationLevel IsolationLevel => IsolationLevel.ReadCommitted; + + protected override DbConnection DbConnection => connection; + + public override void Commit() => throw new NotSupportedException(); + + public override void Rollback() => throw new NotSupportedException(); + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/DataProtection/AttributionReferenceCounterTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/DataProtection/AttributionReferenceCounterTests.cs new file mode 100644 index 000000000..8b4d804f6 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/DataProtection/AttributionReferenceCounterTests.cs @@ -0,0 +1,77 @@ +using FluentAssertions; +using LearnStack.Infrastructure.DataProtection; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.Modules.Tenancy.Domain; +using LearnStack.Modules.Tenancy.Infrastructure.Persistence; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.EntityFrameworkCore; +using Xunit; + +namespace LearnStack.Tests.Unit.Infrastructure.DataProtection; + +/// +/// ADR-0107 § 6: which columns attribution_reference reads, derived from the model; the database proof of the +/// row unit is DataExportParticipantTests. +/// +public sealed class AttributionReferenceCounterTests +{ + [Fact] + public void Every_UserId_column_of_a_tenant_owned_entity_is_attribution_unless_named_a_party() + { + using var identity = Identity(); + var plan = AttributionReferenceCounter.Plan(identity.Model, new HashSet { typeof(DataSubjectRequest) }, + [(typeof(Membership), nameof(Membership.UserId)), (typeof(Invitation), nameof(Invitation.InviterUserId)), + (typeof(Invitation), nameof(Invitation.AcceptedBy))]).ToDictionary(entry => entry.Entity, entry => entry.Properties); + + plan[typeof(Membership)].Should().Equal("CreatedBy", "DeletedBy", "UpdatedBy"); + plan[typeof(Invitation)].Should().Equal("CreatedBy", "DeletedBy", "UpdatedBy"); + plan[typeof(DataExportTicket)].Should().Equal(["CreatedBy"], "a non-AuditableEntity CreatedBy is attribution too"); + plan[typeof(FederationConnection)].Should().Contain(["PendingActor", "TestActor"], "a party not named is counted"); + plan.Should().NotContainKey(typeof(DataSubjectRequest), "an excluded type is reported under its own kind"); + plan.Keys.Should().OnlyContain(type => typeof(LearnStack.SharedKernel.Persistence.ITenantOwned).IsAssignableFrom(type), + "global rows are not a tenant group's"); + + using var tenancy = new TenancyDbContext(new DbContextOptionsBuilder().UseNpgsql(ModelOnly).Options, + StaticTenantContextAccessor.Unresolved); + var settings = AttributionReferenceCounter.Plan(tenancy.Model, new HashSet { typeof(MembershipFieldConsent) }, null) + .ToDictionary(entry => entry.Entity, entry => entry.Properties); + settings[typeof(TenantFeatureFlag)].Should().Equal(["UpdatedBy"], "an updater outside the AuditableEntity set is attribution"); + settings.Should().NotContainKey(typeof(MembershipFieldConsent)); + } + + [Fact] + public void A_receipt_row_is_the_persons_whichever_UserId_column_names_them() + { + using var identity = Identity(); + var plan = AttributionReferenceCounter.NamingPlan(identity.Model, + [typeof(DataExportTicket), typeof(DataSubjectRequest), typeof(DataExportArtifact)]) + .ToDictionary(entry => entry.Entity, entry => entry.Properties); + + plan[typeof(DataSubjectRequest)].Should().Equal(["CreatedBy", "DeletedBy", "RequesterUserId", "SubjectUserId", "UpdatedBy"], + "an administrator who filed or cancelled a request about someone else is named by it too"); + plan[typeof(DataExportArtifact)].Should().Equal(["CreatedBy", "DeletedBy", "SubjectUserId", "UpdatedBy"], + "an administrator who revoked an artifact is named by it"); + plan[typeof(DataExportTicket)].Should().Equal(["CreatedBy"]); + FluentActions.Invoking(() => AttributionReferenceCounter.NamingPlan(identity.Model, [typeof(string)])) + .Should().Throw("a named receipt type that is not mapped is a programming error"); + } + + [Theory] + [InlineData("Membership", "Missing")] + [InlineData("Membership", "TenantId")] + [InlineData("DataSubjectRequest", "SubjectUserIdTypo")] + public void A_party_that_is_not_a_mapped_UserId_column_is_a_programming_error(string entity, string property) + { + using var identity = Identity(); + var type = entity == "Membership" ? typeof(Membership) : typeof(DataSubjectRequest); + + FluentActions.Invoking(() => AttributionReferenceCounter.Plan(identity.Model, null, [(type, property)])) + .Should().Throw("an exclusion cannot silently go stale"); + } + + private const string ModelOnly = "Host=model-only;Database=model-only;Username=model-only"; + + private static IdentityDbContext Identity() => new(new DbContextOptionsBuilder().UseNpgsql(ModelOnly).Options, + StaticTenantContextAccessor.Unresolved, EmptyIdentityScope.Instance); +} 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 000000000..7816d309d --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/DataProtection/DataExportCipherTests.cs @@ -0,0 +1,325 @@ +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)); + + // The refusal names the setting and its environment spelling so an operator knows what to supply, and nothing + // of the value: no label, no key, not which rule it broke. + var refused = act.Should().Throw() + .WithMessage("Data export custody unavailable: the setting DataExport:KeyRing (environment DataExport__KeyRing) is absent or malformed.*") + .Which; + refused.InnerException.Should().BeNull(); + if (secret is not null) + { + foreach (var fragment in new[] { "k1", "k9", "%%%", Convert.ToBase64String(Key(1)), "legacy", "other" }) + refused.Message.Should().NotContain(fragment); + } + } + + /// + /// A secret provider that fails to answer is its own failure: the startup refusal names a ring that is absent or + /// malformed, so it must not be raised for a ring that was never read. + /// + [Fact] + public void A_secret_provider_failure_propagates_unchanged_and_is_not_reported_as_a_bad_ring() + { + var unavailable = new InvalidOperationException("Synthetic secret store outage."); + + var act = () => new DataExportCipher(new FailingSecrets(unavailable)); + + act.Should().Throw().Which.Should().BeSameAs(unavailable, + "the provider's own exception reaches the host, not the ring refusal"); + } + + [Fact] + public void The_ring_answers_whether_it_holds_a_label_and_a_disposed_ring_holds_none() + { + var cipher = Cipher("k2", new() { ["k1"] = Key(1), ["k2"] = Key(2) }); + cipher.HoldsKey("k1").Should().BeTrue(); + cipher.HoldsKey("k2").Should().BeTrue(); + cipher.HoldsKey("k3").Should().BeFalse(); + cipher.HoldsKey(null).Should().BeFalse(); + cipher.Dispose(); + cipher.HoldsKey("k2").Should().BeFalse("a cleared ring can open nothing"); + } + + /// + /// A smoke test, not a proof: seal racing host shutdown, where every call either refuses as disposed or seals under + /// the real key, so whatever it returned opens under an intact copy of the ring. The race window is a scheduling + /// accident, so a pass shows only that no interleaving these rounds happened to hit broke the rule; the gate's + /// guarantee rests on Keyed copying the key under the lock Dispose takes, which this cannot force. + /// + [Fact] + public async Task Smoke_a_seal_racing_disposal_either_refuses_or_seals_under_the_real_key() + { + using var verifier = Cipher("k1", new() { ["k1"] = Key(1) }); + var plaintext = Plaintext(4096); + for (var round = 0; round < 50; round++) + { + var cipher = Cipher("k1", new() { ["k1"] = Key(1) }); + using var start = new ManualResetEventSlim(); + var sealers = Enumerable.Range(0, 4).Select(_ => Task.Run(() => + { + var sealedChunks = new List(); + start.Wait(); + while (true) + { + try + { + sealedChunks.Add(cipher.Seal(Binding(0, 1), plaintext)); + } + catch (ObjectDisposedException) + { + return sealedChunks; + } + } + })).ToArray(); + start.Set(); + await Task.Delay(1); + cipher.Dispose(); + foreach (var sealedChunk in (await Task.WhenAll(sealers)).SelectMany(chunks => chunks)) + verifier.Open(Binding(0, 1), sealedChunk).Should().Equal(plaintext, "nothing is ever sealed under a zeroed key"); + } + } + + [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; + } + + private sealed class FailingSecrets(Exception failure) : ISecretProvider + { + public string? GetSecret(string key) => throw failure; + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/AccountRemovalPreflightTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/AccountRemovalPreflightTests.cs new file mode 100644 index 000000000..0746f59c7 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/AccountRemovalPreflightTests.cs @@ -0,0 +1,106 @@ +using System.Net; +using FluentAssertions; +using LearnStack.Infrastructure.Identity.AccountRemoval; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Resilience; +using LearnStack.SharedKernel.Secrets; +using Microsoft.Extensions.Logging.Abstractions; +using Polly; +using Xunit; + +namespace LearnStack.Tests.Unit.Infrastructure.Identity; + +/// +/// ADR-0107 § 7: the account-removal port's local preflight, which a closure's Begin asks before the person leaves Active. +/// The fail-closed default could never delete anything; the Keycloak adapter accepts exactly the subjects its own deletion +/// would send, by the same pure check, and the preflight sends nothing. +/// +public sealed class AccountRemovalPreflightTests +{ + private const string Issuer = "https://provider.invalid/realms/learnstack"; + private const string Canonical = "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d"; + + [Theory] + [InlineData(Canonical)] + [InlineData("")] + [InlineData("anything")] + public void The_fail_closed_default_could_never_delete_any_account(string subject) => + new RefusingIdentityProviderAccountRemoval().CanRemove(subject).Should().BeFalse("nothing is configured"); + + [Theory] + [InlineData(Canonical, true)] + [InlineData("0A1B2C3D-4E5F-4A6B-8C7D-9E0F1A2B3C4D", false)] + [InlineData("{0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d}", false)] + [InlineData("0a1b2c3d4e5f4a6b8c7d9e0f1a2b3c4d", false)] + [InlineData("00000000-0000-0000-0000-000000000000", false)] + [InlineData("an-imported-user", false)] + [InlineData("", false)] + public async Task The_adapter_accepts_exactly_the_subjects_its_deletion_would_send_and_the_preflight_sends_nothing( + string subject, bool accepted) + { + var provider = new Recording(); + using var adapter = new KeycloakAccountRemoval(new KeycloakAccountRemovalOptions(Issuer), new Secrets(), new Resilience(), NullLogger.Instance, provider); + + adapter.CanRemove(subject).Should().Be(accepted); + provider.Requests.Should().Be(0, "the preflight is local"); + + // The deletion refuses by the same check before any network effect: a subject the preflight refuses is never sent, + // and one it accepts reaches the provider (here a token endpoint that refuses the client, so nothing is deleted). + (await adapter.RemoveAsync(subject)).Should().Be(AccountRemovalOutcome.Refused); + provider.Requests.Should().Be(accepted ? 1 : 0); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("**********")] + [InlineData("${ACCOUNT_REMOVAL_SECRET}")] + public async Task An_unusable_secret_fails_the_preflight_exactly_as_the_deletion_refuses_it(string? secret) + { + var provider = new Recording(); + using var adapter = new KeycloakAccountRemoval( + new KeycloakAccountRemovalOptions(Issuer), new Secrets(secret), new Resilience(), NullLogger.Instance, provider); + + adapter.CanRemove(Canonical).Should().BeFalse("a secret the client cannot present would stop every Finalize"); + (await adapter.RemoveAsync(Canonical)).Should().Be(AccountRemovalOutcome.Refused); + provider.Requests.Should().Be(0, "an unusable secret never leaves"); + } + + [Fact] + public async Task A_secret_over_the_size_limit_fails_the_preflight_too() + { + var provider = new Recording(); + using var adapter = new KeycloakAccountRemoval(new KeycloakAccountRemovalOptions(Issuer), + new Secrets(new string('x', 1025)), new Resilience(), NullLogger.Instance, provider); + + adapter.CanRemove(Canonical).Should().BeFalse(); + (await adapter.RemoveAsync(Canonical)).Should().Be(AccountRemovalOutcome.Refused); + provider.Requests.Should().Be(0); + } + + private sealed class Secrets(string? value = "account-removal-secret-canary") : ISecretProvider + { + public string? GetSecret(string key) => key == "AccountRemoval:ClientSecret" ? value : null; + } + + private sealed class Resilience : IProviderResilience + { + public ResiliencePipeline Pipeline => ResiliencePipeline.Empty; + public string PortName => "accountRemoval"; + } + + /// A provider whose token endpoint refuses the client, and which counts every request it is sent. + private sealed class Recording : HttpMessageHandler + { + private int _requests; + + internal int Requests => Volatile.Read(ref _requests); + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Interlocked.Increment(ref _requests); + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.Unauthorized)); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/KeycloakAccountRemovalTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/KeycloakAccountRemovalTests.cs new file mode 100644 index 000000000..8b3c685b7 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/KeycloakAccountRemovalTests.cs @@ -0,0 +1,745 @@ +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Text.Json.Nodes; +using FluentAssertions; +using LearnStack.Infrastructure.Identity.AccountRemoval; +using LearnStack.Infrastructure.Resilience; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Resilience; +using LearnStack.SharedKernel.Secrets; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Polly; +using Polly.Retry; +using Xunit; + +namespace LearnStack.Tests.Unit.Infrastructure.Identity; + +/// +/// ADR-0107 § 7: the confined account-removal adapter against a scripted provider. Every outcome of the port, the token +/// narrowing, the refusals that precede any network effect, and that no subject, secret or provider text leaves the adapter. +/// +public sealed class KeycloakAccountRemovalTests +{ + private const string Issuer = "https://provider.invalid/realms/learnstack"; + private const string Secret = "account-removal-secret-canary"; + private const string Subject = "0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d"; + + [Fact] + public async Task A_deleted_account_is_removed_by_one_token_and_one_delete_on_the_exact_user_route() + { + var provider = new FakeKeycloak(); + using var adapter = Create(provider); + + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Removed); + + provider.Requests.Select(request => request.Method + " " + request.Path).Should().Equal( + "POST /realms/learnstack/protocol/openid-connect/token", + "DELETE /admin/realms/learnstack/users/" + Subject); + var delete = provider.Requests[1]; + delete.Authorization.Should().StartWith("Bearer "); + delete.Query.Should().BeEmpty(); + delete.Body.Should().BeEmpty("a deletion carries no body"); + delete.NoStore.Should().BeTrue(); + provider.Requests[0].Body.Should().Contain("client_id=learnstack-account-removal").And.Contain("grant_type=client_credentials") + .And.NotContain(Subject, "the subject is sent on the deletion path only"); + } + + [Theory] + [InlineData("application/json")] + [InlineData("application/json; charset=utf-8")] + [InlineData("APPLICATION/JSON")] + public async Task A_missing_account_the_provider_reports_in_its_own_json_is_absent_which_is_success(string mediaType) + { + var log = new CapturingLogger(); + using var adapter = Create(new FakeKeycloak { DeleteStatus = HttpStatusCode.NotFound, DeleteBody = KeycloakNotFound, DeleteMediaType = mediaType }, log: log); + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Absent); + log.Entries.Should().BeEmpty("success logs nothing"); + } + + [Theory] + [InlineData("text/html", "404 Not Found")] + [InlineData("text/html; charset=utf-8", "

Not Found

")] + [InlineData("text/plain", "not found")] + [InlineData("application/xml", "not found")] + [InlineData("application/problem+json", "{\"title\":\"Not Found\"}")] + [InlineData(null, "")] + [InlineData(null, "no content type")] + public async Task A_404_that_is_not_the_providers_own_json_is_refused_because_a_hop_in_front_may_have_answered( + string? mediaType, string body) + { + // A proxy or gateway that hides the admin path answers 404 in HTML, plain text or nothing at all. Treated as absence it + // would let the closure finish while the account still exists, and nothing in the audit would differ from a true absence. + var provider = new FakeKeycloak { DeleteStatus = HttpStatusCode.NotFound, DeleteBody = body, DeleteMediaType = mediaType }; + var log = new CapturingLogger(); + using var adapter = Create(provider, log: log); + + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Refused); + provider.Requests.Should().HaveCount(2, "a refusal is never repeated by the adapter"); + log.Reasons.Should().Equal("delete_not_found_foreign"); + } + + [Theory] + [InlineData(HttpStatusCode.Unauthorized, "delete_unauthorized")] + [InlineData(HttpStatusCode.Forbidden, "delete_unauthorized")] + [InlineData(HttpStatusCode.BadRequest, "delete_rejected")] + [InlineData(HttpStatusCode.Conflict, "delete_rejected")] + [InlineData(HttpStatusCode.MethodNotAllowed, "delete_rejected")] + [InlineData(HttpStatusCode.Found, "delete_redirect")] + [InlineData(HttpStatusCode.MovedPermanently, "delete_redirect")] + [InlineData(HttpStatusCode.TemporaryRedirect, "delete_redirect")] + public async Task A_definitive_refusal_or_a_redirect_is_refused_and_nothing_follows_the_redirect(HttpStatusCode status, string reason) + { + var provider = new FakeKeycloak { DeleteStatus = status, Location = "https://attacker.invalid/steal" }; + var log = new CapturingLogger(); + using var adapter = Create(provider, log: log); + + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Refused); + provider.Requests.Should().HaveCount(2, "a redirect is never followed and a refusal is never repeated"); + provider.Requests.Should().NotContain(request => request.Path.Contains("steal", StringComparison.Ordinal)); + log.Reasons.Should().Equal(reason); + } + + [Theory] + [InlineData(HttpStatusCode.TooManyRequests)] + [InlineData(HttpStatusCode.InternalServerError)] + [InlineData(HttpStatusCode.BadGateway)] + [InlineData(HttpStatusCode.ServiceUnavailable)] + [InlineData(HttpStatusCode.RequestTimeout)] + [InlineData((HttpStatusCode)425)] + public async Task A_server_fault_throttle_or_transient_answer_on_the_deletion_is_unavailable(HttpStatusCode status) + { + // 408 and 425 are defined as "not processed" (RFC 9110, RFC 8470): repeating is right, and the breaker counts them. + var log = new CapturingLogger(); + using var adapter = Create(new FakeKeycloak { DeleteStatus = status }, log: log); + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Unavailable); + log.Entries.Should().BeEmpty("only a refusal is logged"); + } + + [Theory] + [InlineData(HttpStatusCode.OK)] + [InlineData(HttpStatusCode.Accepted)] + [InlineData(HttpStatusCode.ResetContent)] + public async Task A_success_that_is_not_the_deletions_own_answer_is_uncertain(HttpStatusCode status) + { + using var adapter = Create(new FakeKeycloak { DeleteStatus = status }); + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Uncertain); + } + + [Theory] + [InlineData(HttpStatusCode.TooManyRequests)] + [InlineData(HttpStatusCode.InternalServerError)] + [InlineData(HttpStatusCode.ServiceUnavailable)] + [InlineData(HttpStatusCode.RequestTimeout)] + [InlineData((HttpStatusCode)425)] + public async Task A_server_fault_or_throttle_on_the_token_is_unavailable_and_no_deletion_is_sent(HttpStatusCode status) + { + var provider = new FakeKeycloak { TokenStatus = status }; + using var adapter = Create(provider); + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Unavailable); + provider.Requests.Should().NotContain(request => request.Method == "DELETE"); + } + + [Theory] + [InlineData(HttpStatusCode.Unauthorized)] + [InlineData(HttpStatusCode.Forbidden)] + [InlineData(HttpStatusCode.BadRequest)] + [InlineData(HttpStatusCode.Found)] + public async Task A_token_endpoint_that_refuses_the_client_is_refused_and_no_deletion_is_sent(HttpStatusCode status) + { + var provider = new FakeKeycloak { TokenStatus = status }; + var log = new CapturingLogger(); + using var adapter = Create(provider, log: log); + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Refused); + provider.Requests.Should().NotContain(request => request.Method == "DELETE"); + log.Reasons.Should().Equal("token_refused"); + } + + [Theory] + [InlineData("issuer", "token_not_confined")] + [InlineData("client", "token_not_confined")] + [InlineData("extra-role", "token_not_confined")] + [InlineData("wrong-role", "token_not_confined")] + [InlineData("no-role", "token_not_confined")] + [InlineData("realm-role", "token_not_confined")] + [InlineData("two-clients", "token_not_confined")] + [InlineData("no-resource-access", "token_not_confined")] + [InlineData("not-a-jwt", "token_malformed")] + [InlineData("not-json-payload", "token_malformed")] + [InlineData("type-mac", "token_malformed")] + [InlineData("no-access-token", "token_malformed")] + [InlineData("body-not-json", "token_malformed")] + [InlineData("body-array", "token_malformed")] + [InlineData("oversize-token", "token_malformed")] + [InlineData("oversize-body", "token_malformed")] + public async Task A_token_broader_or_other_than_the_confined_client_is_refused_before_any_deletion(string defect, string reason) + { + var provider = new FakeKeycloak { TokenDefect = defect }; + var log = new CapturingLogger(); + using var adapter = Create(provider, log: log); + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Refused); + provider.Requests.Should().NotContain(request => request.Method == "DELETE"); + log.Reasons.Should().Equal(reason); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("**********")] + [InlineData("${vault.account-removal}")] + public async Task An_unusable_secret_is_refused_before_any_network_call(string? secret) + { + var provider = new FakeKeycloak(); + var log = new CapturingLogger(); + using var adapter = Create(provider, secret, log: log); + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Refused); + provider.Requests.Should().BeEmpty(); + log.Reasons.Should().Equal("secret_unusable"); + } + + [Fact] + public async Task An_oversized_secret_is_refused_before_any_network_call() + { + var provider = new FakeKeycloak(); + var log = new CapturingLogger(); + using var adapter = Create(provider, new string('s', 1025), log: log); + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Refused); + provider.Requests.Should().BeEmpty(); + log.Reasons.Should().Equal("secret_unusable"); + } + + [Fact] + public async Task Only_its_own_secret_key_is_read_so_the_federation_secret_is_never_used() + { + var provider = new FakeKeycloak(); + var secrets = new Secrets(new Dictionary { ["Federation:ClientSecret"] = Secret, ["IdentityEvents:ClientSecret"] = Secret }); + using var adapter = new KeycloakAccountRemoval(new KeycloakAccountRemovalOptions(Issuer), secrets, new Resilience(), NullLogger.Instance, provider); + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Refused); + provider.Requests.Should().BeEmpty(); + secrets.Asked.Should().Equal("AccountRemoval:ClientSecret"); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("not-a-uuid")] + [InlineData("0A1B2C3D-4E5F-4A6B-8C7D-9E0F1A2B3C4D")] + [InlineData("{0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d}")] + [InlineData("0a1b2c3d4e5f4a6b8c7d9e0f1a2b3c4d")] + [InlineData("0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d ")] + [InlineData(" 0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d")] + [InlineData("0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d/../clients")] + [InlineData("0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d?briefRepresentation=true")] + [InlineData("0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d#x")] + [InlineData("..%2f..%2fclients")] + [InlineData("../clients/0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4d")] + [InlineData("00000000-0000-0000-0000-000000000000")] + [InlineData("0a1b2c3d-4e5f-4a6b-8c7d-9e0f1a2b3c4é")] + public async Task A_subject_that_is_not_a_canonical_provider_user_id_is_refused_before_any_network_call(string subject) + { + var provider = new FakeKeycloak(); + var log = new CapturingLogger(); + using var adapter = Create(provider, log: log); + (await adapter.RemoveAsync(subject)).Should().Be(AccountRemovalOutcome.Refused); + provider.Requests.Should().BeEmpty(); + log.Reasons.Should().Equal("subject_shape"); + log.Entries.Should().NotContain(entry => entry.Message.Contains(subject.Trim(), StringComparison.Ordinal) && subject.Trim().Length > 0); + } + + [Fact] + public async Task A_bad_subject_and_a_bad_secret_together_report_the_subject_which_no_repair_of_the_secret_changes() + { + var log = new CapturingLogger(); + using var adapter = Create(new FakeKeycloak(), secret: null, log: log); + (await adapter.RemoveAsync("not-a-uuid")).Should().Be(AccountRemovalOutcome.Refused); + log.Reasons.Should().Equal("subject_shape"); + } + + [Fact] + public async Task A_null_subject_is_a_programmer_error() + { + using var adapter = Create(new FakeKeycloak()); + await FluentActions.Awaiting(() => adapter.RemoveAsync(null!)).Should().ThrowAsync(); + } + + [Fact] + public async Task A_refused_connection_to_the_token_endpoint_is_unavailable_and_nothing_is_deleted() + { + var provider = new FakeKeycloak { TokenFault = new HttpRequestException(HttpRequestError.ConnectionError, "connect") }; + using var adapter = Create(provider); + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Unavailable); + provider.Requests.Should().NotContain(request => request.Method == "DELETE"); + } + + [Theory] + [InlineData(HttpRequestError.NameResolutionError)] + [InlineData(HttpRequestError.SecureConnectionError)] + [InlineData(HttpRequestError.ProxyTunnelError)] + public async Task A_fault_that_surely_precedes_the_deletions_write_is_unavailable(HttpRequestError error) + { + using var adapter = Create(new FakeKeycloak { DeleteFault = () => new HttpRequestException(error, "before-write") }); + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Unavailable); + } + + [Theory] + [InlineData(HttpRequestError.ConnectionError)] + [InlineData(HttpRequestError.ResponseEnded)] + [InlineData(HttpRequestError.InvalidResponse)] + [InlineData(HttpRequestError.Unknown)] + public async Task A_connection_lost_or_failed_on_the_deletion_that_may_have_been_written_is_uncertain(HttpRequestError error) + { + using var adapter = Create(new FakeKeycloak { DeleteFault = () => new HttpRequestException(error, "after-write") }); + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Uncertain); + } + + [Fact] + public async Task A_reused_connection_that_dies_after_the_deletion_was_read_and_cannot_be_reopened_is_uncertain() + { + // The real transport, not an injected fault. The token call leaves a pooled keep-alive connection; the provider reads the + // deletion's request head on it, then goes away: it closes that connection and its listener. The transport retries the + // request on a new connection, which is refused, and reports a connection error although the deletion was read. A + // connection error is therefore not proof that nothing was written. + using var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var issuer = "http://127.0.0.1:" + ((IPEndPoint)listener.LocalEndpoint).Port + "/realms/learnstack"; + var server = Task.Run(async () => + { + using var connection = await listener.AcceptTcpClientAsync(); + var stream = connection.GetStream(); + await ReadHeadAsync(stream, withBody: true); + var payload = new JsonObject + { + ["iss"] = issuer, + ["azp"] = "learnstack-account-removal", + ["resource_access"] = new JsonObject { ["realm-management"] = new JsonObject { ["roles"] = new JsonArray("manage-users") } }, + }; + var body = new JsonObject + { + ["access_token"] = FakeKeycloak.Jwt(payload.ToJsonString()), + ["token_type"] = "Bearer", + }.ToJsonString(); + await stream.WriteAsync(Encoding.ASCII.GetBytes("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: " + + body.Length + "\r\n\r\n" + body)); + await ReadHeadAsync(stream, withBody: false); + listener.Stop(); + connection.Close(); + }); + var observed = new FaultRecorder(new SocketsHttpHandler { UseProxy = false, AllowAutoRedirect = false }); + var log = new CapturingLogger(); + using var adapter = new KeycloakAccountRemoval(new KeycloakAccountRemovalOptions(issuer, allowLocalDevelopmentHttp: true), + new Secrets(new Dictionary { ["AccountRemoval:ClientSecret"] = Secret }), new Resilience(), log, observed); + + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Uncertain); + await server; + observed.Errors.Should().Contain(HttpRequestError.ConnectionError, + "the premise: the transport reported a connection error for a request whose head the provider had read"); + log.Entries.Should().BeEmpty("an uncertain answer is not a refusal"); + } + + [Fact] + public async Task A_timeout_before_the_deletion_is_unavailable_and_after_it_is_uncertain() + { + var beforeSend = new FakeKeycloak { TokenHangs = true }; + using (var adapter = Create(beforeSend, resilience: new Resilience(Timeout(200)))) + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Unavailable, "the token call never reaches the deletion"); + beforeSend.Requests.Should().NotContain(request => request.Method == "DELETE"); + + var afterSend = new FakeKeycloak { DeleteHangs = true }; + using (var adapter = Create(afterSend, resilience: new Resilience(Timeout(200)))) + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Uncertain, "the deletion was handed to the transport"); + afterSend.Requests.Should().Contain(request => request.Method == "DELETE"); + } + + [Fact] + public async Task A_transport_cancellation_that_is_not_the_callers_follows_the_same_phase_rule() + { + using (var adapter = Create(new FakeKeycloak { TokenFault = new TaskCanceledException() })) + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Unavailable); + using (var adapter = Create(new FakeKeycloak { DeleteFault = () => new TaskCanceledException() })) + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Uncertain); + } + + [Fact] + public async Task The_callers_cancellation_propagates_before_and_after_the_deletion_is_sent() + { + using var before = new CancellationTokenSource(); + var token = new FakeKeycloak { TokenHangs = true }; + using (var adapter = Create(token)) + { + var call = adapter.RemoveAsync(Subject, before.Token); + await token.TokenReached.Task; + await before.CancelAsync(); + await FluentActions.Awaiting(() => call).Should().ThrowAsync(); + } + + using var after = new CancellationTokenSource(); + var delete = new FakeKeycloak { DeleteHangs = true }; + using (var adapter = Create(delete)) + { + var call = adapter.RemoveAsync(Subject, after.Token); + await delete.DeleteReached.Task; + await after.CancelAsync(); + await FluentActions.Awaiting(() => call).Should().ThrowAsync(); + } + } + + [Fact] + public async Task The_subject_secret_and_provider_text_never_reach_an_exception_the_pipeline_sees() + { + // A pipeline whose retry hook captures every exception the adapter throws into it: the closed fault carries none of them. + var captured = new List(); + var spy = new ResiliencePipelineBuilder().AddRetry(new RetryStrategyOptions + { + MaxRetryAttempts = 1, + Delay = TimeSpan.Zero, + ShouldHandle = new PredicateBuilder().Handle(), + OnRetry = arguments => { captured.Add(arguments.Outcome.Exception!); return ValueTask.CompletedTask; }, + }).Build(); + foreach (var provider in new[] + { + new FakeKeycloak { DeleteStatus = HttpStatusCode.InternalServerError, DeleteBody = "provider-body-canary" }, + new FakeKeycloak { TokenStatus = HttpStatusCode.ServiceUnavailable }, + new FakeKeycloak { DeleteFault = () => new HttpRequestException(HttpRequestError.ConnectionError, "transport-message-canary " + Subject) }, + new FakeKeycloak { DeleteFault = () => new HttpRequestException(HttpRequestError.ResponseEnded, "transport-message-canary " + Subject) }, + new FakeKeycloak { DeleteStatus = HttpStatusCode.OK }, + }) + { + using var adapter = Create(provider, resilience: new Resilience(spy)); + await adapter.RemoveAsync(Subject); + } + captured.Should().HaveCount(5).And.AllBeOfType(); + foreach (var error in captured) + { + var text = error + " " + error.Message + " " + error.InnerException; + text.Should().NotContain(Subject).And.NotContain(Secret).And.NotContain("canary").And.NotContain("Bearer"); + } + // The adapter and its options render as their type name: no issuer, secret key or subject can come from a log of either. + using var rendered = Create(new FakeKeycloak()); + rendered.ToString().Should().Be("KeycloakAccountRemoval"); + new KeycloakAccountRemovalOptions(Issuer).ToString().Should().Be("KeycloakAccountRemovalOptions"); + } + + [Fact] + public async Task A_real_breaker_opens_on_repeated_faults_and_an_open_breaker_never_sends() + { + var provider = new FakeKeycloak { DeleteStatus = HttpStatusCode.InternalServerError }; + using var adapter = Create(provider, resilience: Real(("CircuitBreaker:MinimumThroughput", "2"), ("CircuitBreaker:FailureRatio", "1"), + ("CircuitBreaker:BreakDurationSeconds", "30"))); + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Unavailable); + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Unavailable); + var sent = provider.Requests.Count; + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Unavailable); + provider.Requests.Should().HaveCount(sent, "an open breaker answers without a request"); + } + + [Fact] + public async Task A_hanging_provider_opens_the_breaker_because_the_pipeline_timeout_is_what_the_adapter_surfaces() + { + // The composed pair: the real pipeline timeout (the fixed five seconds the composition root enforces), the real breaker + // and the adapter's own cancellation. Were the two five-second limits equal, the adapter's, started first, would win; the + // timeout strategy would rethrow a plain cancellation, the breaker would not count it, and a hanging provider would + // answer uncertain, five seconds at a time, for ever. Two hangs must open the breaker; the third call never sends. + var provider = new FakeKeycloak { DeleteHangs = true }; + using var adapter = Create(provider, resilience: Real(("Timeout:TotalSeconds", "5"), ("CircuitBreaker:MinimumThroughput", "2"), + ("CircuitBreaker:FailureRatio", "1"), ("CircuitBreaker:BreakDurationSeconds", "30"))); + + var calls = await Task.WhenAll(adapter.RemoveAsync(Subject), adapter.RemoveAsync(Subject)); + calls.Should().Equal([AccountRemovalOutcome.Uncertain, AccountRemovalOutcome.Uncertain], + "the deletion was handed to the transport and its answer never came"); + var sent = provider.Requests.Count; + + (await adapter.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Unavailable, "the breaker recorded both timeouts"); + provider.Requests.Should().HaveCount(sent, "an open breaker answers without a request"); + } + + [Fact] + public void The_adapters_own_backstop_is_later_than_the_pipeline_timeout_the_composition_root_fixes() + { + KeycloakAccountRemoval.Backstop.Should().BeGreaterThan(KeycloakAccountRemoval.CallCeiling); + KeycloakAccountRemoval.CallCeiling.TotalSeconds.Should().Be(AccountRemovalAdapterFactory.CallCeilingSeconds); + } + + [Fact] + public async Task A_second_concurrent_call_meets_the_bulkhead_and_is_unavailable_without_a_request() + { + var provider = new FakeKeycloak { DeleteHangs = true }; + using var adapter = Create(provider, resilience: Real(("Bulkhead:MaxConcurrency", "1"), ("Bulkhead:QueueLength", "0"), + ("Timeout:TotalSeconds", "30"))); + var first = adapter.RemoveAsync(Subject); + await provider.DeleteReached.Task; + var sent = provider.Requests.Count; + + (await adapter.RemoveAsync("1b2c3d4e-5f6a-4b7c-8d9e-0f1a2b3c4d5e")).Should().Be(AccountRemovalOutcome.Unavailable); + provider.Requests.Should().HaveCount(sent); + + provider.ReleaseDelete.SetResult(); + (await first).Should().Be(AccountRemovalOutcome.Removed); + } + + [Theory] + [InlineData("http://provider.invalid/realms/learnstack")] + [InlineData("http://127.0.0.1/realms/learnstack")] + [InlineData("https://user:pass@provider.invalid/realms/learnstack")] + [InlineData("https://provider.invalid/realms/learnstack?x=1")] + [InlineData("https://provider.invalid/realms/learnstack#x")] + [InlineData("https://provider.invalid/realms/other")] + [InlineData("https://provider.invalid/realms/learnstack-hub")] + [InlineData("https://provider.invalid/realms/learnstack/extra")] + [InlineData("https://provider.invalid/realms/learnstack-hub/")] + [InlineData("https://provider.invalid/x-realms/learnstack")] + [InlineData("https://provider.invalid/")] + [InlineData("provider.invalid/realms/learnstack")] + [InlineData("")] + public void The_issuer_must_be_an_https_learnstack_realm(string issuer) + { + FluentActions.Invoking(() => new KeycloakAccountRemovalOptions(issuer)).Should().Throw(); + } + + [Fact] + public void A_loopback_http_issuer_needs_the_development_flag_and_derives_the_fixed_routes() + { + FluentActions.Invoking(() => new KeycloakAccountRemovalOptions("http://localhost:8080/realms/learnstack")).Should().Throw(); + FluentActions.Invoking(() => new KeycloakAccountRemovalOptions("http://provider.invalid/realms/learnstack", true)).Should().Throw(); + var options = new KeycloakAccountRemovalOptions("http://localhost:8080/realms/learnstack/", true); + options.Issuer.Should().Be("http://localhost:8080/realms/learnstack"); + KeycloakAccountRemovalRoutes.Token(options).AbsoluteUri.Should().Be("http://localhost:8080/realms/learnstack/protocol/openid-connect/token"); + KeycloakAccountRemovalRoutes.User(options, Subject).AbsoluteUri.Should().Be("http://localhost:8080/admin/realms/learnstack/users/" + Subject); + } + + [Fact] + public void The_user_route_refuses_what_is_not_a_canonical_user_id() + { + var options = new KeycloakAccountRemovalOptions(Issuer); + foreach (var subject in new[] { "", "x", Subject.ToUpperInvariant(), Subject + "/x", "../" + Subject }) + FluentActions.Invoking(() => KeycloakAccountRemovalRoutes.User(options, subject)).Should().Throw(); + } + + [Fact] + public void The_factory_returns_the_port_and_names_the_secret_key() + { + using var adapter = (IDisposable)AccountRemovalAdapterFactory.Create(new KeycloakAccountRemovalOptions(Issuer), + new Secrets(new Dictionary()), new Resilience(), NullLoggerFactory.Instance); + adapter.Should().BeAssignableTo(); + AccountRemovalAdapterFactory.SecretKey.Should().Be("AccountRemoval:ClientSecret"); + } + + [Fact] + public async Task The_default_refuses_every_call_without_reading_the_subject() + { + var port = new RefusingIdentityProviderAccountRemoval(); + (await port.RemoveAsync(Subject)).Should().Be(AccountRemovalOutcome.Refused); + (await port.RemoveAsync("")).Should().Be(AccountRemovalOutcome.Refused); + (await port.RemoveAsync(null!)).Should().Be(AccountRemovalOutcome.Refused); + port.ToString().Should().Be("RefusingIdentityProviderAccountRemoval"); + } + + private const string KeycloakNotFound = "{\"error\":\"User not found\"}"; + + private static KeycloakAccountRemoval Create(FakeKeycloak provider, string? secret = Secret, + IProviderResilience? resilience = null, CapturingLogger? log = null) => + new(new KeycloakAccountRemovalOptions(Issuer), new Secrets(new Dictionary { ["AccountRemoval:ClientSecret"] = secret }), + resilience ?? new Resilience(), log ?? new CapturingLogger(), provider); + + /// Reads one request head (and, with a body, whatever follows it) off a raw loopback connection. + private static async Task ReadHeadAsync(NetworkStream stream, bool withBody) + { + var buffer = new byte[8192]; + var total = 0; + while (total < buffer.Length) + { + var read = await stream.ReadAsync(buffer.AsMemory(total)); + if (read == 0) return; + total += read; + var text = Encoding.ASCII.GetString(buffer, 0, total); + var end = text.IndexOf("\r\n\r\n", StringComparison.Ordinal); + if (end >= 0 && (!withBody || text.Length > end + 4)) return; + } + } + + /// Records every transport error the adapter's client saw, then lets it propagate. + private sealed class FaultRecorder(HttpMessageHandler inner) : DelegatingHandler(inner) + { + internal List Errors { get; } = []; + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + try { return await base.SendAsync(request, cancellationToken); } + catch (HttpRequestException error) + { + Errors.Add(error.HttpRequestError); + throw; + } + } + } + + /// Keeps every line the adapter logs, with its level, event id and formatted text. + private sealed class CapturingLogger : ILogger + { + internal List<(LogLevel Level, int Event, string Message)> Entries { get; } = []; + + /// The closed reason code of each refusal line, taken from the text after the last colon. + internal IEnumerable Reasons => Entries.Where(entry => entry.Level == LogLevel.Warning && entry.Event == 7125) + .Select(entry => entry.Message[(entry.Message.LastIndexOf(": ", StringComparison.Ordinal) + 2)..].TrimEnd('.')); + + public IDisposable? BeginScope(TState state) where TState : notnull => null; + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + var message = formatter(state, exception); + lock (Entries) Entries.Add((logLevel, eventId.Id, message)); + message.Should().NotContain(Subject).And.NotContain(Secret).And.NotContain("provider.invalid").And.NotContain("Bearer") + .And.NotContain("canary"); + } + } + + private static ResiliencePipeline Timeout(int milliseconds) => + new ResiliencePipelineBuilder().AddTimeout(TimeSpan.FromMilliseconds(milliseconds)).Build(); + + /// The real pipeline the composition root builds, with a few values overridden for one test. + private static IProviderResilience Real(params (string Key, string Value)[] values) + { + var settings = new Dictionary { ["Retry:Enabled"] = "false", ["Retry:MaxRetryAttempts"] = "0" }; + foreach (var (key, value) in values) settings[key] = value; + var configuration = new ConfigurationBuilder().AddInMemoryCollection( + settings.ToDictionary(pair => "Resilience:accountRemoval:" + pair.Key, pair => pair.Value)).Build(); + var services = new ServiceCollection(); + services.AddProviderResilience(configuration, "accountRemoval"); + return services.BuildServiceProvider().GetRequiredService>(); + } + + private sealed class Secrets(Dictionary values) : ISecretProvider + { + internal List Asked { get; } = []; + + public string? GetSecret(string key) + { + Asked.Add(key); + return values.GetValueOrDefault(key); + } + } + + private sealed class Resilience(ResiliencePipeline? pipeline = null) : IProviderResilience + { + public ResiliencePipeline Pipeline => pipeline ?? ResiliencePipeline.Empty; + public string PortName => "accountRemoval"; + } + + internal sealed record Recorded(string Method, string Path, string Query, string Body, string? Authorization, bool NoStore); + + /// A scripted Keycloak: a token endpoint with injectable defects and a user deletion with injectable answers. + private sealed class FakeKeycloak : HttpMessageHandler + { + internal List Requests { get; } = []; + internal string? TokenDefect { get; init; } + internal HttpStatusCode? TokenStatus { get; init; } + internal Exception? TokenFault { get; init; } + internal bool TokenHangs { get; init; } + internal HttpStatusCode DeleteStatus { get; init; } = HttpStatusCode.NoContent; + internal string? DeleteBody { get; init; } + + /// The deletion answer's media type; null leaves the answer without a Content-Type header. + internal string? DeleteMediaType { get; init; } + internal Func? DeleteFault { get; init; } + internal bool DeleteHangs { get; init; } + internal string? Location { get; init; } + internal TaskCompletionSource TokenReached { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal TaskCompletionSource DeleteReached { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + internal TaskCompletionSource ReleaseDelete { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var body = request.Content is null ? string.Empty : await request.Content.ReadAsStringAsync(cancellationToken); + var path = request.RequestUri!.AbsolutePath; + lock (Requests) + Requests.Add(new(request.Method.Method, path, request.RequestUri.Query, body, request.Headers.Authorization?.ToString(), + request.Headers.CacheControl?.NoStore == true)); + if (path.EndsWith("/protocol/openid-connect/token", StringComparison.Ordinal)) + { + TokenReached.TrySetResult(); + if (TokenHangs) await Task.Delay(System.Threading.Timeout.Infinite, cancellationToken); + if (TokenFault is not null) throw TokenFault; + if (TokenStatus is { } status) return Answer(status); + return TokenAnswer(TokenDefect); + } + if (request.Method != HttpMethod.Delete || request.Headers.Authorization?.Scheme != "Bearer") return new(HttpStatusCode.Unauthorized); + DeleteReached.TrySetResult(); + if (DeleteHangs) + { + var released = ReleaseDelete.Task; + var done = await Task.WhenAny(released, Task.Delay(System.Threading.Timeout.Infinite, cancellationToken)); + await done; + return new(HttpStatusCode.NoContent); + } + if (DeleteFault is { } fault) throw fault(); + return Answer(DeleteStatus, DeleteBody, DeleteMediaType); + } + + private HttpResponseMessage Answer(HttpStatusCode status, string? body = null, string? mediaType = null) + { + var response = new HttpResponseMessage(status); + if (body is not null) + { + var bytes = Encoding.UTF8.GetBytes(body); + response.Content = new ByteArrayContent(bytes); + if (mediaType is not null) response.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(mediaType); + } + if (Location is not null && (int)status is >= 300 and < 400) response.Headers.Location = new Uri(Location); + return response; + } + + private static HttpResponseMessage Json(string text) => + new(HttpStatusCode.OK) { Content = new StringContent(text, Encoding.UTF8, "application/json") }; + + private static HttpResponseMessage TokenAnswer(string? defect) + { + switch (defect) + { + case "body-not-json": return Json("not json"); + case "body-array": return Json("[]"); + case "no-access-token": return Json("{\"token_type\":\"Bearer\"}"); + case "oversize-body": return Json("{\"access_token\":\"" + new string('a', 20 * 1024) + "\",\"token_type\":\"Bearer\"}"); + } + var access = defect switch + { + "not-a-jwt" => "not-a-jwt", + "not-json-payload" => Part("{\"alg\":\"none\"}") + "." + Part("not json") + ".c2ln", + "oversize-token" => new string('a', 16 * 1024 + 1), + _ => Token(defect), + }; + return Json(new JsonObject { ["access_token"] = access, ["token_type"] = defect == "type-mac" ? "MAC" : "Bearer", ["expires_in"] = 60 }.ToJsonString()); + } + + private static string Part(string json) => Convert.ToBase64String(Encoding.UTF8.GetBytes(json)).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + /// An unsigned token with the given payload: the adapter reads the claims and never verifies the signature. + internal static string Jwt(string payloadJson) => Part("{\"alg\":\"none\"}") + "." + Part(payloadJson) + ".c2ln"; + + private static string Token(string? defect) + { + var roles = defect switch + { + "extra-role" => new JsonArray("manage-users", "view-users"), + "wrong-role" => new JsonArray("manage-identity-providers"), + "no-role" => new JsonArray(), + _ => new JsonArray("manage-users"), + }; + var management = new JsonObject { ["roles"] = roles }; + var resources = defect == "two-clients" + ? new JsonObject { ["realm-management"] = management, ["account"] = new JsonObject { ["roles"] = new JsonArray("manage-account") } } + : new JsonObject { ["realm-management"] = management }; + var payload = new JsonObject + { + ["iss"] = defect == "issuer" ? "https://other.invalid/realms/learnstack" : Issuer, + ["azp"] = defect == "client" ? "learnstack-federation-admin" : "learnstack-account-removal", + }; + if (defect != "no-resource-access") payload["resource_access"] = resources; + if (defect == "realm-role") payload["realm_access"] = new JsonObject { ["roles"] = new JsonArray("default-roles-learnstack") }; + return Part("{\"alg\":\"none\"}") + "." + Part(payload.ToJsonString()) + ".c2ln"; + } + } +} diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs index 32e7c42ec..3ce3e9416 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformAdminGateTests.cs @@ -95,6 +95,11 @@ public async Task The_Rebind_Operation_Is_Admitted_Only_For_The_Identity_Authori [InlineData("platform.federation.report", "platform.federation.read")] [InlineData("platform.federation.remove", "platform.federation.admin")] [InlineData("platform.federation.disable", "platform.federation.admin")] + [InlineData("platform.data_request.inspect", "platform.data_request.read")] + [InlineData("audit.redaction.apply", "platform.data_request.write")] + [InlineData("platform.closure.begin", "platform.data_request.write")] + [InlineData("platform.closure.finalize", "platform.data_request.write")] + [InlineData("identity.data_request.fan_out_closure", "platform.data_request.write")] public async Task An_Operator_Operation_Is_Admitted_Only_For_Its_Own_Permission(string slug, string permission) { // ADR-0103 Decision table and ADR-0099 Amendment 10: a read needs the read key and an act needs the write or @@ -371,6 +376,24 @@ public void The_Shipped_Tenancy_Source_Declares_The_Slugs_The_Scope_Records() } } + [Fact] + public void The_Closure_Operations_Carry_Their_Recorded_Spellings_And_Only_Finalize_Has_A_Checkpoint() + { + // ADR-0107 § 8 leaves the spellings to the step record: both acts run in the platform scope under the one write + // key, their rows name the platform module because the operator writes refuse identity, and Finalize alone + // writes an intent row, the redaction's evidence, before its provider call (ADR-0108 § 8). + var spellings = new[] { PlatformOperations.ClosureBegin, PlatformOperations.ClosureFinalize } + .Select(operation => (operation.AuditSlug, operation.ReasonSlug, operation.AttemptAuditSlug, operation.Executor, + operation.Permission.Key)); + + spellings.Should().Equal( + ("platform.closure.begin", "closure_begin", (string?)null, PlatformOperationExecutor.PlatformScope, + "platform.data_request.write"), + ("platform.closure.finalize", "closure_finalize", "platform.closure.finalize_attempt", + PlatformOperationExecutor.PlatformScope, "platform.data_request.write")); + PlatformOperations.All.Should().Contain([PlatformOperations.ClosureBegin, PlatformOperations.ClosureFinalize]); + } + [Fact] public void The_Registry_Is_Closed_And_Every_Operation_Names_A_Registered_Platform_Permission() { diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActCatalogTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActCatalogTests.cs index 5fa39873f..a267ff477 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActCatalogTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActCatalogTests.cs @@ -45,6 +45,10 @@ public void An_Operation_That_Runs_Anywhere_But_The_Pipeline_Is_Refused_By_The_C PlatformOperations.DeliveryInspect.AuditSlug, PlatformOperations.DeliveryReplay.AuditSlug, PlatformOperations.DeliveryReset.AuditSlug, + PlatformOperations.DataRequestInspect.AuditSlug, + PlatformOperations.ErasureComplete.AuditSlug, + PlatformOperations.ClosureBegin.AuditSlug, + PlatformOperations.ClosureFinalize.AuditSlug, }; [Fact] @@ -59,6 +63,8 @@ public void Every_Registered_Operation_Runs_In_Exactly_One_Place_And_Only_The_Sc PlatformOperations.DeliveryReplay.Executor.Should().Be(PlatformOperationExecutor.RecoveryOwner); PlatformOperations.DeliveryReset.Executor.Should().Be(PlatformOperationExecutor.RecoveryOwner); PlatformOperations.DeliveryInspect.Executor.Should().Be(PlatformOperationExecutor.PlatformScope); + PlatformOperations.ClosureFanOut.Executor.Should().Be(PlatformOperationExecutor.Pipeline, + "a closure's fan-out writes each group's rows on the application role, never in the platform scope (ADR-0107 § 7)"); } [Fact] diff --git a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActExecutorTests.cs b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActExecutorTests.cs index 47cfe8cec..1c07c8782 100644 --- a/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActExecutorTests.cs +++ b/backend/tests/LearnStack.Tests.Unit/Infrastructure/MultiTenancy/PlatformOperatorActExecutorTests.cs @@ -3,6 +3,7 @@ using LearnStack.Application.Authorization; using LearnStack.Infrastructure.PlatformOperator; using LearnStack.Modules.Identity.Application; +using LearnStack.Modules.Identity.Application.Contracts.OperatorActs; using LearnStack.Modules.Tenancy.Application.Authorization; using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; using LearnStack.SharedKernel.Errors; @@ -42,6 +43,9 @@ public sealed class PlatformOperatorActExecutorTests private static OperatorProvisionTenantCommand Provision(TenantId? tenant = null) => new( tenant ?? Tenant, "acme", "Acme", OrganizationId.From(Guid.CreateVersion7()), "main", "Main"); + private static FanOutClosureCommand FanOut(OrganizationId? organization) => + new(UserId.From(Guid.CreateVersion7()), organization); + [Fact] public async Task An_Admitted_Act_Runs_On_A_Resolved_Ambient_Context_Of_The_Tenant_It_Names_And_Nothing_Else() { @@ -235,6 +239,104 @@ await rig.Executor.ExecuteAsync( rig.LoggedEvents.Should().Equal([7109], "the warning an operator can alert on, since this refusal writes no audit row"); } + /// + /// ADR-0102 Amendment 2: a closure's fan-out is the one act whose context names an organization, the participant + /// group's, so the ordinary transaction behavior announces that group; its descriptor is minted for that operation alone. + /// + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task A_Closure_Fan_Out_Runs_In_Its_Groups_Organization_Or_The_Tenant_Wide_Group(bool organization) + { + await using var rig = new Rig(); + var group = organization ? OrganizationId.From(Guid.CreateVersion7()) : (OrganizationId?)null; + var admission = TestPlatformAdmissions.Admission(PlatformOperations.ClosureFanOut, issuedAt: Now); + + var result = await rig.Executor.ExecuteAsync(admission, Tenant, group, FanOut(group)); + + result.IsSuccess.Should().BeTrue(); + var seen = rig.Observed.Should().ContainSingle().Subject; + seen.Context.TenantId.Should().Be(Tenant); + seen.Context.OrganizationId.Should().Be(group, "the group's organization is announced with its tenant"); + seen.Context.UserId.Should().BeNull(); + seen.Context.HostScope.Should().BeNull(); + seen.Context.Origin.Should().Be(TenantContextOrigin.Ambient); + seen.Descriptor.Should().NotBeNull(); + seen.Descriptor!.RequestType.Should().Be(); + seen.Descriptor.Operator!.Operation.Should().BeSameAs(PlatformOperations.ClosureFanOut); + seen.Descriptor.Operator.ReasonSlug.Should().Be("closure_fan_out"); + seen.MatchedWhileLive.Should().BeTrue(); + } + + /// + /// ADR-0102 Amendment 2: no other operation's act announces an organization, and an organization nobody assigned is + /// no group; each is refused before the admission is spent or the pipeline is reached. + /// + [Theory] + [InlineData("tenant_provision")] + [InlineData("host_map")] + [InlineData("unassigned_organization")] + public async Task An_Organization_Is_Announced_Only_For_A_Closure_Fan_Out(string variant) + { + await using var rig = new Rig(); + var slot = new OrganizationId[1]; + var (admission, organization) = variant switch + { + "tenant_provision" => (TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now), + OrganizationId.From(Guid.CreateVersion7())), + "host_map" => (TestPlatformAdmissions.Admission(PlatformOperations.HostMap, issuedAt: Now), OrganizationId.From(Guid.CreateVersion7())), + _ => (TestPlatformAdmissions.Admission(PlatformOperations.ClosureFanOut, issuedAt: Now), slot[0]), + }; + + Func act = variant switch + { + "tenant_provision" => () => rig.Executor.ExecuteAsync(admission, Tenant, organization, Provision()), + "host_map" => () => rig.Executor.ExecuteAsync(admission, Tenant, organization, + new OperatorMapHostCommand("acme.test")), + _ => () => rig.Executor.ExecuteAsync(admission, Tenant, organization, FanOut(organization)), + }; + + await act.Should().ThrowAsync(); + rig.Observed.Should().BeEmpty("the pipeline was never reached"); + admission.TryConsume().Should().BeTrue("a refusal before the act leaves the admission unspent"); + } + + /// + /// The source restates the rule on its own frame: a context that names an organization is evidence only for a closure's + /// fan-out, so a frame an onboarding admission opened over one is refused at entry and captures nothing. + /// + [Fact] + public void The_Source_Opens_A_Frame_With_An_Organization_Only_For_A_Closure_Fan_Out() + { + // One source per act, as the executor resolves one per scope: a source whose frame was refused opens no other. + var accessor = new StaticTenantContextAccessor(null); + PlatformOperatorOperationSource Source() => new( + new OperationPolicyCatalog([new TenancyOperationPolicySource(), new IdentityOperationPolicySource()]), + new PlatformOperatorActCatalog( + [ + new(typeof(OperatorProvisionTenantCommand), new(PlatformOperations.TenantProvision)), + new(typeof(FanOutClosureCommand), new(PlatformOperations.ClosureFanOut)), + ]), + accessor); + var organization = OrganizationId.From(Guid.CreateVersion7()); + + using var refusing = Source(); + var onboarding = new OperatorTenantContext(Tenant, organization, "00-test"); + accessor.Current = onboarding; + var refused = () => refusing.Enter(TestPlatformAdmissions.Admission(PlatformOperations.TenantProvision, issuedAt: Now), onboarding); + refused.Should().Throw("an onboarding act never runs in an organization"); + refusing.Capture(typeof(OperatorProvisionTenantCommand), onboarding).Should().BeNull(); + + using var admitting = Source(); + var fanOut = new OperatorTenantContext(Tenant, organization, "00-test"); + accessor.Current = fanOut; + using (admitting.Enter(TestPlatformAdmissions.Admission(PlatformOperations.ClosureFanOut, issuedAt: Now), fanOut)) + { + admitting.Capture(typeof(FanOutClosureCommand), fanOut).Should().NotBeNull("the fan-out's own request in its group"); + admitting.Capture(typeof(OperatorProvisionTenantCommand), fanOut).Should().BeNull("one admission, one act"); + } + } + [Fact] public void The_Act_Catalog_Refuses_An_Operation_That_Needs_The_Platform_Role_Or_No_Acts_At_All() { @@ -263,6 +365,7 @@ public Rig() [ new(typeof(OperatorProvisionTenantCommand), new(PlatformOperations.TenantProvision)), new(typeof(OperatorMapHostCommand), new(PlatformOperations.HostMap)), + new(typeof(FanOutClosureCommand), new(PlatformOperations.ClosureFanOut)), // A request whose policy admits the seed source and not the operator's: bound in the catalog // here so the source's own check of the policy's sources is what has to refuse it. new(typeof(MapHostToTenantCommand), new(PlatformOperations.TenantProvision)), @@ -306,6 +409,15 @@ public Rig() ? Result.FailFor>(refusal) : Result.Ok(new ProvisionedTenantDto(Tenant, "acme", OrganizationId.From(Guid.CreateVersion7()), "main"))); }); + sender.Send(Arg.Any>>(), Arg.Any()).Returns(_ => + { + var context = Accessor.Current!; + var source = provider.GetServices().Single(); + var descriptor = source.Capture(typeof(FanOutClosureCommand), context); + Observed.Add(new Observation(context, source, descriptor, + descriptor?.Matches(typeof(FanOutClosureCommand), context) ?? false, [])); + return Task.FromResult(Result.Ok(ClosureGroupOutcome.Started)); + }); return sender; }); _provider = services.BuildServiceProvider(); diff --git a/backend/tests/LearnStack.Tests.Unit/InvitationEmailRegistryTests.cs b/backend/tests/LearnStack.Tests.Unit/InvitationEmailRegistryTests.cs index dffa90427..e204d24cd 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,22 @@ 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", + ]; + + private static readonly string[] DataErasureKeys = ["identity.data_erasure_tenant.v1", "identity.data_erasure_organization.v1"]; + [Fact] - public void Actual_Registry_Binds_Exactly_Two_Active_Definitions_And_Four_Scoped_Ordinary_Roots() + public void Actual_Registry_Binds_Exactly_Eight_Active_Definitions_And_Ten_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).Concat(DataErasureKeys)); + 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 +40,10 @@ 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), + typeof(RunTenantDataErasureCommand), typeof(RunOrganizationDataErasureCommand) }); foreach (var definition in definitions) { definition.ProfileRegistration.PlanType.Should().Be(); @@ -47,6 +61,79 @@ 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); + } + + /// ADR-0107 § 2, § 5: the two erasure definitions, one per scope group, transactional and identifier-only. + [Theory] + [InlineData("identity.data_erasure_tenant.v1", "tenant")] + [InlineData("identity.data_erasure_organization.v1", "organization")] + public void Actual_Registry_Binds_The_Data_Erasure_Definitions_As_Transactional_Identifier_Only_Roots(string key, string scope) + { + var registry = InvitationEmailRegistration.CreateRegistry(); + var expectedScope = scope == "tenant" ? BackgroundJobScope.TenantWide : BackgroundJobScope.Organization; + var expectedRoot = scope == "tenant" ? typeof(RunTenantDataErasureCommand) : typeof(RunOrganizationDataErasureCommand); + + 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(); + 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), new DataErasureJobParameters(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/backend/tests/LearnStack.Tests.Unit/SharedKernel/Audit/AuditRedactionPlanTests.cs b/backend/tests/LearnStack.Tests.Unit/SharedKernel/Audit/AuditRedactionPlanTests.cs new file mode 100644 index 000000000..b6226ffea --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/SharedKernel/Audit/AuditRedactionPlanTests.cs @@ -0,0 +1,249 @@ +using System.Text; +using System.Text.Json.Nodes; +using FluentAssertions; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using Xunit; + +namespace LearnStack.Tests.Unit.SharedKernel.Audit; + +/// +/// The redaction plan's three closed shapes and the closure's summed report +/// (ADR-0108 §§ 3, 4, 8): an +/// erasure's plan keeps its request's subject and reach, a closure's tenant pass reaches one real tenant by every +/// Membership the person holds there, its sentinel pass reaches only the platform sentinel by the subject key, and the +/// aggregate's document is counts only and bounded however many tenants. +/// +public sealed class AuditRedactionPlanTests +{ + private static readonly TenantId Tenant = TenantId.From(Guid.Parse("0190aaaa-0000-7000-8000-00000000aaaa")); + private static readonly OrganizationId Branch = OrganizationId.From(Guid.Parse("0190bbbb-0000-7000-8000-00000000bbbb")); + private static readonly UserId Person = UserId.From(Guid.Parse("0190c0de-0000-7000-8000-00000000c0de")); + private static readonly Guid MembershipA = Guid.Parse("0190c0de-0000-7000-8000-0000000000a1"); + private static readonly Guid MembershipB = Guid.Parse("0190c0de-0000-7000-8000-0000000000a2"); + private static readonly IdentitySubjectKey Key = IdentitySubjectKey.FromBytes(Enumerable.Range(1, 32).Select(value => (byte)value).ToArray()); + + [Theory] + [InlineData(DataRequestOrigin.Self, true)] + [InlineData(DataRequestOrigin.ClosureFanout, true)] + [InlineData(DataRequestOrigin.Administrator, false)] + public void An_erasure_plan_keeps_its_request_s_subject_and_the_reach_of_who_asked(DataRequestOrigin origin, bool wholeTenant) + { + var subject = new UserDataSubject(Guid.CreateVersion7(), DataRequestKind.Erasure, origin, Person, + new DataRequestScopeGroup(Tenant, Branch), [MembershipA]); + + var plan = new AuditRedactionPlan(subject); + + plan.Pass.Should().Be(AuditRedactionPass.Erasure); + plan.Subject.Should().BeSameAs(subject); + (plan.TenantId, plan.OrganizationId, plan.WholeTenant, plan.SubjectUserId).Should().Be((Tenant, (OrganizationId?)Branch, wholeTenant, Person)); + plan.MembershipIds.Should().Equal(MembershipA); + plan.SubjectKey.Should().BeNull("only the sentinel pass selects by the key"); + } + + [Theory] + [InlineData(DataRequestKind.Export)] + [InlineData(DataRequestKind.Closure)] + public void The_request_constructor_takes_an_erasure_s_subject_alone(DataRequestKind kind) + { + var subject = new UserDataSubject(Guid.CreateVersion7(), kind, DataRequestOrigin.Self, Person, + new DataRequestScopeGroup(Tenant, null), [MembershipA]); + + FluentActions.Invoking(() => new AuditRedactionPlan(subject)).Should().Throw( + "an export is never redacted, and a closure's redaction is its Finalize's passes, never one request's"); + } + + [Fact] + public void A_closure_tenant_pass_reaches_the_whole_tenant_by_every_membership_and_is_no_request() + { + var plan = AuditRedactionPlan.ForClosureTenant(Tenant, Person, [MembershipA, MembershipB]); + + plan.Pass.Should().Be(AuditRedactionPass.ClosureTenant); + (plan.TenantId, plan.OrganizationId, plan.WholeTenant, plan.SubjectUserId).Should().Be((Tenant, (OrganizationId?)null, true, Person), + "one pass reaches every group of the tenant (ADR-0108 § 4)"); + plan.MembershipIds.Should().Equal(MembershipA, MembershipB); + plan.SubjectKey.Should().BeNull(); + FluentActions.Invoking(() => plan.Subject).Should().Throw("a closure's pass is not one request's"); + } + + [Fact] + public void A_closure_tenant_pass_refuses_the_sentinel_an_unassigned_tenant_a_system_subject_and_a_bad_membership_list() + { + var bounded = Enumerable.Range(0, DataRequestLimits.MaximumSnapshotMemberships).Select(_ => Guid.CreateVersion7()).ToArray(); + AuditRedactionPlan.ForClosureTenant(Tenant, Person, bounded).MembershipIds.Should().HaveCount(bounded.Length, + "the bound an erasure's snapshot carries is admitted"); + + var refusals = new (string Case, Func Build)[] + { + ("the platform sentinel", () => AuditRedactionPlan.ForClosureTenant(TenantId.PlatformSentinel, Person, [MembershipA])), + ("the nil tenant", () => AuditRedactionPlan.ForClosureTenant(TenantId.From(Guid.Empty), Person, [MembershipA])), + ("the system actor", () => AuditRedactionPlan.ForClosureTenant(Tenant, UserId.SystemActor, [MembershipA])), + ("the nil subject", () => AuditRedactionPlan.ForClosureTenant(Tenant, UserId.From(Guid.Empty), [MembershipA])), + ("no Membership", () => AuditRedactionPlan.ForClosureTenant(Tenant, Person, [])), + ("a nil Membership", () => AuditRedactionPlan.ForClosureTenant(Tenant, Person, [MembershipA, Guid.Empty])), + ("a duplicated Membership", () => AuditRedactionPlan.ForClosureTenant(Tenant, Person, [MembershipA, MembershipA])), + ("one Membership past the bound", () => AuditRedactionPlan.ForClosureTenant(Tenant, Person, [.. bounded, Guid.CreateVersion7()])), + }; + foreach (var (name, build) in refusals) + { + FluentActions.Invoking(build).Should().Throw(name); + } + } + + [Fact] + public void A_closure_sentinel_pass_reaches_only_the_platform_sentinel_by_the_subject_key() + { + var plan = AuditRedactionPlan.ForClosureSentinel(Person, Key); + + plan.Pass.Should().Be(AuditRedactionPass.ClosureSentinel); + (plan.TenantId, plan.OrganizationId, plan.WholeTenant, plan.SubjectUserId).Should().Be( + (TenantId.PlatformSentinel, (OrganizationId?)null, true, Person)); + plan.MembershipIds.Should().BeEmpty("the sentinel tenant holds no Membership"); + plan.SubjectKey.Should().BeSameAs(Key); + FluentActions.Invoking(() => plan.Subject).Should().Throw(); + } + + [Fact] + public void A_closure_sentinel_pass_refuses_a_system_or_nil_subject() + { + FluentActions.Invoking(() => AuditRedactionPlan.ForClosureSentinel(UserId.SystemActor, Key)).Should().Throw(); + FluentActions.Invoking(() => AuditRedactionPlan.ForClosureSentinel(UserId.From(Guid.Empty), Key)).Should().Throw(); + FluentActions.Invoking(() => AuditRedactionPlan.ForClosureSentinel(Person, null!)).Should().Throw(); + } + + [Fact] + public void No_plan_and_no_aggregate_prints_what_it_concerns() + { + var plans = new[] + { + new AuditRedactionPlan(new UserDataSubject(Guid.CreateVersion7(), DataRequestKind.Erasure, DataRequestOrigin.Self, Person, + new DataRequestScopeGroup(Tenant, null), [MembershipA])), + AuditRedactionPlan.ForClosureTenant(Tenant, Person, [MembershipA]), + AuditRedactionPlan.ForClosureSentinel(Person, Key), + }; + + plans.Select(plan => plan.ToString()).Should().AllBe(nameof(AuditRedactionPlan)); + new AuditRedactionAggregate(new Dictionary { [Tenant] = Report(1) }, Report(1)) + .ToString().Should().Be(nameof(AuditRedactionAggregate)); + } + + [Fact] + public void The_aggregate_sums_every_pass_and_lists_each_tenant_s_rows_selected_in_tenant_order() + { + var first = TenantId.From(Guid.Parse("0190aaaa-0000-7000-8000-000000000001")); + var second = TenantId.From(Guid.Parse("0190aaaa-0000-7000-8000-000000000002")); + var aggregate = new AuditRedactionAggregate( + new Dictionary + { + [second] = new(3, Columns(3, 3, 3, 1, 2, 0), Kinds(actor: 2, entity: 1, metadata: 4)), + [first] = new(5, Columns(5, 4, 5, 2, 0, 1), Kinds(actor: 3, entity: 2, metadata: 0)), + }, + new AuditRedactionReport(2, Columns(0, 0, 0, 0, 1, 0), Kinds(actor: 0, entity: 1, metadata: 2))); + + aggregate.ListsTenants.Should().BeTrue(); + aggregate.Tenants.Should().HaveCount(2); + aggregate.Total.RowsSelected.Should().Be(10); + Enum.GetValues().Select(column => aggregate.Total.Redacted[column]).Should().Equal(8, 7, 8, 3, 3, 1); + aggregate.Total.Retained.Select(entry => (entry.Kind, entry.Count)).Should().Equal( + (RetainedReferenceKind.AuditActorReference, 5L), (RetainedReferenceKind.AuditEntityReference, 4L), + (RetainedReferenceKind.AuditMetadataReference, 6L)); + + // Counts and tenant identifiers only, the tenants in identifier order, and the platform pass beside the total. + var expected = """ + {"tenant_count":2, + "rows_selected_by_tenant":{"0190aaaa-0000-7000-8000-000000000001":5,"0190aaaa-0000-7000-8000-000000000002":3}, + "platform":{"rows_selected":2,"redacted":{"ip_address":0,"user_agent":0,"actor_email":0,"before_state":0,"after_state":1,"changes":0}, + "retained":{"audit_actor_reference":0,"audit_entity_reference":1,"audit_metadata_reference":2}}, + "total":{"rows_selected":10,"redacted":{"ip_address":8,"user_agent":7,"actor_email":8,"before_state":3,"after_state":3,"changes":1}, + "retained":{"audit_actor_reference":5,"audit_entity_reference":4,"audit_metadata_reference":6}}} + """; + aggregate.ToClosedJson().Should().Be(JsonNode.Parse(expected)!.ToJsonString()); + } + + [Fact] + public void An_aggregate_with_no_served_tenant_is_its_platform_pass() + { + var platform = new AuditRedactionReport(2, Columns(0, 0, 0, 0, 1, 0), Kinds(actor: 0, entity: 1, metadata: 2)); + + var aggregate = new AuditRedactionAggregate(new Dictionary(), platform); + + aggregate.Total.ToClosedJson().Should().Be(platform.ToClosedJson()); + JsonNode.Parse(aggregate.ToClosedJson())!["rows_selected_by_tenant"]!.AsObject().Should().BeEmpty(); + } + + [Fact] + public void Beyond_two_hundred_tenants_the_document_carries_the_count_and_the_totals_alone() + { + var listed = new AuditRedactionAggregate(Tenants(AuditRedactionAggregate.MaximumListedTenants, rows: 1), Report(1)); + var aggregated = new AuditRedactionAggregate(Tenants(AuditRedactionAggregate.MaximumListedTenants + 1, rows: 1), Report(1)); + + listed.ListsTenants.Should().BeTrue(); + JsonNode.Parse(listed.ToClosedJson())!["rows_selected_by_tenant"]!.AsObject().Should().HaveCount(200); + aggregated.ListsTenants.Should().BeFalse(); + var document = JsonNode.Parse(aggregated.ToClosedJson())!.AsObject(); + document.Select(member => member.Key).Should().Equal("tenant_count", "platform", "total"); + document["tenant_count"]!.GetValue().Should().Be(201); + document["total"]!["rows_selected"]!.GetValue().Should().Be(202, "the totals still count every pass"); + } + + [Fact] + public void The_document_stays_under_its_bound_at_the_listing_s_limit_with_every_kind_and_the_largest_counts() + { + // Each tenant's counts as large as two hundred can be and still sum, every column and all sixteen kinds present. + var large = long.MaxValue / (AuditRedactionAggregate.MaximumListedTenants + 1); + var every = Enum.GetValues().Select(kind => new RetainedReferenceCount(kind, large)).ToArray(); + var report = new AuditRedactionReport(large, Columns(large, large, large, large, large, large), every); + var tenants = Enumerable.Range(0, AuditRedactionAggregate.MaximumListedTenants) + .ToDictionary(_ => TenantId.From(Guid.CreateVersion7()), _ => report); + + var json = new AuditRedactionAggregate(tenants, report).ToClosedJson(); + + Encoding.UTF8.GetByteCount(json).Should().BeLessThanOrEqualTo(AuditRedactionAggregate.MaximumClosedJsonBytes) + .And.BeLessThan(32 * 1024, "the intent and result rows each hold at most 32 KiB of state"); + } + + [Fact] + public void The_aggregate_refuses_the_sentinel_a_nil_tenant_a_missing_report_and_a_total_past_a_count() + { + var refusals = new (string Case, Func Build)[] + { + ("the platform sentinel as a tenant pass", () => new( + new Dictionary { [TenantId.PlatformSentinel] = Report(1) }, Report(1))), + ("the nil tenant", () => new(new Dictionary { [TenantId.From(Guid.Empty)] = Report(1) }, Report(1))), + ("a tenant without its report", () => new(new Dictionary { [Tenant] = null! }, Report(1))), + }; + foreach (var (name, build) in refusals) + { + FluentActions.Invoking(build).Should().Throw(name); + } + + FluentActions.Invoking(() => new AuditRedactionAggregate( + new Dictionary { [Tenant] = Report(long.MaxValue) }, Report(1))) + .Should().Throw("a total that does not fit is refused, never wrapped"); + } + + private static Dictionary Tenants(int count, long rows) => + Enumerable.Range(0, count).ToDictionary(_ => TenantId.From(Guid.CreateVersion7()), _ => Report(rows)); + + private static AuditRedactionReport Report(long rows) => + new(rows, Columns(rows, rows, rows, 0, 0, 0), Kinds(actor: rows, entity: 0, metadata: 0)); + + private static Dictionary Columns(long ip, long agent, long email, long before, long after, long changes) => new() + { + [AuditRedactedColumn.IpAddress] = ip, + [AuditRedactedColumn.UserAgent] = agent, + [AuditRedactedColumn.ActorEmail] = email, + [AuditRedactedColumn.BeforeState] = before, + [AuditRedactedColumn.AfterState] = after, + [AuditRedactedColumn.Changes] = changes, + }; + + private static RetainedReferenceCount[] Kinds(long actor, long entity, long metadata) => + [ + new(RetainedReferenceKind.AuditActorReference, actor), + new(RetainedReferenceKind.AuditEntityReference, entity), + new(RetainedReferenceKind.AuditMetadataReference, metadata), + ]; +} 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 000000000..670f9fbbf --- /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/backend/tests/LearnStack.Tests.Unit/SharedKernel/DataProtection/UserReferenceLocatorTests.cs b/backend/tests/LearnStack.Tests.Unit/SharedKernel/DataProtection/UserReferenceLocatorTests.cs new file mode 100644 index 000000000..0427eb2b1 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Unit/SharedKernel/DataProtection/UserReferenceLocatorTests.cs @@ -0,0 +1,104 @@ +using FluentAssertions; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Domain; +using LearnStack.SharedKernel.Identifiers; +using Xunit; + +namespace LearnStack.Tests.Unit.SharedKernel.DataProtection; + +/// The locator contract of ADR-0108 § 7: the closed path grammar and the checks a merged set of declarations passes. +public sealed class UserReferenceLocatorTests +{ + [Fact] + public void The_grammar_has_three_spellings_and_accepts_only_identifier_names() + { + UserReferencePath.Of("CreatedBy").ToString().Should().Be("CreatedBy"); + UserReferencePath.Member("FeatureFlags", "UpdatedBy").ToString().Should().Be("FeatureFlags/*/UpdatedBy"); + UserReferencePath.Elements("MembershipSnapshotJson").ToString().Should().Be("MembershipSnapshotJson/*"); + + foreach (var malformed in new[] { "", " ", "Created By", "a/b", "~0", "*", "1Created", "Créé", new string('a', 129) }) + { + FluentActions.Invoking(() => UserReferencePath.Of(malformed)).Should().Throw(malformed); + FluentActions.Invoking(() => UserReferencePath.Member(malformed, "UpdatedBy")).Should().Throw(malformed); + FluentActions.Invoking(() => UserReferencePath.Elements(malformed)).Should().Throw(malformed); + } + + UserReferencePath.IsName(new string('a', UserReferencePath.MaximumNameLength)).Should().BeTrue(); + FluentActions.Invoking(() => UserReferencePath.Member(null!, "UpdatedBy")).Should().Throw(); + } + + [Fact] + public void A_declaration_names_a_plain_entity_and_a_defined_kind() + { + new UserReferenceDeclaration(typeof(LocatorProbe), UserReferencePath.Of("Owner"), UserReferenceKind.User).EntityName.Should().Be("LocatorProbe"); + + FluentActions.Invoking(() => new UserReferenceDeclaration(typeof(List), UserReferencePath.Of("Owner"), UserReferenceKind.User)) + .Should().Throw("an audit row's entity_type is a plain CLR name"); + FluentActions.Invoking(() => new UserReferenceDeclaration(typeof(Nested), UserReferencePath.Of("Owner"), UserReferenceKind.User)) + .Should().Throw(); + FluentActions.Invoking(() => new UserReferenceDeclaration(typeof(LocatorProbe), UserReferencePath.Of("Owner"), 0)) + .Should().Throw(); + } + + [Fact] + public void A_retained_reference_is_an_entity_key_reported_as_the_entity_reference_with_a_reason() + { + UserReferenceDeclarations.OwnKey(typeof(LocatorProbe)).ReportedAs.Should().Be(RetainedReferenceKind.AuditEntityReference); + + FluentActions.Invoking(() => new RetainedUserReference(typeof(LocatorProbe), UserReferencePath.Of("Id"), + RetainedReferenceKind.AuditActorReference, "no")).Should().Throw(); + FluentActions.Invoking(() => new RetainedUserReference(typeof(LocatorProbe), UserReferencePath.Member("Items", "Id"), + RetainedReferenceKind.AuditEntityReference, "no")).Should().Throw(); + FluentActions.Invoking(() => new RetainedUserReference(typeof(LocatorProbe), UserReferencePath.Of("Id"), + RetainedReferenceKind.AuditEntityReference, " ")).Should().Throw(); + } + + [Fact] + public void Attribution_is_declared_once_per_auditable_entity_and_refused_for_anything_else() + { + UserReferenceDeclarations.Attribution(typeof(LocatorProbe)).Select(declaration => declaration.Path.ToString()) + .Should().Equal("CreatedBy", "UpdatedBy", "DeletedBy"); + UserReferenceDeclarations.Attribution(typeof(LocatorProbe)).Should().OnlyContain(declaration => declaration.Kind == UserReferenceKind.User); + + FluentActions.Invoking(() => UserReferenceDeclarations.Attribution(typeof(string))).Should().Throw(); + FluentActions.Invoking(() => UserReferenceDeclarations.Attribution()).Should().Throw(); + } + + [Fact] + public void A_merged_catalog_refuses_an_empty_locator_a_duplicate_path_a_name_clash_and_a_navigation_clash() + { + var owner = new UserReferenceDeclaration(typeof(LocatorProbe), UserReferencePath.Of("Owner"), UserReferenceKind.User); + var catalog = new UserReferenceCatalog([new Locator([owner, .. UserReferenceDeclarations.Attribution(typeof(LocatorProbe))], + [UserReferenceDeclarations.OwnKey(typeof(LocatorProbe))])]); + catalog.Redactable.Select(declaration => declaration.Path.ToString()) + .Should().Equal("CreatedBy", "DeletedBy", "Owner", "UpdatedBy"); + catalog.Retained.Should().ContainSingle(); + + Refused(new Locator([], [])); + Refused(new Locator([owner], []), new Locator([owner], [])); + Refused(new Locator([owner, new UserReferenceDeclaration(typeof(LocatorProbe), UserReferencePath.Elements("Owner"), UserReferenceKind.User)], [])); + Refused(new Locator([owner], [new RetainedUserReference(typeof(LocatorProbe), UserReferencePath.Of("Owner"), + RetainedReferenceKind.AuditEntityReference, "kept")])); + Refused(new Locator([new UserReferenceDeclaration(typeof(System.Threading.Timer), UserReferencePath.Of("Owner"), + UserReferenceKind.User)], []), new Locator([new UserReferenceDeclaration(typeof(System.Timers.Timer), UserReferencePath.Of("Lead"), + UserReferenceKind.User)], [])); + Refused(new Locator([owner, new UserReferenceDeclaration(typeof(LocatorProbe), UserReferencePath.Member("Owner", "Approver"), + UserReferenceKind.User)], [])); + } + + private static void Refused(params IUserReferenceLocator[] locators) => + FluentActions.Invoking(() => new UserReferenceCatalog(locators)).Should().Throw(); + + private sealed class Locator(IReadOnlyCollection redactable, IReadOnlyCollection retained) + : IUserReferenceLocator + { + public IReadOnlyCollection Redactable { get; } = redactable; + + public IReadOnlyCollection Retained { get; } = retained; + } + + private sealed class Nested; +} + +/// An auditable entity for the locator tests: its attribution columns are inherited. +internal sealed class LocatorProbe : AuditableEntity; diff --git a/docs/architecture/14-frontend-architecture.md b/docs/architecture/14-frontend-architecture.md index 92dc842ae..ecb42e727 100644 --- a/docs/architecture/14-frontend-architecture.md +++ b/docs/architecture/14-frontend-architecture.md @@ -354,6 +354,17 @@ purpose whose callback publishes nothing, and the Studio federation page. The the purposes, the closed forms and the page; [Security](../standards/11-security.md#federation-host-binding) owns the host binding. +Accepted [ADR-0106](../decisions/0106-subject-data-requests-authority-and-status.md) and +[ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) add the +person's data-request document `/account/data`, served by the same native owner on a +live session or on the retained entry, the administrator's Studio data-request pages, +and the first BFF binary relay: the export download, which streams the API's chunks +as one attachment and keeps its ticket inside the relay. The +[Frontend contract](../standards/07-frontend-architecture.md#subject-data-requests) +owns the routes, the closed forms and the relay; +[Security](../standards/11-security.md#retained-consent-subject-admission) owns the +owners and the ticket's confinement. + ## Page-Block Resolver The CMS stores pages as ordered lists of blocks. The renderer resolves each block to a diff --git a/docs/architecture/23-data-protection.md b/docs/architecture/23-data-protection.md index 201da2e43..a05045cb6 100644 --- a/docs/architecture/23-data-protection.md +++ b/docs/architecture/23-data-protection.md @@ -123,10 +123,47 @@ 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 + short-lived ticketed download in their live session, readable for a fixed period after + completion and revocable; no URL is a bearer credential. ADR-0107 § 4 owns both + lifetimes and the [Identity module](../modules/identity/README.md) the ticket bound. +- 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. +- Plaintext in memory is cleared on a best-effort basis only: the buffers the export + and download code own (the bundle's segments, each decrypted chunk, the parsed + ticket and chunk request bodies) are overwritten with zeros, but managed strings, + serializer internals, grown-and-discarded buffers and the runtime hold copies no + code can reach. API and worker process dumps and crash dumps therefore contain + personal data and secrets (the export key ring, session material) and are handled + as such: not collected by default, access-controlled when taken, and deleted after + use ([Data export runbook](../runbooks/data-export.md)). +- Delivered reach and counts (P03-10 Step 1). The + [Identity module's bundle sections](../modules/identity/README.md#export-bundle-sections) + own the section contents, the audit reach words, the caps and the retained counts; + this document states only what they mean for the person: + - **The audit section is not the person's whole audit trail.** The job reads under the + row policy without a tenant-wide witness, so an export reaches one group's rows and + says so in its first record (`complete` is `false`). Rows the person caused in an + organization where they have no Membership of any status reach **no** export of + theirs, because no export can be filed in a group without one. The "whole tenant" + reach of ADR-0107 § 3 and ADR-0108 § 4 is not delivered and needs its own decision. + - **A cap truncates and says so**; it does not fail the request. + - **The retained list is partial.** The tenant side counts the kinds its participants + own and the operator's completion sets the audit log's kinds from the redaction; a + kind not listed is retained and not counted, not zero. The web surface's retention + explanation names the classes with no subject-keyed count (P03-10 Step 4) and + Phase 11 owns the retention periods and the counting of the stores it purges. - 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 +200,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 +218,16 @@ 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). The request waits a 24-hour cancellable + window, and an administrator files it only for a person whose Membership is already + Revoked (ADR-0106 §§ 3, 11). +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 +246,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 @@ -292,6 +342,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 the retained-kind counts, classified `Audit` because they count the person's references; pseudonymous identifiers and counts, no content; 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, key-ring label, lifecycle, and the bundle's size, chunk count and immutable closed truncation statement (ADR-0107 § 3: collection names and counts), classified `Audit` because they measure the person's data; pseudonymous identifiers 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`; the digests outlive the ticket's expiry until Phase 11's retention purge nulls them | +| `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 @@ -444,8 +498,8 @@ admission event. The same per-row retention targets and existing metadata UPDATE restrictions apply. No new private Identity audit store or blanket metadata redaction grant follows. -P03-10's Identity closure coordinator and Audit redaction participant own subject/ -actor/context/receipt locators and truthful retained-copy reporting before their +P03-10's Identity closure coordinator and the Audit module's redaction executor own +subject/actor/context/receipt locators and truthful retained-copy reporting before their first affected writer. They must include these synchronous and volatile copies, not infer erasure from a deleted source row or logout. Phase 11 owns automatic purge, replay-table maintenance, backups and provider/diagnostic retained-copy @@ -521,13 +575,13 @@ remains in the phase Status block. `user_agent`, `before_state`, `after_state` and `changes`. `actor_user_id` remains immutable and `metadata` is outside that grant ([Audit append-only enforcement](31-audit-subsystem.md#append-only-enforcement)). - Phase 03 must decide the surviving actor/entity/causation references and new - causal metadata before its redaction/erasure handler lands; this inventory - does not claim that complete anonymisation already works. + [ADR-0108](../decisions/0108-privileged-audit-redaction.md) § 6 decides the + surviving actor, entity, causation and metadata references; this inventory does not + claim that complete anonymisation works. **Accepted identity fulfillment ownership — implementation remains P03-10.** P03-10's Identity closure coordinator owns the authorized lifecycle transition -and raw-subject removal. The Audit redaction participant uses +and raw-subject removal. The Audit redaction executor uses `IUserReferenceLocator` to locate exact global failed-attempt paths by subject key even when no User was committed, together with successful actor references and ADR-0077 authorization linkage. Its request/result contract reports retained immutable linkage and the applicable diff --git a/docs/architecture/31-audit-subsystem.md b/docs/architecture/31-audit-subsystem.md index ab3680f73..db315af61 100644 --- a/docs/architecture/31-audit-subsystem.md +++ b/docs/architecture/31-audit-subsystem.md @@ -1330,6 +1330,21 @@ CREATE INDEX ix_audit_log_correlation_id WHERE correlation_id IS NOT NULL; CREATE INDEX ix_audit_log_module_operation_timestamp ON audit_log (module, operation, timestamp DESC); +-- P03-10: the subject data-request statements (ADR-0107 § 3, § 6; ADR-0108 § 4). +CREATE INDEX ix_audit_log_tenant_id_entity_type_entity_id_timestamp + ON audit_log (tenant_id, entity_type, entity_id, timestamp DESC); +CREATE INDEX ix_audit_log_tenant_id_organization_id_person_reference + ON audit_log (tenant_id, organization_id, timestamp DESC) + WHERE organization_id IS NOT NULL + AND (metadata ? 'causal_actor_user_id' + OR (metadata -> 'authorization') ? 'causal_actor_user_id' + OR (metadata -> 'provider_event') ? 'affected_user_id'); +CREATE INDEX ix_audit_log_tenant_id_tenant_level_person_reference + ON audit_log (tenant_id, timestamp DESC) + WHERE organization_id IS NULL + AND (metadata ? 'causal_actor_user_id' + OR (metadata -> 'authorization') ? 'causal_actor_user_id' + OR (metadata -> 'provider_event') ? 'affected_user_id'); -- Row security is NOT written here. Database Standards owns the ordinary -- tenant-owned, ORG-SCOPED template and ADR-0072's accepted exact global-identity @@ -1338,16 +1353,28 @@ CREATE INDEX ix_audit_log_module_operation_timestamp -- the global branch adds only its exact confined owner evidence functions. ``` -**Four indexes, and deliberately not the org-scoped template's fifth.** The canonical -template carries `ix__tenant_id_organization_id` so the organization arm of the -policy has an index to read. This table does not take it. Every read the admin API -issues is tenant-scope — `audit.event.read` is a Tenant-scope permission +**Seven indexes, and deliberately not the org-scoped template's +`(tenant_id, organization_id)`.** The canonical template carries +`ix_
_tenant_id_organization_id` so the organization arm of the policy has an +index to read. This table does not take it. Every read the admin API issues is +tenant-scope — `audit.event.read` is a Tenant-scope permission ([§ 11](#11-querying-audit-log)) — so the arm that fires is -`current_setting('app.scope') = 'tenant'`, which no index serves, and the four above all -lead with a column those queries filter on. A fifth index on a high-volume append-only -table is a write cost paid on every row for a predicate arm the shipped readers do not -take. Phase 03's admin API is the place to revisit it, against a measured plan rather -than this paragraph. +`current_setting('app.scope') = 'tenant'`, which no index serves, and the indexes above +all lead with a column those queries filter on. Such an index on a high-volume +append-only table is a write cost paid on every row for a predicate arm the shipped +readers do not take. Phase 03's admin API is the place to revisit it, against a measured +plan rather than this paragraph. The three P03-10 indexes serve the subject data-request +statements, measured in the +[Audit module's performance budget](../modules/audit/README.md#performance-budget). The +person-reference indexes order the keyed rows rather than index the person: under the +row policy PostgreSQL applies a non-leakproof qual, and every JSON operator is one, only +after the policy, so no expression index on a `metadata` path can take a person's value +as an index condition. The keyed rows are split by organization into two partial +indexes so that each branch of a request's reach (its organization, the tenant-level +rows) is one newest-first seek that stops at the window: no organization's window reads +another organization's keyed rows only to drop them at the policy, and the tenant-level +branch has an index of its own because an `organization_id IS NULL` index condition +yields no order and would sort the whole branch. **`module` is the column; `ModuleName` is the CLR property.** The names differ in exactly one direction and for one reason: `CA1716` flags `Module` as an identifier that collides @@ -1363,10 +1390,10 @@ the same reason. The primary key is `audit_log_pkey` rather than `pk_audit_log`, because [ADR-0033](../decisions/0033-audit-durability-model.md) and [ADR-0016](../decisions/0016-audit-log-subsystem.md) both write it that way and two -Accepted records fix a name. The three `CHECK`s and the four indexes take the standard's -`ck_
_` and `ix_
_` forms, and so does the `TRUNCATE` trigger; -the only other divergence on this table is `audit_log_append_only_guard`, which two -Accepted records fix in the same way. +Accepted records fix a name. The three `CHECK`s and the seven indexes take the standard's +`ck_
_` and `ix_
_` forms, and so does the `TRUNCATE` +trigger; the only other divergence on this table is `audit_log_append_only_guard`, which +two Accepted records fix in the same way. The ordinary tenant policy shape is [Database Standards § Table classes](../standards/05-database.md)'s. Its [accepted global audit extension](../standards/05-database.md#proposed-global-central-audit-branch) @@ -1690,49 +1717,54 @@ 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` that changes any of them. `metadata` is also outside the six-column redaction grant and can retain causal actor and authorization Membership/Role references. -Preserving an attributable history is not proof of complete anonymisation. Phase 03 settles those references under -the [erasure first-writer prerequisites](23-data-protection.md#erasure-authority-and-first-writer-prerequisites) -before its redaction handler ships. P03-10's Audit participant locates the -accepted authorization metadata through retained actor/subject attribution and -reports surviving references; no metadata UPDATE authority follows. +Preserving an attributable history is not proof of complete anonymisation. Phase 03 +settles those references under the +[erasure first-writer prerequisites](23-data-protection.md#erasure-authority-and-first-writer-prerequisites) +as [ADR-0108](../decisions/0108-privileged-audit-redaction.md) § 6 decides. P03-10's +Audit participant locates the accepted authorization metadata through retained +actor/subject attribution and reports surviving references; no metadata UPDATE authority +follows. Every module that stores user references in audit payloads registers an `IUserReferenceLocator`. [Phase 03 P03-10](../roadmap/phase-03-identity-admin.md#inherited-architecture-obligations) owns its applicable-module census and the handler above; P03-1 supplies their global User prerequisite. Neither creating that table nor its PII census grants the privileged redaction writer. The rule -`Every_PII_Module_RegistersUserReferenceLocator` is registered in -[the catalogue](../standards/21-architecture-tests-catalogue.md) against that phase — -unasserted until then, because a rule naming a phase's absent types would only fail. +`Every_PII_Module_RegistersUserReferenceLocator` in +[the catalogue](../standards/21-architecture-tests-catalogue.md) asserts the census, and +each declared path has a canary that proves the executor redacts it. ## 11. Querying audit log @@ -1886,12 +1918,9 @@ update it constrains. **owner**, whom only the two triggers stop — `UPDATE` by the row guard and `TRUNCATE` by the statement guard. -`Every_PII_Module_RegistersUserReferenceLocator` is registered in the catalogue against -[Phase 03](../roadmap/phase-03-identity-admin.md) and is deliberately **unasserted** until -P03-10 supplies the locators and erasure handler, consuming P03-1's User foundation. -A rule naming types no packet has built could only fail. It is absent from the Packet 9 -list above for that reason and no other — the catalogue row, not this list, is where its -status lives. +`Every_PII_Module_RegistersUserReferenceLocator` is absent from the Packet 9 list above +because P03-10 supplies the locators and the redaction executor it asserts, consuming +P03-1's User foundation; the catalogue row, not this list, is where its status lives. `Audit_Config_Failure_Rejects_Operation` from the earlier draft is **withdrawn**, not renamed: under ADR-0033 as settled, a tenant-override read failure falls back to the @@ -1912,7 +1941,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 +1964,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 87a6729d2..82a73668c 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 dda460793..940b22375 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 6299d71fe..d81b9e27f 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 256efc2c1..0f20b6262 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 6edc825c6..f55504f71 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 56b773680..df7b3590b 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 46ddbad05..1f4234ae2 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 a76338a88..d632d701f 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 3650049d4..04f775d20 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 06e134d7c..b4ba41b08 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 496bc6cd1..b483a157c 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 000000000..14c5edf2d --- /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 000000000..12a199174 --- /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 000000000..8269acbb3 --- /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 7d64aa6b0..2d007c78b 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -141,13 +141,16 @@ 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. | | 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 09c2a7434..f59db0e1a 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -298,6 +298,18 @@ 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). | +| **Retained entry** | The web's use of the retained own scope: `/account/data` served on the sign-in entry owner instead of a live session, for any group where the person holds or held a Membership. It lives at most five minutes from the start of sign-in and is never extended ([Frontend Architecture § Subject data requests](standards/07-frontend-architecture.md#subject-data-requests), [Security](standards/11-security.md#retained-consent-subject-admission)). | +| **Retained group** | A scope group reached through the retained own scope: one where the person holds or held a Membership of any status or has a data request. The browser names it only as `tenant` or an organization UUIDv7, and `fn_identity_own_data_request_scopes` proves it for the entry owner on every operation ([ADR-0106](decisions/0106-subject-data-requests-authority-and-status.md) § 9). | +| **Export ticket** | The download cursor of one export artifact: minted by a CSRF-protected POST for one session binding, valid 15 minutes, stored only as a digest, consumed with the final chunk, and bounded to three open per binding and artifact and twenty ever per artifact. It authorizes the chunk reads of one download and never appears in a URL, a page or a log ([ADR-0107](decisions/0107-data-request-fulfillment-and-account-closure.md) § 4). | +| **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. | +| **Erasure witness** | The sealed, single-purpose proof that an erasure request is `fulfilling` and not deleted; only the erasure service mints it, and the Membership and Invitation erasure operations run only under it for the request's subject and group ([ADR-0107](decisions/0107-data-request-fulfillment-and-account-closure.md) § 5). | +| **User reference locator** | A module's declaration of the audited properties that hold a person or Membership reference (`IUserReferenceLocator`): the paths the audit redaction rewrites and the key references it retains. It performs no SQL and holds no privilege ([ADR-0108](decisions/0108-privileged-audit-redaction.md) § 7). | +| **Audit redaction** | The operator's act on a subject's audit rows, run by the Audit module's one executor on the platform scope: the address, user agent and e-mail become NULL, and the person's identifiers at the paths the modules declare in the three JSON columns become the redaction sentinel; every other column stays ([ADR-0108](decisions/0108-privileged-audit-redaction.md)). | | **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 4f23937e9..3b4c0128b 100644 --- a/docs/modules/audit/README.md +++ b/docs/modules/audit/README.md @@ -25,9 +25,10 @@ packet. Rows marked 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` +[Phase 03](../../roadmap/phase-03-identity-admin.md). The GDPR redaction path is +delivered: 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)). @@ -106,11 +107,11 @@ know before touching it. nothing else, which is what keeps that impossible. The **ports** those types implement live in `LearnStack.SharedKernel.Audit`, beside the value types every module's catalogue source names. -- **The log's own retention or redaction.** Redaction is Phase 03's and the purge Phase - 11's; both run as - `learnstack_platform` through the audited `EnterPlatformAdminScope(reason)` path, and - both are already bounded by what this packet's migration grants: a `DELETE`, and an - `UPDATE` restricted to six columns. +- **The log's own retention or redaction.** Redaction is the privileged step of an + erasure and of a closure's Finalize, and the purge is Phase 11's; both run as + `learnstack_platform` through the audited platform scope, and both are bounded by + what this packet's migration grants: a `DELETE`, and an `UPDATE` restricted to six + columns. The redaction's one executor ships; the purge has no caller yet. - **Anything a reader would call a metric.** Counters, latencies and error rates are [ADR-0032](../../decisions/0032-exception-handling-logging-and-observability.md)'s, and an audit row is not a log line: it is a record a regulator reads and a tenant @@ -413,6 +414,11 @@ audited request rather than by a reader. | In-transaction `INSERT` | < 1 ms | One parameterised statement on a connection that is already open and already has its tenant announced. It adds no round trip of its own. | | Standalone write | < 5 ms | Its own connection, its own `BEGIN`/`COMMIT`, and two `set_config` calls. Off the happy path — it runs for `denied`, for a rolled-back business write, and for the commit-in-doubt re-write. | | Read, tenant's own log, newest first | < 50 ms p95 | `ix_audit_log_tenant_id_timestamp` answers it as an index scan. The budget is Phase 03's to hold; it is here because the index that serves it ships now. | +| Data-request selection, count and actor/entity counts (P03-10) | Bounded by the subject's own rows, under a 15 s statement budget | Unions of equality branches on `ix_audit_log_actor_user_id_timestamp` and `ix_audit_log_tenant_id_entity_type_entity_id_timestamp`. Measured at 1.9 million rows of one tenant: about 2 ms each, against 140–235 ms for the single `OR` predicate they replaced, whose parallel scan grows with the tenant. | +| Data-request metadata count (P03-10) | Bounded by `MetadataScanWindow` (500,000 keyed rows) per branch of the reach | The causal-actor and affected-user references cannot be index conditions under the row policy (JSON operators are not leakproof), so each branch of the reach, the group's organization and the tenant-level rows, is a newest-first seek cut at the window, on `ix_audit_log_tenant_id_organization_id_person_reference` and `ix_audit_log_tenant_id_tenant_level_person_reference`; `audit_metadata_reference` is a lower bound past a window. Measured at 2.3 million rows, 2,000,000 of them keyed rows of one organization: about 1 ms for an organization with no keyed rows of its own, against 2.2–3.4 s (2,000,000 rows read and removed by the row policy) for the single tenant-keyed window it replaced; 1.2–1.6 s for the organization whose branch fills a window, as before; about 1 s for a tenant-level branch of 601,000 keyed rows, stopping at the window with no sort. | +| Redaction selection (P03-10, [ADR-0108](../../decisions/0108-privileged-audit-redaction.md)) | One statement per batch of at most 100,000 of the tenant's rows or 64 MiB of decompressed payload in the reach, newest first, each under a 30 s statement budget; the act's time grows with the tenant's decompressed payload | The actor and entity branches are index-served (`ix_audit_log_actor_user_id_timestamp`; `ix_audit_log_tenant_id_entity_type_entity_id_timestamp` by a skip scan over the entity types). A payload or metadata reference has no index, so each batch is a range of the key `("timestamp", id)` along `ix_audit_log_tenant_id_timestamp`, whose payload columns are walked once for the identifiers and rewritten only when that filter keeps the row. A boundary statement ends the batch at the row cap or where the decompressed size of the payload columns of its rows in the reach reaches the byte budget, because the selection and the rewrite work in proportion to decompressed bytes, which a compressible document can make tens of times its stored size: an uncompressed value is sized by `pg_column_size` without detoasting, a compressed one is decompressed once to be measured, and a row outside the reach counts nothing. Measured on PostgreSQL 18.4 with 1 GB of shared buffers, before and after the budget counted decompressed bytes. At 1.5 million rows of one tenant (1.5 GB stored, 9.8 GB decompressed): 155 batches instead of 24, every statement at most 0.34 s; 12.1–12.9 s for a whole-tenant act instead of 7.1–8.5 s, 3.2 s for an organization group's instead of 1.3–1.5 s, 4.2–5.2 s for the tenant-wide group's instead of 2.7–3.3 s; the difference is the boundary's decompression. At 30,000 rows of 250 KB documents that compress to 3 KB (88 MB stored, 7.2 GB decompressed): 112 batches, every statement at most 0.04 s, 3.0–4.0 s for a whole-tenant act; counted by stored size, two batches of 3.7 GB each took up to 1.15 s per statement, unbounded on a slower host. At 10,000 documents of 2,000 keys (78 MB stored, 660 MB decompressed): 10 batches of at most 0.12 s instead of 2 of 0.9 s. At 150,000 rows each carrying 100 KiB of incompressible payload (14 GB stored, which is also its decompressed size, so its batches did not change): 230 batches of about 650 rows, every statement at most 2.0 s, 215–243 s for a whole-tenant act; batches of 100,000 rows put about 10 GB in the first statement, which ran past its 30 s budget on every attempt. JIT is off for these statements: with it a batch took 1.6–3.1 s and a whole-tenant act 41–42 s. The payload filter tests two spellings of every identifier, and a closure's tenant pass carries every Membership the person holds in the tenant, up to 256, so up to 514 spellings. Tested against the walked array, the filter's cost is the spellings times the strings: at 1.5 million rows such a pass took 76–80 s, every statement at most 0.70 s, against 12 s for a pass of two Memberships. From 128 spellings (`AuditRedactionExecutor.SetLookupFrom`) the filter looks each walked string up in the spellings as a hashed set instead, and the same pass took 21.6–23.2 s, every statement at most 0.20 s, on a host shared with other work. Over 300,000 rows the array test took 2.1 s at 6 spellings and 16.7 s at 514, and the set lookup 4.0–5.5 s at any count, its unnest paid on every row, so the two cross at about 110 spellings and a pass of fewer keeps the array test. | +| Redaction sentinel pass (P03-10, a closure's Finalize, [ADR-0108](../../decisions/0108-privileged-audit-redaction.md) § 4) | The selection's batches over the platform sentinel tenant: one statement per batch of at most 100,000 rows or 64 MiB of decompressed payload, each under the 30 s statement budget; the pass's time grows with the sentinel tenant's rows, about one global creation row per person | No index serves `metadata ->> 'identity_subject_key'`, and none is added: each batch is a range of `ix_audit_log_tenant_id_timestamp` whose rows the subject key, the subject as actor and the subject's `User` as entity filter, and only the few rows naming the person are rewritten. Measured on PostgreSQL 18.4 with 1 GB of shared buffers at 1.53 million sentinel rows (1.5 million creation rows in the capture's shape and 30,000 operator rows, 2.9 GB of heap): 35 batches; each selection statement at most 81 ms (44,000 rows in 34 ms on that index); each boundary statement, which then sized the payload of every row of the batch, at most 0.14–2.0 s; 4.3–13.6 s for the pass, the spread coming from a host shared with other work. The sentinel selection walks no payload, so its boundary now sizes none (`@size_payload` is false) and the row cap alone ends a batch: re-measured on the same data and a shared host, 16 batches instead of 35, each boundary at most 0.53–0.93 s and each selection at most 0.13 s, 1.8–4.5 s for the pass against 2.1–5.7 s with the sizing, and 33 s with the sizing from a cache the tenant passes had just filled. No statement came near its budget. | +| Redaction rewrite (P03-10) | At most 1,000 selected rows of one batch per statement | Each statement locks and rewrites its rows by primary key, touching only the six granted columns, and keeps the stored value of a payload column the redaction leaves equal, so an unchanged large payload is not recompressed and logged again: 277 rows in 31–35 ms, the re-run rewrote nothing in under 10 ms, no statement took more than 27 ms on the 14 GB tenant, and decompressed payload was rewritten at 17–165 MB a second. | Two budget-shaped facts that are not latency: @@ -420,12 +426,15 @@ Two budget-shaped facts that are not latency: retention purge in this packet, deliberately — audit correctness cannot be added later and audit scale can, and the platform has no rows yet to scale ([ADR-0028's 2026-09-07 amendment](../../decisions/0028-audit-log-partition-management.md)). -- **Four indexes, not five.** The canonical organization-scoped template carries an index - on `(tenant_id, organization_id)`; this table does not take it, because a fifth index on - a high-volume append-only table is a write cost paid on every row for a predicate arm - the shipped readers do not take. The reasoning is in - [Audit Subsystem § 7](../../architecture/31-audit-subsystem.md), and Phase 03's admin - API is where to revisit it against a measured plan. +- **Seven indexes, still not the template's `(tenant_id, organization_id)`.** The + canonical organization-scoped template carries an index on + `(tenant_id, organization_id)`; this table does not take it, because it is a write + cost paid on every row for a predicate arm the shipped readers do not take. The + reasoning is in [Audit Subsystem § 7](../../architecture/31-audit-subsystem.md), and + Phase 03's admin API is where to revisit it against a measured plan. P03-10 added the + three data-request indexes measured above: the entity index takes an entry for every + row, and a row carrying a causal-actor or affected-user key takes one entry in one of + the two person-reference indexes, split by whether it has an organization. ## Risks and open questions @@ -447,7 +456,7 @@ Two budget-shaped facts that are not latency: that seeds the row as the migration role rather than by any shipped caller. - **Retention is unowned until Phase 11.** The purge and the partition-management job sit behind the same trigger — measured `audit_log` growth. GDPR redaction is not on it: - it is triggered by an erasure and lands with Phase 03's erasure handler. The grants all + an erasure triggers it, and its executor ships with Phase 03's erasure. The grants all three need are already written, which is the part that could not be added later without a migration on a table nobody may rewrite. - **The read API's shape is Phase 03's to settle.** The four permission keys and the diff --git a/docs/modules/audit/audit.md b/docs/modules/audit/audit.md index 4792f4ebd..21b843692 100644 --- a/docs/modules/audit/audit.md +++ b/docs/modules/audit/audit.md @@ -26,8 +26,7 @@ observation below uses that pipeline under [ADR-0097](../../decisions/0097-retained-provider-events-and-tenant-audit-mirror.md). The query API and export job remain in [Phase 03](../../roadmap/phase-03-identity-admin.md), the override editor in -[Phase 06](../../roadmap/phase-06-renderer-admin-studio.md), redaction with Phase 03's -erasure handler, and retention in +[Phase 06](../../roadmap/phase-06-renderer-admin-studio.md), and retention in [Phase 11](../../roadmap/phase-11-production-hardening.md). Those future rows carry `(planned)`, a claim `Every_Matrix_Row_Whose_Command_Exists_Is_Registered` re-checks on every run: a `(planned)` row whose command has since shipped fails. @@ -46,8 +45,10 @@ matches `audit.event.read` in [permissions.md](permissions.md). Two resource segments have no permission key to agree with, and keep their own names for the reason `tenancy.tenant_assertion.*` keeps its prefix: the key that gates them is -Platform-scope, does not share the `audit.` module segment, and has no name yet — -[permissions.md](permissions.md) records who names it. +Platform-scope and does not share the `audit.` module segment. +`audit.redaction.apply` is gated by `platform.data_request.write`; +`audit.purge.apply` has no key yet, and [permissions.md](permissions.md) records who +names it. `audit.redaction.apply` is the spelling [Audit Subsystem § 10](../../architecture/31-audit-subsystem.md) already writes into the draft it shows, and `audit.purge.apply` is its twin — one resource per act, one verb @@ -55,13 +56,13 @@ each, rather than two more verbs on `event`, which is the resource a tenant read | Resource | Operation | Class | Notes | |---|---|---|---| -| `provider_event` | `audit.provider_event.observe` | **MUST** (`security-event`) | `ProviderEventObservationHandler` consumes the required transport-owned inbox. Closed typed evidence records a retained account-history observation, with SystemActor separate from the affected User and processing outcome/time separate from provider outcome/time. No tenant-login or human-G13 proof is inferred. | +| `provider_event` | `audit.provider_event.observe` | **MUST** (`security-event`) | `ProviderEventObservationHandler` consumes the required transport-owned inbox. Closed typed evidence records a retained account-history observation, with SystemActor separate from the affected User and processing outcome/time separate from provider outcome/time. No tenant-login or human-G13 proof is inferred. A delivery whose affected person's User is no longer Active, as the Identity fact reader judges it under that person's User fence ([ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) §§ 7, 9), withholds the observation: the intent is withdrawn before anything is written, so the delivery completes as a recorded no-op with its inbox row and no row naming a closing or closed person; only this subscriber withholds, with the evidence it alone mints. | | `event` | `audit.event.read` `(planned)` | **SHOULD** (`read-sensitive`) | Someone read a tenant's audit trail. SHOULD rather than MUST because a tenant admin reading their own log is ordinary administration, and a MUST here would make every page of the audit screen write a row into the table it is paging — which is the one place a self-referential write compounds. The tenant may narrow it; the platform-scope read below cannot be narrowed | | `event_export` | `audit.event_export.write` `(planned)` | **MUST** | An export produces a file containing the log, outside every policy in this schema and outliving the request that asked for it. The row records who asked and for what range; the file's own retention is [Phase 03](../../roadmap/phase-03-identity-admin.md)'s to settle | | `event_export` | `audit.event_export.read` `(planned)` | **MUST** | Collecting the file is a separate act from asking for it, often by a different principal and always at a different time. Two grants in [permissions.md](permissions.md), two rows here | | `config` | `audit.config.write` `(planned)` | **MUST** | A tenant narrowed its own SHOULD/MAY coverage. Recording it is what keeps the narrowing itself visible — an override that could be set without a trace would be the first move of anyone reducing what the log will show. The floor holds regardless: `ClassifyAsync` re-applies the catalogue's MUST after the override ([ADR-0033](../../decisions/0033-audit-durability-model.md)) | | `config` | `audit.config.delete` `(planned)` | **MUST** | The override removed, restoring baseline coverage. Recorded for the same reason and with the same weight as setting it: a reader of the log must be able to reconstruct what coverage was in force at any moment | -| `redaction` | `audit.redaction.apply` `(planned)` `(off-path)` | **MUST** (`security-event`) | The GDPR erasure path of [Audit Subsystem § 10](../../architecture/31-audit-subsystem.md), restricted by the column grant to `actor_email`, `ip_address`, `user_agent`, `before_state`, `after_state`, `changes`. `actor_user_id` is deliberately never redacted — it remains a pseudonymous, potentially linkable identifier. Phase 03's bounded first-writer decision must address surviving references before claiming complete anonymisation. `(off-path)`: it runs as `learnstack_platform` inside `EnterPlatformAdminScope(reason)`, so there is no request type to key a catalogue entry on | +| `redaction` | `audit.redaction.apply` `(off-path)` | **MUST** (`security-event`) | The privileged half of an erasure ([ADR-0108](../../decisions/0108-privileged-audit-redaction.md)): an operator act in the platform scope, `complete_erasure` of [ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) § 8, under the Platform key `platform.data_request.write`. One Audit-owned executor redacts the subject's `ip_address`, `user_agent` and `actor_email`, and the string values at the references each module's locator declares in `before_state`, `after_state` and `changes`, in the same platform transaction that completes the request and writes this row. The row names the request's real tenant, carries no actor and holds a closed report of the rows redacted per column and the retained references per kind, never a person identifier. `actor_user_id`, `entity_id`, the causation and correlation identifiers and `metadata` are deliberately never redacted: they stay a pseudonymous, linkable identifier and the report says so. A global account closure's Finalize runs the same executor over every participant tenant and the platform sentinel tenant, where it selects the person's global creation rows by the subject key in `metadata`, and records it on its own intent row, `platform.closure.finalize_attempt` in [Tenancy's matrix](../tenancy/audit.md), not on this slug. `(off-path)`: the platform scope is a service, so there is no request type to key a catalogue entry on, and the slug names the Audit module because the operator result write refuses `identity` | | `purge` | `audit.purge.apply` `(planned)` `(off-path)` | **MUST** (`security-event`) | Retention removed rows. One row per purge run rather than per deleted row, carrying the range and the count — a per-row record of a per-row deletion is a log that grows faster than the purge shrinks it. It stays a row-level `DELETE` after [Phase 11](../../roadmap/phase-11-production-hardening.md) partitioning — one monthly partition holds many tenants and retention classes — and dropping a whole partition past the platform's maximum retention is [ADR-0028](../../decisions/0028-audit-log-partition-management.md)'s separate partition-management job. `(off-path)` for the same reason as redaction | ## What is deliberately not here @@ -110,9 +111,9 @@ when it does. Each row takes its OperationType/domain's target from [Standard 18 Retention](../../standards/18-audit-coverage.md#retention), not a blanket MUST-class period. Automatic purge and retention overrides remain unimplemented -until Phase 11, so rows can outlive their targets. The planned purge/redaction -security events preserve evidence of the maintenance act; retention machinery -must apply the canonical policy when admitted. +until Phase 11, so rows can outlive their targets. The redaction's result row and the +planned purge's security event preserve evidence of the maintenance act; retention +machinery must apply the canonical policy when admitted. diff --git a/docs/modules/audit/permissions.md b/docs/modules/audit/permissions.md index 90dfc55a9..c0cfac936 100644 --- a/docs/modules/audit/permissions.md +++ b/docs/modules/audit/permissions.md @@ -28,17 +28,24 @@ Tenant or Organization and this one is the only Platform key the module declares **`event` has no `write`, no `delete` and no `admin`, and the absence is the point.** Every other resource in the corpus gets the actions its commands need. This one has no command at all: rows arrive from `PostgresAuditStore` on behalf of the operation being -audited, and the two mutating paths that exist — GDPR redaction, which lands with the -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 -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. -`learnstack_app` holds `SELECT, INSERT` on `audit_log` for the central store; that -database grant does not create an assignable `audit.event.write` capability. +audited, and the two mutating paths, GDPR redaction and the retention purge, which lands +in [Phase 11](../../roadmap/phase-11-production-hardening.md), run as +`learnstack_platform` in the platform scope an operator's admission opens and are gated +by a Platform-scope key rather than a tenant-facing one. The redaction's 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), registered in the +Platform catalogue with the operations `audit.redaction.apply` and +`platform.closure.finalize`: the scope hands the redaction to those two operator acts +alone, each for its own plans, through the one Audit-owned executor, in the transaction +that completes an erasure ([runbook](../../runbooks/data-erasure.md)) and in the first +transaction of a closure's Finalize, which commits it with the act's intent row +([ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) § 7). +Phase 11's purge takes the same key or a sibling it names, so no writer of `audit_log` +lands with a permission nobody has declared. Tenant-facing audit-row creation is not an +admitted operation. `learnstack_app` holds `SELECT, INSERT` on `audit_log` for the +central store; that database grant does not create an assignable `audit.event.write` +capability. **Export is a sub-resource, because the action set is closed.** `export` is not one of `read | write | delete | admin`, and diff --git a/docs/modules/identity/README.md b/docs/modules/identity/README.md index 8e363234a..91247301d 100644 --- a/docs/modules/identity/README.md +++ b/docs/modules/identity/README.md @@ -109,6 +109,28 @@ consumer uses the ordinary inbox and central typed-evidence writer. The [provider specification](providers.md#retained-user-event-reader) owns adapter and deployment configuration; the phase Status owns final qualification. +A delivery of the tenant mirror refuses a person whose User is no longer Active, as +intake does +([ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) §§ 7 +and 9): the fact reader asks the confined definer +`fn_identity_provider_event_subject_status` for the affected person's status under that +person's User fence held shared, so the read orders against a closure's Begin and +Finalize, and the Audit subscriber then withholds its observation. The delivery +completes as a recorded no-op with its inbox row and no audit row, and a replayed +delivery runs the same rule. + +The identity-provider ports are four: `IIdentityEventProvider` (read-only history), +`IFederationProvider` with `IFederationEgressFetcher` and `IFederationOperator` +(tenant federation), and `IIdentityProviderAccountRemoval` +([ADR-0107 § 7](../../decisions/0107-data-request-fulfillment-and-account-closure.md)), +whose one deleting method deletes one account for the closure's Finalize alone, beside +a local preflight (`CanRemove`) the closure's Begin asks before the person leaves +Active. Each has a fail-closed default (the account-removal one is +`RefusingIdentityProviderAccountRemoval`, whose preflight answers no) and a confined +Keycloak adapter selected at the composition root only when its own client secret is +configured; the [provider specification](providers.md#account-removal-adapter) owns the +account-removal adapter. + ### Aggregate and storage contract User's authority is [ADR-0072](../../decisions/0072-application-owned-identity-bootstrap.md); @@ -284,7 +306,9 @@ guard rejects direct resurrection, inconsistent status/deletion markers and transitions outside the diagram. Active/Suspended share current uniqueness; Revoked is terminal. Rejoin creates a new ID and fresh assignments after retiring the predecessor. Profile has no independent delete/status lifecycle; historical -child facts cannot restore a revoked Membership's authority. +child facts cannot restore a revoked Membership's authority. The one write a Revoked +Membership admits is the erasure's clearing of its profile +([Tenant erasure](#tenant-erasure-p03-10-step-2)). Profile carries optional contextual `DisplayName` (128 characters) and `PreferredLocale` (35-character well-formed locale tag), both marked sensitive. @@ -318,12 +342,17 @@ templates, without a bootstrap Boolean, receipt or table. Trial, Active and Suspended retain their admin. No Archived/termination exemption exists until separately admitted by G13/G16. Final-admin removal/suspension/revocation or kernel stripping refuses. -Future global closure cannot make the final admin ineligible before its separate -recovery/termination authority and guards are Accepted and implemented. +A global closure's Begin refuses `blocked_last_administrator` for the only eligible +tenant-wide administrator of a tenant that allows ordinary work; a tenant that does not +is the named exception of +[ADR-0107 § 7](../../decisions/0107-data-request-fulfillment-and-account-closure.md) +and is not judged. P03-1 supplies the bounded Tenancy Application.Contracts port -`IIdentityScopeLifecycleReader.ReadAsync(TenantId, OrganizationId?, CancellationToken)`. -Its immutable `IdentityScopeLifecycle` result has four Booleans: +`IIdentityScopeLifecycleReader.ReadAsync(TenantId, OrganizationId?, CancellationToken)`; +a closure's Begin reads the same facts for every participant group at once with +`ReadOnPlatformScopeAsync`, on the platform scope's handle and in one statement over +Tenancy's own tables. Its immutable `IdentityScopeLifecycle` result has four Booleans: `TenantExistsAndNotDeleted`, `TenantAllowsOrdinaryWork`, `OrganizationBelongsToTenant` and `OrganizationAllowsOrdinaryWork`. Organization facts are false when no organization is requested; it returns no row or list. @@ -810,6 +839,549 @@ 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` | +| `POST identity/me/data-requests/erasures` | `identity.data_request.create_own_erasure` | `CreateOwnDataErasureCommand` | +| `POST identity/me/data-requests/closures` | `identity.data_request.create_own_closure` | `CreateOwnAccountClosureCommand` | +| `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` | +| `POST identity/data-requests/erasures` | `identity.data_request.create_erasure` | `CreateDataErasureForSubjectCommand` | +| `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 or erasure job is dead (an + erasure's only after its window ended) 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. +- **One readable artifact, the subject's.** A completed export revokes the subject's + previous available artifact in the group before it stores its own (ADR-0107 § 4). The + subject's own export may do so; an administrator's may not: while the subject holds a + readable artifact in the group, of any origin, an administrator's creation is refused + with `409 business_rule_violation` and `errors.$ = lockey_subject_export_available`, + judged by the database clock under the creation fences. It can be filed once that + artifact is revoked or has expired. One active export per subject and group means no + export can store an artifact between that read and the insert. +- **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`; a chunk the store cannot open (its key left the ring, or it fails + authentication) is answered the same way and logged with identifiers only: critical + the first time an artifact is refused under a key label in the process, a warning for + each repeat (`DataExportCustodyRefusals`, a bounded per-process memory). The chunk is + written as `{index, count, bytes}` straight from its plaintext buffer, which is then + zeroed, and the ticket and chunk request bodies are read into a buffer that is zeroed + once parsed (best effort: managed strings are beyond reach); responses are + `no-store`. +- **Ticket bounds.** Ticket rows and their MUST audit rows are permanent, so minting is + bounded, counted under the artifact's row lock in one statement: + `DataRequestLimits.MaximumOpenTicketsPerBinding` unconsumed, unexpired tickets per + session binding (a slot frees when one is consumed by its final chunk or expires; a + ticket left open by a credential since refreshed does not count against the new one) + and `DataRequestLimits.MaximumTicketsPerArtifact` tickets ever per artifact, consumed + or not, which is final. A bound reached is `409 business_rule_violation` with + `errors.artifact = lockey_data_export_ticket_limit`: wait, or, past the per-artifact + bound, file a new export. An artifact that is gone, unreadable or sealed under a key + the export key ring no longer holds is `errors.artifact = + lockey_data_export_unavailable`: only a new export helps. The OpenAPI document states + the numbers from the same constants. +- **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. + +#### 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 erasures?group=` | `identity.data_request.create_retained_erasure` | `CreateRetainedDataErasureCommand` | +| `POST closures?group=` | `identity.data_request.create_retained_closure` | `CreateRetainedAccountClosureCommand` | +| `POST revocations?group=` | `identity.data_request.revoke_retained_export` | `RevokeRetainedDataExportCommand` | +| `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 nine 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.** Export creation, cancellation, erasure creation, artifact + revocation and closure filing are `ProtectedAdministrationOperation`s 30, 31, 34, 35 + and 37. Creation answers `202` with `{id, kind, status, version}` and its `ETag` and + no `Location` (there is no per-request route); an erasure's answer is `scheduled` and + its receipt shows `executeAt`, the end of the cancellable window; cancellation needs + `If-Match`, and a revocation's `If-Match` is the artifact's version. 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. + +#### Web surface (P03-10 Step 4) + +The person's own page is the native `/account/data` document of +[Frontend Architecture § Subject data requests](../../standards/07-frontend-architecture.md#subject-data-requests): +the live session's group through the own routes above, the retained groups through the +retained entry, the erasure and closure confirmations, and the export download relayed +chunk by chunk as one attachment. Its copy names every refusal reason these routes emit, +and the retained classes no count reaches. + +The administrator's surface is Studio's `/studio/data-requests` list and request page, +the erasure page `/studio/data-requests/erasure` and a section of the member page, for a +holder of `identity.membership.admin` in the context's group through the administrator +routes above. It shows each request's status, dates, filer, retained counts and file +size, never a closure and never the bundle: the page says the file reaches only the +person. A receipt names its subject by the frozen Membership, so the list names it with +the same audited member read the member page makes, and never reads a subject known to +be Revoked, whose detail the API refuses. The member section files an export for that +Membership. A Revoked Membership has no member page, so a successful revocation leads to +the erasure page, which reads nothing about it and files the erasure behind an explicit +confirmation that states what is erased and kept and the 24-hour window. Only the +administrator who filed a request sees its cancel and revoke forms. Each refusal reason +of these routes has its own sentence; the copy shares the person's catalogue where the +wording is the same. + +#### Account closure filing (P03-10 Step 3) + +The person files the global account closure of +[ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) § 7 +from one group, its originating group: through a live session +(`POST identity/me/data-requests/closures`, `ProtectedAdministrationOperation` 36) or +the retained entry (`POST closures?group=`, 37). The closure itself is global; its row +lives in the originating tenant. Begin, the per-group fan-out and Finalize are operator +acts, and the operator documentation owns them. + +- **The person alone.** Both routes are the subject's own (`OwnDataRequest`, + `OwnDataRequestEntry`); `DataRequestService.CreateClosureAsync` refuses an + administrator caller before it takes a fence, and the administrator surface has no + closure route, list row, read or cancellation (`DataRequestRules.Reaches` and + `Mutates` exclude the kind, and the reader's administrator page filters it out). +- **What a group's administrator learns.** They never read the closure, but they see + the group's erasure the closure's fan-out created (`origin` `closure_fanout`, with its + frozen Memberships) on their page and its receipt, and a filing of theirs for a member + whose account is closing answers `lockey_subject_not_admitted`. Both tell a + participant group that one of its members is closing their account, which is + intended: the group's own data of that member is being erased. +- **Creation.** The erasure's creation path with the kind `closure`: the subject's + exclusive User fence and the shared tenant fence, the authority recheck, the frozen + snapshot of the subject's Memberships of any status in the group, `audit.Designate` + and the one-active insert. `DataRequestEligibility` judges a closure only at its + creation: a Membership of any status in the group (`404 not_found` otherwise), no + other active closure of the subject in the group + (`lockey_request_already_active`) and the hold port (`lockey_blocked_hold`). It is + never refused for the last administrator: Begin judges that across every participant + tenant. Asked about a closure's execution, the port refuses to answer. +- **A closing person files nothing.** The request guard admits every person's and + administrator's request only for a subject whose User is Active, read under the User + fence the creation holds, so a filing of any kind that reaches its insertion after a + Begin committed, or an administrator's filing for a person whose account is closing, + stores nothing and answers `409` with `lockey_subject_not_admitted` in `errors.$`. +- **No job.** The request is `scheduled` with `executeAt` 24 hours after its creation. + `DataRequestFulfillmentScheduler` accepts a scheduled closure explicitly and submits + nothing; the receipt never reads a job phase for it and + `DataRequestFailureReconciler` never fails it, so a closure is never shown or stored + `failed`. +- **Cancellation.** The subject cancels a scheduled closure through the ordinary + cancellation routes until its Begin commits, also after `executeAt`, which is the + earliest Begin and not a cancellation deadline. Begin holds the fence of every tenant + where the person holds a Membership, the originating tenant included, so a + cancellation either commits first or finds the closure `fulfilling` and is refused + with `lockey_data_request_not_cancellable`. +- **Receipt.** The ordinary receipt: `status`, `executeAt`, and `lastRefusal` when a + Begin was refused (`blocked_window`, `blocked_hold`, `blocked_last_administrator`). + Once begun the account no longer admits a session, so no in-product status remains; + the receipt descriptions of the OpenAPI document say so. + +#### Export bundle sections + +What each participant writes into the bundle of +[ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) § 3, in +the order the bundle carries them; the envelope and the bounds are +`DataExportBundleBuilder`'s. + +**Identifier legend.** No identifier but the request's own leaves in a bundle. Where a +record names a person, it writes one closed word instead: + +| Word | Means | +|---|---| +| `self` | The subject of the request, or one of their own Memberships | +| `third_party` | Any other person, or another person's Membership, role or invitation | +| `system` | The platform's own actor (audit `actor` only): a job or a provider event, not a person | + +| Section | Collection | Contents | +|---|---|---| +| `audit` | `audit_scope` | One record, `{"reach": …, "complete": false}`, with the closed reach below | +| `audit` | `entries` | The subject's rows in that reach, newest first, capped at 8 MiB (`DataRequestLimits.AuditSectionBytes`) | +| `customization`, `education` | none | Empty: definitions and content are tenant data; both only report `attribution_reference` | +| `identity` | `memberships` | The snapshot Memberships: status, scope, role names, timestamps, display name, locale and every custom-field value with its revision, labels and classification, a value withheld by a withdrawn consent included | +| `identity` | `invitations_accepted` | Oldest first: the person's own recipient address and `issued_by` | +| `identity` | `invitations_issued` | Newest first: the invitee's address omitted, `accepted_by` as `self`, `third_party` or null; capped at 4 MiB (`DataRequestLimits.IssuedInvitationsCollectionBytes`) | +| `tenancy` | `field_consents` | The subject's consent acts for the snapshot Memberships of the group, `recorded_by` as a closed word | + +- **The audit reach is what the row policy shows.** The export job runs on its group's + ordinary transaction, which holds no tenant-wide read witness, so + `audit_log_isolation` bounds what it can read. `reach` is one of three closed words: + `organization_and_tenant_level` (a self-requested export in an organization group: + that organization's rows and the tenant-level rows), `organization_only` (an + administrator's request in an organization group, ADR-0108 § 4) and + `tenant_level_only` (any request in the tenant-wide group). A self-requested export + therefore does **not** reach the rows recorded in the person's other organizations, + which ADR-0107 § 3 and ADR-0108 § 4 call "the whole tenant". Those rows are in + another export only where the person can file one: an export needs a Membership, of + any status, in its group. Rows the person caused in an organization where they have + none (a tenant-wide administrator acting in a branch) reach **no** export of theirs. +- **`complete` says so.** It is `false` for every reach word, so the Step 4 screens can + tell the person the audit section is not their whole audit trail in the tenant; + `true` is reserved for a whole-tenant reach, which needs its own decision. +- **A cap truncates, whatever the ceiling.** The builder clamps every declared section + and collection cap to half of `DataExport:MaxBytes`, so at the 1 MiB minimum the audit + section and `invitations_issued` still truncate, stated in `truncated` and on the + artifact receipt; `export_too_large` remains for a bundle the uncapped sections fill. +- **Retained counts.** `attribution_reference` counts **rows**: a row of a tenant-owned + entity whose `UserId` columns name the subject counts once, whichever and however many + of those columns do, a non-`AuditableEntity` updater such as a feature flag's + included. A participant names the columns that are the row's subject or party instead + (a Membership's `UserId`, an invitation's inviter and acceptor, the federation and + provider-event actors) and the types reported under another kind (the request + receipts, and the consent table, whose `ck_membership_field_consents_actor` makes + every act its own subject's). `request_receipt` counts the group's requests, + artifacts and tickets in which **any** `UserId` column names the person, once per + row: the subject, the requester, and whoever created, cancelled or revoked them, so + an administrator who filed or cancelled a request about someone else is told the row + survives. `audit_metadata_reference` is exact up to a scan window per branch of the + reach (the group's organization, the tenant-level rows) and a lower bound past it; + the [Audit module](../audit/README.md#performance-budget) owns both audit statements' + bounds. +- **The retained list is partial.** The tenant side reports `request_receipt`, + `invitation_record` (the offers the person issued or accepted: a pending offer + addressed to their e-mail address is retained and not locatable by person, so it is + not counted), `attribution_reference`, `consent_evidence` and, in the + tenant-wide group, `federation_actor_reference` and `provider_event_record`; the + operator's completion replaces the three audit kinds the Audit participant counted + while the request waited (`audit_actor_reference`, `audit_entity_reference`, + `audit_metadata_reference`) with the redaction's exact counts, so a receipt's numbers + change at completion, and adds `unscoped_audit_rows` for an administrator's request. + A kind not listed is retained and not counted, which + is not zero: `invitation_envelope` (the application role holds no `SELECT` on the + envelope table), `transport_evidence`, `execution_evidence`, `idempotency_cache` and + `external_copy` have no subject-keyed count. The web surface's retention explanation + names those classes in its copy ([Phase 03](../../roadmap/phase-03-identity-admin.md) + P03-10 Step 4), `unserved_group` is a closure's kind (Step 3), and Phase 11 owns + every retention period and the counting of the stores it purges. + +#### Tenant erasure (P03-10 Step 2) + +The erasure of [ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) +§ 5 for one scope group; the routes are in the tables above, the +[audit matrix](audit.md#data-request-bindings) owns its rows and the +[data erasure runbook](../../runbooks/data-erasure.md) its operator step. + +- **Filing.** The person files it (live session or retained entry); an administrator + files it only for a person who holds no Active or Suspended Membership in the group + (`lockey_subject_membership_current`, and never for themselves, + `lockey_subject_is_requester`). The request is `scheduled` with `executeAt` 24 hours + later and its job queued for that time. Other refusals, each writing no request, are + `lockey_request_already_active`, `lockey_blocked_last_administrator` (the only + eligible tenant-wide administrator), `lockey_blocked_hold` and + `lockey_snapshot_too_large`. Cancelling until `executeAt` is the person's or the + filing administrator's; later it answers `lockey_data_request_window_ended`, and a + request that already ended `lockey_data_request_not_cancellable`. +- **The job.** `identity.data_erasure_{tenant,organization}.v1`, one root, one + transaction. It takes the person's User fence and the tenant key exclusively, + re-judges eligibility (`blocked`), runs each participant's `EraseAsync` in key order + (a resumed run skips those its progress records), records the retained report and + parks the request `awaiting_privileged_step`. +- **What the Identity participant erases** (`DataErasureService`, in this order): the + person's available export artifact and unstarted export request; the Memberships of + the request's frozen snapshot (role assignments removed, profile cleared, left as a + Revoked tombstone that keeps the person's identifier); the pending invitations the + person issued, in pages of 100. It touches no other person, group or tenant and not + the `users` row. +- **The witness.** `DataErasureWitness` is sealed and minted only by the service from a + `fulfilling` erasure; `Membership.RemoveAssignmentsForErasure`, + `ClearProfileForErasure`, `RevokeForErasure` and `Invitation.RevokeForErasure` run + only under it, and the database guard admits the profile clearing only while that + person's erasure for the group is `fulfilling` and names the Membership + ([Database Standards](../../standards/05-database.md)). +- **When the job dies.** Every write rolls back, so the request stays stored + `scheduled` and its receipt reads `failed`; a new filing stores the old one `failed`. + +#### Operator data-request steps (P03-10 Step 2) + +The operator's two acts of +[ADR-0107 § 8](../../decisions/0107-data-request-fulfillment-and-account-closure.md) and +[ADR-0108 § 8](../../decisions/0108-privileged-audit-redaction.md), run by the +[data erasure runbook](../../runbooks/data-erasure.md); the platform +[permission matrix](permissions.md) owns the two keys and the audit matrices the slugs. + +- **Port and owner.** `IDataRequestOperatorOperations` (SharedKernel) is implemented by + `DataRequestOperatorOperations` in this module's Infrastructure, the one class that + enters the platform scope for these two acts; a closure's acts have their own owner, + below. Each call is one entered scope on `learnstack_platform`; no route and no other + module touches the request tables. +- **`inspect`** (`platform.data_request.read`) lists four closed states, metadata only, + oldest due first and keyset-paged: `awaiting_privileged_step`, `overdue_scheduled`, + `stuck_fulfilling` and `expired_artifact`. Its audit is the scope's entry row. +- **`complete_erasure`** (`platform.data_request.write`) reads and locks one erasure + awaiting its privileged step, builds the redaction plan from the row, has the Audit + executor redact on the scope's transaction, moves the request to `completed` through + the request guard's platform arm and writes the MUST result row under the request's + tenant, all in one transaction. A closure's fan-out erasure is refused. +- **No tenant write.** The request guard admits the platform role this completion and a + closure's arrows of + [Account closure storage](../../standards/05-database.md#account-closure-storage), + and stamps each itself; every other request change belongs to the tenant side. + +#### Account closure Begin (P03-10 Step 3) + +The operator's Begin of +[ADR-0107 § 7](../../decisions/0107-data-request-fulfillment-and-account-closure.md), +run by the [account closure runbook](../../runbooks/account-closure.md). + +- **Port and owner.** `IAccountClosureOperatorOperations` (SharedKernel) is implemented + by `AccountClosureOperatorOperations` in this module's Infrastructure, one class in + one file per act, which enters the platform scope for a closure. It refuses before it + enters when no single `IClosureFanOut` is registered. +- **What could never finish is refused first.** The request is read with the person's + raw provider subject, which only `IIdentityProviderAccountRemoval.CanRemove` sees: a + port that could never delete the account refuses the Begin (`RefusedProvider`). Then + `PlatformIdentityFences` takes the person's User fence and reads the participant + groups under it, with the Memberships the person holds in each, in one grouped + statement over `ix_memberships_user_id`; a person in more than + `ClosureLimits.MaximumParticipantGroups` (256) groups, served or not, or with more + than `ClosureLimits.MaximumTenantMemberships` (256) Memberships of any status in one + participant tenant, takes no tenant fence and is refused (`RefusedTooLarge`). Every + later step is bounded by those two numbers, so both refusals change nothing and record + no code: the scope ends by disposal with its entry row. +- **One transaction.** `PlatformIdentityFences` then takes every participant tenant's + fence ascending, each transaction-scoped and bounded by a three-second `lock_timeout` + in a transaction it checks is READ COMMITTED + ([Database Standards](../../standards/05-database.md#the-closures-fences)); the + request is locked and read again with the User's status; then `blocked_window` (the + database clock), `blocked_hold` (`IDataRequestHoldSource`, asked for the closure + directly, not through eligibility) and `blocked_last_administrator` (each + participant tenant that allows ordinary work, read through Tenancy's lifecycle port) + are judged, and the refusal is recorded or the User moves Active to Closing and the + request to `fulfilling`. The result row names the platform sentinel. A User already + Closing for another closure is not moved again and is not judged for the last + administrator, which its first Begin judged. +- **Then the fan-out.** After the commit the served groups go to `IClosureFanOut`, + each in its own pipeline act; a group that does not report a start or an adoption + makes the answer incomplete, and the operator repeats Begin. A repeat on a + `fulfilling` closure fences, judges and writes nothing and fans out again. + +#### Closure fan-out (P03-10 Step 3) + +The per-group half of a closure's Begin +([ADR-0107 § 7](../../decisions/0107-data-request-fulfillment-and-account-closure.md)): +after Begin's transaction commits and releases the fences, the same operator call fans +the closure out to every participant group Begin judged served. The act is +`fan_out_closure` (`PlatformOperations.ClosureFanOut`, audit slug +`identity.data_request.fan_out_closure`, reason `closure_fan_out`, +`platform.data_request.write`, the pipeline executor); it has no route. + +- **One admitted act per group.** `ClosureFanOut`, this module's `IClosureFanOut`, asks + the gate for one admission of `fan_out_closure` per group from the operator's witness + and ticket, so the grant is evaluated per act, and runs + `FanOutClosureCommand(SubjectUserId, OrganizationId)` through the operator act + executor for the group's tenant and organization. Groups run one after another in a + fixed order (tenant, the tenant-wide group first, then each organization), at most + `ClosureLimits.MaximumParticipantGroups` (256), the bound Begin judges, so a longer + list is the caller's programming error, thrown before any group runs; a refused + admission, a refusal and an exception are each that group's `Failed`, and only the + operator's cancellation stops the loop. +- **The organization is announced** + ([ADR-0102](../../decisions/0102-production-tenant-onboarding.md) Amendment 2). The + fan-out is the one operator act whose context names an organization: the executor + refuses one for any other operation, the operator source opens no such frame for + another operation, and `OperatorActGuard` admits it only for this operation, by + reference, on a transaction that announced the same tenant and organization. Every + onboarding act still runs with none. +- **Under the fences.** `FanOutClosureCommandHandler` checks the group's lifecycle + (Tenancy's `IIdentityScopeLifecycleReader`), takes the person's exclusive User fence + and the group tenant's shared fence through the guard, checks the lifecycle again, + stores a dead job's request `failed` as every creation path does, and reads the + person's active erasure in the group. +- **What the group holds decides.** None, and a `completed` fan-out erasure of the + person: only the closure's Finalize completes one, in the transaction that closes the + person, so a Begin repeated across that commit finds the group done and adopts it with + nothing stored and nothing designated (`Adopted`), its row naming no one. None + otherwise, or only terminal ones: a fan-out erasure is + created `fulfilling`, with no window, the system actor's, its snapshot every + Membership of the person in the group of any status, and its erasure job is enqueued + on the same transaction (`Started`). A fan-out still `fulfilling`: adopted, and its + job enqueued again unless one is still queued, running or retrying (`Adopted`), which + is how a repeated Begin retries a dead job. Any erasure awaiting its privileged step: + adopted as it is (`Adopted`). The person's or an administrator's erasure still in its + window: cancelled by the system actor and replaced in the same transaction, the + cancellation saved first so the one-active index frees the slot (`Started`). Such an + erasure past its window: its own job runs it (`Waiting`); a repeated Begin adopts it + once it awaits its privileged step. +- **The database is the witness.** The request guard admits a request born `fulfilling` + only as a closure's fan-out erasure of a person whose User is Closing, read under the + User fence; a refused insertion rolls the group back, the replaced erasure's + cancellation included, and answers `lockey_subject_not_admitted`. A group whose tenant + or organization stopped allowing ordinary work after Begin judged it answers + `not_found`; both are the group's `Failed`. +- **The job.** The ordinary erasure job of the group's scope runs the fan-out from + `fulfilling`, so it never asks eligibility again and never blocks; it erases every + Membership of the snapshot, a Revoked tombstone's profile included, records the + retained report and parks the request `awaiting_privileged_step`. Only the closure's + [Finalize](#account-closure-finalize-p03-10-step-3) completes it; `complete_erasure` + refuses it. +- **Audit.** One MUST row per group in that tenant, about the request created, adopted + or waited for, with the operator in `metadata.operator` and the reason + `closure_fan_out`, never the ticket; a replaced erasure travels in its `changes`. + These rows are the closure's evidence in every affected tenant. + +#### Account closure Finalize (P03-10 Step 3) + +The operator's Finalize of +[ADR-0107 § 7](../../decisions/0107-data-request-fulfillment-and-account-closure.md) and +[ADR-0108 § 8](../../decisions/0108-privileged-audit-redaction.md), run by the +[account closure runbook](../../runbooks/account-closure.md#finalize): +`finalize_closure` (`PlatformOperations.ClosureFinalize`, audit slug +`platform.closure.finalize`, intent slug `platform.closure.finalize_attempt`, reason +`closure_finalize`, `platform.data_request.write`), routed at +`POST /api/platform/v1/data-requests/{requestId}/finalize-closure`. + +- **Owner.** The Finalize part of `AccountClosureOperatorOperations`, whose constructor + takes `IIdentityProviderAccountRemoval`; the class is the port's one holder. Its + answers are `ClosureFinalizeOutcome`: `Finalized`, `AlreadyFinalized`, `NotFound`, + `NotClosure`, `NotFinalizable` (never begun or cancelled), `GroupsPending` and the + provider's `ProviderRefused`, `ProviderUnavailable` and `ProviderUncertain`. +- **Ready.** Every required group's newest erasure of the person, of any origin, must + await its privileged step, or have completed at or after this closure's Begin (the + closure's own update stamp), and its frozen Memberships must include every Membership + the person holds in the group. Every served group is required, and so is an unserved + group whose newest erasure is the closure's own fan-out and still open: its job began + before the group stopped allowing ordinary work, and nothing completes a fan-out + erasure once the person is Closed. An erasure completed before the person was admitted + again and began closing never stands in for a fan-out that did not run. Any other + unserved group needs none. +- **Transaction 1.** `PlatformIdentityFences.AcquireUserAsync`: the person's User fence + alone and the participant groups read under it, because this transaction moves no + User and no request, so no participant tenant's identity writes wait for its + redaction; the closure locked; the account's status, raw provider subject and subject + key read; the readiness; then the redaction through the scope's `RedactAuditAsync`: + one `AuditRedactionPlan.ForClosureTenant` per participant tenant, served or not, with + every Membership the person holds there, then `ForClosureSentinel` by the subject key. + The intent row carries the summed `AuditRedactionAggregate` and commits with the + redaction. Groups past the bound (`participants_beyond_bound`) and a tenant whose + Memberships the plan refuses (`redaction_plan_refused`), which Begin refused while the + person was Active, are defects logged by their closed names (error 7122). +- **The provider.** `RemoveAsync` with the raw subject, before any other statement, so + nothing is held in the database while it runs. Removed or absent goes on; refused, + unavailable, uncertain or a throw stops the act with a result row naming the stop, + the closure `fulfilling` and the User Closing. The raw subject is never logged, + audited, metered or returned. +- **Transaction 2.** `PlatformIdentityFences.AcquireAsync`: the User fence and every + participant tenant's fence, as Begin; the closure, the account, the participant set + and the readiness judged again; then `users` Closing to Closed with + `provider_subject` NULL, every participant erasure awaiting its privileged step + locked and completed with its tenant's retained audit kinds (a fan-out one through the + closure arm, the person's or an administrator's own through Step 2's arm; one that + `complete_erasure` finished meanwhile is left as it completed), this closure and + every other open closure of the person completed with the summed retained kinds and + `unserved_group` (a never-begun one through the same arm, from `scheduled`), and the + result row with closed counts. +- **Repeat.** Every step is idempotent: a repeat after a stop or a crash redacts again, + which changes no row, writes its own intent row, finds a deleted account absent and + finishes; a repeat after the finish answers `AlreadyFinalized` and writes only its + entry row. A result row the audit store refuses after the provider step is the + retryable unavailable, not the audit refusal, because the account may already be + deleted. + ## Entity-relationship diagram ```mermaid @@ -959,7 +1531,7 @@ above. | `Permission_Definitions_DeclareScope` | Implemented for the finite foundation and live operation contracts | `IdentityFoundationConventionTests`, `OperationPermissionConventionTests` and actual command metadata; [catalogue](../../standards/21-architecture-tests-catalogue.md) owns live authorization controls | | `Mapped_Properties_Have_Explicit_Personal_Data_Classification` | Implemented for all current models, including contextual Identity | `DataProtectionConventionTests`; complete census and neutral-name omission controls | | `Identity_Seed_Uses_Finite_Adopted_Manifests` | Implemented; no-write/interrupted/conflict actual seed controls | `IdentityFoundationConventionTests` / `IdentitySeederTests`; [Phase 03 Status](../../roadmap/phase-03-identity-admin.md) owns qualification | -| `Identity_Membership_Invariants_Use_Fresh_Ordered_Locks` | Implemented actual app-role races, live Membership transitions and Organization lifecycle/default invariants | `IdentityMembershipTests`, `IdentityMutationLockTests`, `IdentityFoundationConventionTests`, `MembershipAdministrationRaceTests` and `TenancyAdministrationRaceTests`; broader closure/locators remain P03-10 | +| `Identity_Membership_Invariants_Use_Fresh_Ordered_Locks` | Implemented actual app-role races, live Membership transitions and Organization lifecycle/default invariants | `IdentityMembershipTests`, `IdentityMutationLockTests`, `IdentityFoundationConventionTests`, `MembershipAdministrationRaceTests` and `TenancyAdministrationRaceTests`; the closure's platform acquirer has its own leg, `IdentityPlatformFenceConventionTests`, and its races are `AccountClosureBeginTests` | | Per-sink PII canaries/child audit/MUST rollback | Implemented actual child snapshots/redacted diffs, MUST rollback and value-bearing diagnostic controls | `IdentitySeederTests`, `IdentityDiagnosticSinkTests`, `TenantExistingBindingAdmissionTests` and canonical [data-protection proof ownership](../../architecture/23-data-protection.md#identity-foundation-and-classification-ownership); classification alone does not establish sink safety | | `Global_Identity_Storage_Is_Subject_Confined` / `Global_Identity_Creation_Uses_The_Common_Audit_Owner` | Implemented global storage/creation, exact self-entry HTTP and deliberate native activation | `GlobalIdentitySchemaTests`, `IdentityAuditConventionTests`, `GlobalIdentityBootstrapTests`, `IdentitySelfEntryHttpTests` and native `session-store.test.ts`; [Phase 03 Status](../../roadmap/phase-03-identity-admin.md) owns qualification and reviews | diff --git a/docs/modules/identity/audit.md b/docs/modules/identity/audit.md index 5086243d7..9736a02a1 100644 --- a/docs/modules/identity/audit.md +++ b/docs/modules/identity/audit.md @@ -65,10 +65,15 @@ The [phase Status](../../roadmap/phase-03-identity-admin.md) owns delivery. |---|---|---|---| | Invitation | `identity.invitation.create` | **MUST** (`security-event`) | `CreateInvitationCommand`; offer, generation-1 verifier, encrypted envelope and identifier-only job share the ordinary business transaction and required audit. | | Invitation | `identity.invitation.reissue` | **MUST** (`security-event`) | `ReissueInvitationCommand`; new generation/token/envelope/job with current TTL; former verifier invalidates atomically, without raw secret replay. | -| Invitation | `identity.invitation.revoke` | **MUST** (`security-event`) | `RevokeInvitationCommand`; terminal withdrawal; later Prepare refuses obsolete work, while already-prepared email may still arrive with an invalid link. | +| Invitation | `identity.invitation.revoke` | **MUST** (`security-event`) | `RevokeInvitationCommand`; terminal withdrawal; later Prepare refuses obsolete work, while already-prepared email may still arrive with an invalid link. The erasure job's roots (`RunTenantDataErasureCommand` / `RunOrganizationDataErasureCommand`) share the slug for the pending offers the erased person issued, with that person as the Invitation's actor and the job as the row's; the first offer is the designated subject and the others travel in `changes`, which the 256 KiB payload cap elides above a few hundred offers (about 700 measured); the offers' own rows, `Revoked` with their revoker and time, are then the record of which were withdrawn. The erasure's roots write this row on every run, a recorded no-op, a blocked run and a run with nothing of this type to change included; such a row has no subject (`entity_id` NULL), and what happened is read from the run's `identity.data_request.fulfill_erasure` row. | | 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 erasure fulfilment | `identity.data_request.fulfill_erasure` | **MUST** (`security-event`) | `RunTenantDataErasureCommand` / `RunOrganizationDataErasureCommand` ([ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) § 5); one row about the erasure request, written on the job's transaction with `scheduled → fulfilling → awaiting_privileged_step` (or `blocked` with its refusal). An export request the erasure cancelled travels in its `changes`. A missing, cancelled or ended request writes the row as a recorded no-op with no subject. | +| Membership including Profile/Assignments | `identity.membership.erase` | **MUST** (`security-event`) | Same two roots, second intent: the Memberships of the request's frozen snapshot lose their role assignments and profile values and become the Revoked tombstone, by the system actor under the erasure witness. The first Membership changed is the designated subject; the others travel in `changes`. An earlier-revoked tombstone's own row is not stamped (the contextual guard admits no UPDATE of it), so its cleared profile and removed assignments are on this row only. The erasure's roots write this row on every run, a recorded no-op, a blocked run and a run with nothing of this type to change included; such a row has no subject (`entity_id` NULL), and what happened is read from the run's `identity.data_request.fulfill_erasure` 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. | @@ -85,6 +90,54 @@ 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`, `subject_not_admitted`, and for an administrator `subject_export_available`) writes the row with its refusal and stores nothing. | +| DataSubjectRequest | `identity.data_request.create_erasure` | **MUST** (`create`) | `CreateOwnDataErasureCommand` (the subject) and `CreateDataErasureForSubjectCommand` (an administrator, only for a Membership already Revoked) share this slug; one row about the new `scheduled` request with its frozen Membership snapshot and execution time, on the transaction that also schedules its erasure job for that time. A refused creation (`request_already_active`, `blocked_last_administrator`, `blocked_hold`, `subject_not_admitted`, and for an administrator `subject_membership_current`) writes the row with its refusal and stores nothing. | +| DataSubjectRequest | `identity.data_request.create_closure` | **MUST** (`create`) | `CreateOwnAccountClosureCommand`: the person alone files the closure of their account from the session's group, its originating group ([ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) § 7); no administrator operation names the slug. One row about the new `scheduled` closure with its frozen Membership snapshot and execution time, under the subject's User fence and the shared tenant fence; no job is submitted, because the closure is executed by the operator's Begin. A refused creation (`request_already_active`, `blocked_hold`, `subject_not_admitted`) writes the row with its refusal and stores nothing; it is never refused for the last administrator, which is the Begin's check. The Begin and Finalize acts write their own off-path rows under the platform sentinel tenant, not under this slug. | +| DataSubjectRequest | `identity.data_request.fan_out_closure` | **MUST** (`security-event`) | `FanOutClosureCommand`, a closure's per-group operator act ([ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) § 7, [ADR-0102](../../decisions/0102-production-tenant-onboarding.md) Amendment 2): one row in the participant tenant, under the group's own announcement, with the operator in `metadata.operator` and reason `closure_fan_out`, about the group's fan-out erasure it created (born `fulfilling`, the system actor's, its job enqueued on the same transaction) or the erasure it adopted or waits for. A person's or an administrator's erasure still in its window that the fan-out cancelled and replaced travels in that row's `changes`. A refused group (`not_found` for a group that no longer allows ordinary work, `subject_not_admitted`, `request_already_active`, `dependency_unavailable`) writes the row with its refusal and no subject. A group whose fan-out erasure its closure's Finalize already completed (a Begin repeated across that commit) is adopted with nothing designated, so its row names no request and no person. These per-tenant rows are the closure's "recorded against every affected tenant" evidence; Begin and Finalize write theirs under the platform sentinel tenant. | +| DataSubjectRequest | `identity.data_request.cancel` | **MUST** (`update`) | `CancelOwnDataRequestCommand` and `CancelDataRequestCommand`; `requested → cancelled` for an export, `scheduled → cancelled` for an erasure before its execution time and for the subject's closure until its Begin commits, 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. The erasure job's roots share the slug for the artifact the erasure withdraws (an expired one is recorded `purged`). The erasure's roots write this row on every run, a recorded no-op, a blocked run and a run with nothing of this type to change included; such a row has no subject (`entity_id` NULL), and what happened is read from the run's `identity.data_request.fulfill_erasure` 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. | + +### 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 creations, cancellation, +revocation, ticket mint and chunk read register the operations above +(`CreateRetainedDataExportCommand` → `identity.data_request.create_export`, +`CreateRetainedDataErasureCommand` → `identity.data_request.create_erasure`, +`CreateRetainedAccountClosureCommand` → `identity.data_request.create_closure`, +`CancelRetainedDataRequestCommand` → `identity.data_request.cancel`, +`RevokeRetainedDataExportCommand` → `identity.data_export.revoke`, +`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 92f1b82f0..3bfcf5d19 100644 --- a/docs/modules/identity/permissions.md +++ b/docs/modules/identity/permissions.md @@ -30,6 +30,11 @@ permission admission. An attribute, realm role or SystemActor value grants no ro | `OperatorCreateFirstAdminCommand` | Platform `platform.tenant_bootstrap.write`, `PlatformOperator` source | The first tenant-wide administrator of a tenant with no Membership history; the person is named by provider subject and must be an Active, bootstrapped User | | `OperatorRecoverAdminCommand` | Platform `platform.tenant_bootstrap.write`, `PlatformOperator` source | A replacement administrator while no Active tenant-wide administrator Membership exists; the last-administrator guard is the database's and is unchanged | | `IdentityIssuerRebind` (an offline tool, not a command or a route) | Platform `platform.identity_authority.admin`, `PlatformOperator` token | The operator's per-act grant for the rebind operation only, checked by the operator gate in the tool; the write itself runs on the confined `learnstack_identity_rebind` role, with no tenant context ([ADR-0104](../../decisions/0104-controlled-issuer-rebind.md)) | +| `DataRequestOperatorOperations.InspectAsync` (an operator route in the platform scope, not a command) | Platform `platform.data_request.read`, `PlatformOperator` token | The operator's per-act grant for `platform.data_request.inspect`, checked by the operator gate before the scope is entered; a closed-column read of the request and artifact tables across tenants that names no person ([ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) § 8) | +| `DataRequestOperatorOperations.CompleteErasureAsync` (an operator route in the platform scope, not a command) | Platform `platform.data_request.write`, `PlatformOperator` token | The per-act grant for `audit.redaction.apply`; one erasure awaiting its privileged step, whose subject, group and Memberships are read from its own row; the audit redaction, the completion through the request guard's platform arm and the result row in one platform transaction ([ADR-0108](../../decisions/0108-privileged-audit-redaction.md)) | +| `AccountClosureOperatorOperations.BeginAsync` (an operator route in the platform scope, not a command) | Platform `platform.data_request.write`, `PlatformOperator` token | The per-act grant for `platform.closure.begin`; one closure, whose person and group are read from its own row; the person's fences, the judgment, the User's move to Closing and the request's to `fulfilling` and the result row in one platform transaction, then the fan-out, whose per-group acts the gate admits for the same operator and key ([ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) § 7) | +| `AccountClosureOperatorOperations.FinalizeAsync` (an operator route in the platform scope, not a command) | Platform `platform.data_request.write`, `PlatformOperator` token | The per-act grant for `platform.closure.finalize`; one begun closure, whose person and group are read from its own row; under the person's fences, the readiness of every served group, the audit redaction of every participant tenant and the sentinel tenant and the intent row in one platform transaction, then the identity provider's deletion of the account, then the User's move to Closed, the completion of every participant erasure and open closure of the person and the result row in a second ([ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) § 7, [ADR-0108](../../decisions/0108-privileged-audit-redaction.md) § 8) | +| `FanOutClosureCommand` (a closure's per-group act, run by `ClosureFanOut` after Begin commits, never routed) | Platform `platform.data_request.write`, `PlatformOperator` source | The per-act grant for `identity.data_request.fan_out_closure`, asked of the gate once per participant group; the one operator act whose context names the group's organization ([ADR-0102](../../decisions/0102-production-tenant-onboarding.md) Amendment 2); creates or adopts the closing person's erasure of that group on the application role under the person's User fence ([ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) § 7) | Scope selection derives from immutable target Membership/validated declaration, never a claimed scope string. Finite metadata alternatives count the exact five @@ -45,6 +50,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; the operator's inspection and erasure completion take the non-assignable Platform keys above | 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 +182,61 @@ 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, § 5, § 7.** 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 | +| `CreateOwnDataErasureCommand` | `OwnDataRequest` | As the export, one active erasure per subject and group; `scheduled`, its job due when the 24-hour window ends; refused while the subject is the tenant's only eligible tenant-wide administrator (tenant-wide group) or a hold applies | +| `CreateOwnAccountClosureCommand` | `OwnDataRequest` | The person alone files the global account closure from the session's group, its originating group; one active closure per subject and group; `scheduled` with its execution time 24 hours later and no job; refused while a hold applies, never for the last administrator (its Begin judges that). No administrator operation files, lists, reads or cancels a closure, and no Platform permission is involved | +| `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`: an export while requested, an erasure before its execution time, a closure until its Begin commits | +| `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 | +| `CreateDataErasureForSubjectCommand` | Same | Only for a person whose named Membership in the group is Revoked and who holds no Active or Suspended one there (`subject_membership_current` otherwise): its own target authorization, since membership administration refuses a Revoked target; never for oneself | +| `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).** Nine further key-less operations use the `OwnDataRequestEntry` kind, plus the +receipt read of its five 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` | +| `CreateRetainedDataErasureCommand` | `OwnDataRequestEntry` (Create) | As `CreateOwnDataErasureCommand`, in the selected group; the path of a Suspended person and of one whose Membership is Revoked; keyed, 202 without `Location` | +| `CreateRetainedAccountClosureCommand` | `OwnDataRequestEntry` (Create) | As `CreateOwnAccountClosureCommand`, from the selected group as the originating group; the path of a Suspended person and of one whose Membership is Revoked; keyed, 202 without `Location` | +| `CancelRetainedDataRequestCommand` | `OwnDataRequestEntry` (Cancel) | As `CancelOwnDataRequestCommand`, in the selected group, with `If-Match`; keyed | +| `RevokeRetainedDataExportCommand` | `OwnDataRequestEntry` (Revoke) | As `RevokeOwnDataExportCommand`, in the selected group, with the artifact version in `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/modules/identity/providers.md b/docs/modules/identity/providers.md index c761da53c..017111fbd 100644 --- a/docs/modules/identity/providers.md +++ b/docs/modules/identity/providers.md @@ -1,8 +1,9 @@ # Identity — Provider Adapters **Derives from:** [ADR-0093](../../decisions/0093-verified-invitation-acceptance-and-handoff.md), -[ADR-0097](../../decisions/0097-retained-provider-events-and-tenant-audit-mirror.md) -and [ADR-0099](../../decisions/0099-confined-tenant-federation.md). +[ADR-0097](../../decisions/0097-retained-provider-events-and-tenant-audit-mirror.md), +[ADR-0099](../../decisions/0099-confined-tenant-federation.md) and +[ADR-0107 § 7](../../decisions/0107-data-request-fulfillment-and-account-closure.md). These are the bounded invitation, retained-event and tenant-federation provider contracts; the [Phase 03 Status block](../../roadmap/phase-03-identity-admin.md) owns implementation and qualification. Acceptance is not evidence of a configured production @@ -219,6 +220,31 @@ An entry admits the host for every tenant. It is composition configuration read at startup; tenant input never extends it. Keycloak's own later fetches follow DNS; only deployment egress policy bounds them (Phase 11). +## Account removal adapter + +[ADR-0107 § 7](../../decisions/0107-data-request-fulfillment-and-account-closure.md) +decides this boundary: the last effect of a global account closure deletes the person's +identity-provider account. The [runbook](../../runbooks/account-removal-client.md) owns +provisioning, rotation and leak response. + +| Boundary | Contract | +|---|---| +| Port | SharedKernel `IIdentityProviderAccountRemoval`, one deleting method (`RemoveAsync`) and the pure preflight `CanRemove`; the sole caller of the deletion is the closure's Finalize, pinned by an architecture rule. Outcomes: removed, absent (success), refused, unavailable, uncertain | +| Default | SharedKernel `RefusingIdentityProviderAccountRemoval`, registered by the Identity foundation: every call is refused and nothing is sent | +| Adapter | Internal sealed `KeycloakAccountRemoval` in `LearnStack.Infrastructure.Identity.AccountRemoval`; direct HTTP, no SDK | +| Selection | API `AccountRemovalComposition` replaces the default only when `AccountRemoval:ClientSecret` is configured; `AccountRemovalAdapterFactory` is the only entry. Issuer from `Authentication:Tenant:Issuer`, which must end `/realms/learnstack`; HTTPS, or loopback HTTP in Development only | +| Credentials | Client `learnstack-account-removal`, role `realm-management/manage-users` only; secret through `ISecretProvider` key `AccountRemoval:ClientSecret`, refused when empty, blank, over 1,024 bytes, the mask literal or a `${` reference; a fresh client-credentials token per call | +| Token check | Issuer, `azp`, no realm role and exactly one `realm-management` role, `manage-users`; anything else is refused before the deletion is sent | +| Calls | The token request, then one `DELETE users/{id}`; the identifier must be a canonical lowercase UUID (the provider's own user identifier, the OIDC `sub`), is escaped as one path segment, and any other spelling is refused before any request. No redirect is followed and no response body of the deletion is read | +| Answers | `204` removed; `404` with the provider's own JSON type absent; `401`, `403`, a redirect, any other `4xx`, a `404` in another type (a hop in front of the provider answering for it), a token refusal or a token wider than the role refused; `5xx`, `429`, `408`, `425`, any transport fault on the token call, a name, TLS or proxy-tunnel fault on the deletion, and an open breaker or full bulkhead unavailable (no deletion was confirmed; a repeat finds a landed deletion absent); a timeout, a connection error or loss on the deletion, or an unexpected success answer after the deletion was handed to the transport uncertain | +| Resilience | `IProviderResilience`, configuration `Resilience:accountRemoval`: no retry (the closure's Finalize is the repeatable retry and a quiet repeat would hide a lost answer), a 5 s pipeline timeout that bounds the whole call (the adapter's own cancellation sits one second later, so the breaker records the timeout), circuit breaker on within the federation ranges, and a bulkhead of exactly 1 with no queue; fixed values that composition refuses to change | +| Confidentiality | The subject and the secret are never logged, audited, placed in an exception message or returned; the closed fault type carries no provider text. A refusal logs one closed reason code at Warning (event 7125), listed in the [runbook](../../runbooks/account-removal-client.md#reading-a-refusal-in-the-log) | + +The role is realm-wide and can also create and update users and reset credentials; the +single deleting method, the single caller and the architecture rules in +[Standard 20](../../standards/20-infrastructure-stack.md#confined-account-removal-adapter) +confine what LearnStack sends, not what a leaked secret could do. + ## Invitation SMTP | Boundary | Contract | @@ -310,8 +336,22 @@ SMTP settings are `InvitationEmail:Smtp:Host`, `Port`, `Sender`, and `Tls` composition. Missing configuration prevents startup. No connection is made by configuration validation. -The paired local API launcher selects only these seven email configuration -keys from matching private-file/process sources. Values are compact single-line +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`, whose refusal names the setting (environment +spelling `DataExport__KeyRing`) and never its value. Rotation is a two-phase rollout +across hosts and removes the old key only once every artifact sealed under it has +expired (seven days); a ticket is refused with `data_export_unavailable` while the ring +lacks an artifact's key. The [data export runbook](../../runbooks/data-export.md) owns +rotation, key loss, stuck requests, unpurged artifacts and dump handling. 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 the seven email configuration keys above and +the two data export keys, and no other provider setting, 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 Development plaintext. The API owns key-ring, address, TLS and credential tuple validation. API file selection uses one no-follow handle and requires a regular, diff --git a/docs/modules/tenancy/audit.md b/docs/modules/tenancy/audit.md index 8df020b50..148242ada 100644 --- a/docs/modules/tenancy/audit.md +++ b/docs/modules/tenancy/audit.md @@ -147,6 +147,10 @@ unmarked row is one a shipped command already raises. | `outbox_messages` | `platform.outbox.dead_letter` `(off-path)` | **MUST** (`security-event`) | P02b-2 Step 2's consequential BYPASSRLS terminal transition; state and row commit together through the row-bound fifth audit seam, with stored tenant/org/event identity and SystemActor ([ADR-0046](../../decisions/0046-durable-event-delivery-and-recovery.md)) | | delivery ledger | `platform.delivery.dead_letter` `(off-path)` | **MUST** (`security-event`) | P02b-3 Step 4's subscriber terminal writer binds stored tenant/org/event/subscription, acquisition token, reason and attempts to the actual fenced transition; ledger and MUST audit commit together through the same restricted fifth seam. It receives no causal-envelope or payload SELECT grant | | outbox, delivery ledger and `background_jobs` | `platform.delivery.inspect` `(off-path)` | **MUST** (`security-event`) | An operator's metadata-only inspection of dead-lettered and pending-terminal rows and quarantined jobs ([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)). Written as the platform scope's entry row, whose operation is `platform.admin_scope.enter` and whose closed reason `delivery_inspect` is this slug's, with the operator attribution and ticket in `metadata.operator`; the row does not say which list was read; the scope writes no result row because it reads and changes nothing, and each page of an inspection is one entered scope | +| `data_subject_requests`, `data_export_artifacts` | `platform.data_request.inspect` `(off-path)` | **MUST** (`security-event`) | An operator's metadata-only inspection of the data requests that await an operator step, overdue scheduled requests, stuck fulfilling requests and expired export artifacts not yet purged ([ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) § 8). Written as the platform scope's entry row, whose operation is `platform.admin_scope.enter` and whose closed reason `data_request_inspect` is this slug's, with the operator attribution and ticket in `metadata.operator`; the scope reads and changes nothing, so it writes no result row, and each page of an inspection is one entered scope. Declared here with the other platform operations; the module column of the row it writes is `platform` | +| `users`, `data_subject_requests` | `platform.closure.begin` `(off-path)` | **MUST** (`security-event`) | The result row of an operator's Begin of a person's global account closure ([ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) § 7), on the platform transaction that moves the User from Active to Closing and the closure request to `fulfilling`, or that records the refusal standing on the request. Under the platform sentinel tenant, so the operator's ticket rides in `metadata.operator`; no actor, the closed reason `closure_begin`, closed states and never a person identifier. Each participant tenant's own evidence is its fan-out erasure's MUST rows. A Begin refused for the closure's size or for an account the provider's port could never delete records no code and writes no result row: its scope's entry row is its record. The module column is `platform`, because the operator writes refuse `identity` (ADR-0107 § 8) | +| `audit_log` | `platform.closure.finalize_attempt` `(off-path)` | **MUST** (`security-event`) | The intent row of an operator's Finalize of a global account closure, written at the platform scope handle's checkpoint on the transaction that redacted the person's audit rows in every participant tenant and the platform sentinel tenant, so the redaction commits with it or not at all, before the identity provider's account is removed ([ADR-0108](../../decisions/0108-privileged-audit-redaction.md) § 8). Outcome `indeterminate`, under the platform sentinel tenant with the ticket, no actor, the closed reason `closure_finalize`, and `after_state` holding the redaction's closed report: the tenant count, the rows selected in each participant tenant up to 200 tenants, and per column and per retained kind the sentinel pass's counts and the total's, never a person identifier | +| `users`, `data_subject_requests` | `platform.closure.finalize` `(off-path)` | **MUST** (`security-event`) | The result row of that Finalize, written through the witness-bound result method on the transaction after the checkpoint, which sets the User Closed and completes the participant requests and the person's non-terminal closure requests ([ADR-0107](../../decisions/0107-data-request-fulfillment-and-account-closure.md) § 7), with the audit outcome `success`, under the platform sentinel tenant with the ticket, and closed states only: `before_state` `{"status":"fulfilling","account":"closing"}` and `after_state` with the closed `outcome` `finalized`, `"account":"closed"`, the provider's `removed` or `absent`, the group counts and the closure's recorded retained kinds. An attempt that stops after its checkpoint writes the same row on the same slug with the closed `outcome` that stopped it (`provider_refused`, `provider_unavailable`, `provider_uncertain`, `groups_pending` found again under the second transaction's fences, or `already_finalized` by another call) and changes nothing else. A crash between the two, or a result row the audit store refuses after the provider step (answered as the retryable unavailable, because the account may already be deleted), leaves the intent row alone, and the act, being idempotent, is run again, each attempt with its own intent row | | delivery ledger | `platform.delivery.replay` `(off-path)` | **MUST** (`security-event`) | An operator's fenced reset of one dead-lettered subscriber delivery. Written through the row-bound operator-recovery seam on the outbox-role transaction that makes the change, under the real event tenant, with no actor, the closed reason `delivery_replay`, `metadata.operator`, and `metadata.fence` holding the fence before and after; a forced audit failure rolls the reset back and the request answers `503` with no state change. A stale fence or a refused state writes no row ([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)) | | `outbox_messages` | `platform.delivery.reset` `(off-path)` | **MUST** (`security-event`) | An operator's fenced reset of one dead-lettered producer row whose terminal reason is retry exhaustion, written by the same seam in the same shape under the closed reason `delivery_reset`; the reset renews the six-attempt budget ([ADR-0103](../../decisions/0103-operator-recovery-of-asynchronous-work.md)) | | `federation_connections` and the realm's identity-provider instances | `platform.federation.report` `(off-path)` | **MUST** (`security-event`) | An operator's report of the brokers that are orphaned, unreadable or nonconforming ([ADR-0099](../../decisions/0099-confined-tenant-federation.md) Amendment 10). Written as the platform scope's entry row, whose operation is `platform.admin_scope.enter` and whose closed reason `federation_report` is this slug's, with the operator attribution and ticket in `metadata.operator`; the scope reads and changes nothing, so it writes no result row, and it does not say which page was read | diff --git a/docs/modules/tenancy/permissions.md b/docs/modules/tenancy/permissions.md index 7ea734c81..30cb4fdf2 100644 --- a/docs/modules/tenancy/permissions.md +++ b/docs/modules/tenancy/permissions.md @@ -134,8 +134,16 @@ remove and disable of one [runbook](../../runbooks/federation-operator.md)): they run in the platform scope, not through the pipeline, and write the off-path slugs `platform.federation.report`, `platform.federation.remove_attempt`, `platform.federation.remove`, -`platform.federation.disable_attempt` and `platform.federation.disable`. Operators hold -the keys by configuration ([Standard 19](../../standards/19-permissions.md)). +`platform.federation.disable_attempt` and `platform.federation.disable`. Two more keys, +`platform.data_request.read` and `platform.data_request.write`, belong to the Identity +module's operator data-request acts ([permissions](../identity/permissions.md), +[runbook](../../runbooks/data-erasure.md)); Tenancy's catalogue source declares their +off-path slugs, `platform.data_request.inspect`, `audit.redaction.apply` and a global +account closure's `platform.closure.begin`, `platform.closure.finalize_attempt` and +`platform.closure.finalize`, beside the other platform slugs, and every one of them but +`audit.redaction.apply` has its row in [Tenancy's audit matrix](audit.md). +Operators hold the keys by configuration +([Standard 19](../../standards/19-permissions.md)). ## Bounded human administration contract diff --git a/docs/roadmap/phase-02a-kernel-tenancy.md b/docs/roadmap/phase-02a-kernel-tenancy.md index e70b92710..a8b8230b5 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 fb909a07f..c98944e1f 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,315 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 @@ -532,6 +532,24 @@ not acceptance of implementation choices. Navigate by the generated index below. - [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 - [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) — 925 lines + - [P03-10 decision package and acceptance (2026-11-22)](#p03-10-decision-package-and-acceptance-2026-11-22) — 71 lines + - [P03-10 Step 1 — request core and export (2026-11-22)](#p03-10-step-1--request-core-and-export-2026-11-22) — 63 lines + - [P03-10 Step 1 — review round 1 and its fixes (2026-11-22)](#p03-10-step-1--review-round-1-and-its-fixes-2026-11-22) — 24 lines + - [P03-10 Step 1 — review round 2 and its fixes (2026-11-22)](#p03-10-step-1--review-round-2-and-its-fixes-2026-11-22) — 32 lines + - [P03-10 Step 1 — verification and closeout (2026-11-22)](#p03-10-step-1--verification-and-closeout-2026-11-22) — 69 lines + - [P03-10 Step 2 — tenant erasure and privileged audit redaction (2026-11-23)](#p03-10-step-2--tenant-erasure-and-privileged-audit-redaction-2026-11-23) — 53 lines + - [P03-10 Step 2 — review round 1 and its fixes (2026-11-23)](#p03-10-step-2--review-round-1-and-its-fixes-2026-11-23) — 15 lines + - [P03-10 Step 2 — review round 2 and its fixes (2026-11-23)](#p03-10-step-2--review-round-2-and-its-fixes-2026-11-23) — 23 lines + - [P03-10 Step 2 — verification and closeout (2026-11-23)](#p03-10-step-2--verification-and-closeout-2026-11-23) — 66 lines + - [P03-10 Step 3 — global account closure (2026-11-23)](#p03-10-step-3--global-account-closure-2026-11-23) — 52 lines + - [P03-10 Step 4 — the web surface (2026-11-23)](#p03-10-step-4--the-web-surface-2026-11-23) — 14 lines + - [P03-10 Steps 3 and 4 — review round 1 and its fixes (2026-11-23)](#p03-10-steps-3-and-4--review-round-1-and-its-fixes-2026-11-23) — 50 lines + - [P03-10 Steps 3 and 4 — review round 2 and the usage limit (2026-11-23)](#p03-10-steps-3-and-4--review-round-2-and-the-usage-limit-2026-11-23) — 22 lines + - [P03-10 — owed ADR amendments and maintainer decisions (2026-11-23)](#p03-10--owed-adr-amendments-and-maintainer-decisions-2026-11-23) — 324 lines + - [P03-10 Steps 3 and 4 — verification and closeout (2026-11-23)](#p03-10-steps-3-and-4--verification-and-closeout-2026-11-23) — 45 lines @@ -25504,3 +25522,1045 @@ largest at 33,367 bytes, 43 % and 51 % of the new bound, and the two layouts rem distinct. The 88 shard tests and 42 result tests pass. What local runs cannot show is how the hosted test chain handles a filter above 32 KiB: that is the qualification this record leaves open until a complete layout A and a complete layout B pass on the same source. + +### 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. + +### 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. + +## 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. + +### P03-10 Step 1 — request core and export (2026-11-22) + +Step 1 delivers the request core and the export of +[ADR-0106](../decisions/0106-subject-data-requests-authority-and-status.md) and +[ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md): a person +files an export of their own data in one scope group, a job builds it, and the person +downloads it in encrypted chunks under a short-lived ticket. Five units landed in five +commits (`492f7f9e`, `2929f22f`, `889245c4`, `4fb4fc59`, `33ab8f62`); erasure, closure +and the web surface are Steps 2 to 4. + +Delivered: + +- **Storage.** `data_subject_requests`, `data_export_artifacts`, `data_export_tickets` + and `data_export_chunks` in the Identity chain + (`20261122013001_add_data_subject_requests`), each with the canonical row policy, + guards for the status machine, one active request per group by a partial unique index, + and column-limited grants; no role may DELETE a request, and a chunk goes only once + its artifact is no longer `available`. A Platform migration + (`20261122160000_add_data_request_protected_receipts`) lets a keyed data-request + mutation retain its receipt and indexes the job-phase read; an Audit migration + (`20261122074947_index_audit_log_data_request_selection`) serves the export's audit + selection. +- **Domain and ports.** `DataSubjectRequest`, `DataExportArtifact` and + `DataExportTicket` with their closed status vocabularies; the SharedKernel ports + `IUserDataParticipant`, `IDataExportArtifactStore`, the eligibility and hold ports and + `DataRequestLimits`, the one home of the fixed bounds. +- **Retained own scope.** `fn_identity_own_data_request_scopes` (SECURITY DEFINER) with + owner arms, `TenantContextOrigin.HostAndOwnDataRequestScope`, + `OwnDataRequestScopeWitness` and the policy kinds `OwnDataRequest` and + `OwnDataRequestEntry`, so a Suspended person or one whose Membership was revoked can + still reach their own requests on the real host. +- **Export engine.** AES-256-GCM chunks of 128 KiB under a versioned key ring + (`DataExport:KeyRing`, ceiling `DataExport:MaxBytes`, 16 MiB by default and 64 MiB at + most) in encrypted PostgreSQL custody behind `IDataExportArtifactStore`; five + participants (Identity, Tenancy, Customization, Education, Audit) that describe and + export their section; the export and purge jobs, the fulfilment scheduler and a + reconciler that stores `failed` for a request whose job died. +- **API.** Seven own operations under `/api/v1/identity/me/data-requests` (create, list, + read, cancel, revoke, ticket, chunk), five administrator operations under + `/api/v1/identity/data-requests` (create for a Membership, list, read, cancel, revoke; + a keyed replay reads the original receipt) and six retained-entry operations under + `/api/v1/identity/data-request-entry` (`scopes`, `requests`, `exports`, + `cancellations`, `tickets`, `chunks`). Administrator operations are `Protected` on + `identity.membership.admin`; no assignable key was added, so G20 is untouched. The + OpenAPI and SDK changes are additive. +- **Audit.** `identity.data_request.create_export`, `cancel`, `list`, `read`, + `read_receipt` and `fulfill_export`, and `identity.data_export.revoke`, `mint_ticket` + and `read_chunk`, all MUST; the ticket and chunk reads are read-sensitive and refuse + when the row cannot be written. + +Decisions taken in the code that the ADR text does not state (they are owed as +amendments and listed under the closeout): + +- An export reads `requested` until it completes: the job runs `requested`, `fulfilling` + and `completed` in one transaction, so `fulfilling` is not observable for an export. +- A dead job is stored `failed` with `execution_failed` by the reconciler when the + create path observes it, because the one-active index frees a slot only for a stored + terminal status; a receipt shows `failed` before that. +- The request's `result` column holds the closed retained-kind vocabulary, so the cap a + truncation hit is stated in a closed `truncation` column on the artifact. +- A request needs at least one Membership snapshot, and Memberships are never deleted, + so a person with no Membership of the group cannot file. + +### P03-10 Step 1 — review round 1 and its fixes (2026-11-22) + +Fresh read-only reviewers read the five commits by lens and every finding was checked +against the code before it was fixed. The ones that changed code: + +- **Storage and guards.** An artifact insert is allowed only while its request is + `fulfilling`, and a deferred check requires the exact chunk count at commit; the chunk + and ticket guards read the artifact `FOR SHARE`; the group's request page and the + job-phase read gained indexes. +- **Custody and download.** The cipher's dispose and seal race is closed under one gate; + a mint is refused when the artifact's key left the ring; open tickets are bounded; a + custody refusal answers `not_found` and logs once at Critical; plaintext segments are + pooled and cleared, and the ticket and chunk request bodies are read zeroed. +- **Audit and bundle.** The audit section opens with its reach, its statements are + unions of index-served branches under a 15-second budget, the metadata scan is + windowed, colliding payload keys are suffixed and the per-collection caps clamp to + half the ceiling; `invitations_issued` is capped at 4 MiB, newest first. +- **Observability and pins.** The `learnstack.data_export` meter and ids-only log events + 7501 to 7506; the handler, read-only and job-manifest census pins were brought to the + new counts after the full architecture suite, run in a clean clone, found what the + agents' filters had matched zero tests for. + +The fixes are `ae5b7323`, `810d1a46`, `6ff6969a`, `efbdc274` and `a6c731db`. + +### P03-10 Step 1 — review round 2 and its fixes (2026-11-22) + +Five fresh reviewers (a red team, a regression check of round 1, data protection, +failure injection and maintainability) read the head of round 1. None found a blocker. +The maintainer-side triage accepted the verified findings in three groups, each fixed in +an isolated clone, merged and re-verified in the working tree: + +- **The job and the tickets (`a0e560fc`).** The export job read the shared tenant fence + first and held it through the bundle build, so an exclusive-fence operation could fail + while a large export built; the job now builds the bundle and counts the references + with no fence, then takes the fence, re-reads the request and writes. A completed + export must own an artifact (a deferred trigger), an administrator's export is refused + while the person holds a readable artifact, tickets are bounded per session and per + artifact with distinct refusals, a host cancellation is no longer counted as a + failure, a participant's database fault is an infrastructure fault, and a clock + earlier than the row is floored. Custody refusals, purge failures and downloads are + counted. The runbook was rewritten against the code, and the OpenAPI prose is built + from the limit constants. +- **The audit section and the counts (`5ce0fe49`).** The audit metadata statement is + split into one statement per branch, each with its own partial index; on 2.3 million + rows an organization group's statement fell from 2.2 to 3.4 seconds to about a + millisecond. The audit section says its reach as a closed record, receipts are counted + by any user column, the stored result columns are classified as audit data, and the + describe-only participants share one guard. +- **Maintainability (`1b0e688b`).** One static class holds the request rules, the + creation and chunk read are split at their seams, the statement budget and the + active-status filter have one spelling and the integration helpers one home. No + behaviour, contract or schema changed. + +Two pins followed the fixes: the Platform reversal leaves the four request tables in +place (`0394de97`) and Identity installs one more function, the completed-export check. + +### P03-10 Step 1 — verification and closeout (2026-11-22) + +Step 1 is delivered and twice reviewed. The head of round 1 (`a6c731db`) ran the full +integration suite: 5,003 passed and 28 failed, and none of the 28 is a defect of the +packet. Twenty-six need the frontend dependencies that the clean clone of that run +lacked (the native BFF, public rendering and local launch fixtures); one fails only in a +Release build, because FluentAssertions cannot name the subject without the source path, +and it passes in Debug (`AuthenticatedHttpSurfaceRuntimeTests`, a federation census); +and one was a real pin, the Platform reversal's surviving-table list, fixed in +`0394de97`. + +After round 2: the full unit suite passes (4,810), the full architecture suite passes on +`a0e560fc` (688 tests, 1 hour 20 minutes in a clean clone), the SDK typecheck and tests +pass (234), the contract suite passes (15) and the OpenAPI document differs from the +decision-package base only by additions. The targeted integration run found one more +pin, the Identity function count that the completed-export check raised from 31 to 32, +fixed in `a0e560fc`. The refactor `1b0e688b` was checked by the unit suite, 341 +integration tests over the request, export, retained-scope and migration classes, the 46 +architecture tests that pin the moved code and an empty OpenAPI diff. + +A full integration run on the final head of Step 1 was not repeated: it needs about two +hours of the workstation, and the head of Step 2 contains all of Step 1's code, so the +full run there closes both. A failure in the request or export classes at that run +reopens this record. + +Open for the maintainer, as the amendments the code needs and the choices the ADRs left: + +- **The audit reach of an export is not tenant-wide.** ADR-0107 § 3 and ADR-0108 § 4 say + a self-requested export selects audit rows across the whole tenant. The export job has + no tenant-wide read witness, so RLS shows an organization group its own organization's + rows plus tenant-level rows, and a tenant-wide group only tenant-level rows; a + tenant-wide Membership holder who acted inside an organization has rows no export + reaches. The bundle says so in `audit_scope` (`complete: false`). Either amend the + sections to the visible reach, or decide a sanctioned tenant-wide read for the job, + which needs its own decision because it touches the trusted job policy and the + operation read witness. +- **A ticket reads any chunk index until the final one.** ADR-0107 § 4 says sequential + reads; no position column exists because § 8 grants only `consumed_at`. The amendment + states the semantics and the bounds this step added: three open tickets per session + and artifact, twenty ever minted per artifact. +- **An administrator's export is refused while the person holds a readable artifact**, + because completing it revokes that artifact. A rule the ADRs do not state. +- **Application grants are wider than the § 8 text** (`last_refusal`, `failure_reason`, + `completed_at`, `updated_at`, `updated_by` on requests; `purged_at`, `row_version`, + `updated_at`, `updated_by` on artifacts), and the platform grants the ADRs name + (`last_refusal`, a column-limited read of artifacts for `inspect`) belong to Steps 2 + and 3. +- **A retained person cannot revoke an artifact**, because the retained-entry set has no + revoke purpose; ADR-0107 § 4 says the subject may revoke. Decide at Step 2 or 4. +- **The retained recheck is identity-only.** Step 3 must re-validate the binding and the + User status under the User fence on both paths. +- **No automated sweeper retires expired artifacts.** The purge job runs once per + artifact (six attempts over about an hour); `inspect` in Step 2 lists expired + artifacts not yet purged, and the sweeper is Phase 11's retention purge. +- **Four unreleased migrations were edited in place** during review (the Identity + request and retained-scope migrations, the Platform receipts migration and the Audit + index migration): a development database created from an intermediate commit must be + dropped and migrated again. +- **Pre-existing, not this packet:** `pg_current_xact_id()::text::xid` fails with 22003 + once a cluster passes its first transaction-id epoch (verified on PostgreSQL 18.4). + Step 1 removed its own use; four older sites remain (`TenancyAdministrationDdl`, + `TenancyRetainedDefaultDdl`, `ContextualIdentityStorageDdl` twice) and need a + follow-up migration owned by the next Identity or Tenancy packet. +- **Recommendations, not changes:** derive the HTTP-surface census from attributes, + consolidate the three credential and input copies (it needs re-pinning the IL checks), + and keep port leakage (`CanOpen`, the locking read in the reader) in view in Steps 2 + to 4. + + +### P03-10 Step 2 — tenant erasure and privileged audit redaction (2026-11-23) + +Step 2 delivers the erasure half of +[ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) §§ 5, 6 +and 8 and of [ADR-0108](../decisions/0108-privileged-audit-redaction.md): a person, or +an administrator for a Revoked Membership, files an erasure of one scope group; after +its 24-hour cancellable window a job erases the group's tenant-side data and parks the +request; an operator then redacts the person's audit rows in a platform transaction and +completes it. Five units landed in `cdbb58f6` (platform keys, registry entries and the +redactor port), `8a27e5be` (operator inspection and completion), `1d010cad` (the Audit +executor and the user-reference locators), `ec1f26bd` (the real executor run through +the operator act) and `7d6b0d88` (the Identity erasure). Closure and the web surface +are Steps 3 and 4. + +Delivered: + +- **Request path.** An erasure is `scheduled` for 24 hours, then `fulfilling`, then + `awaiting_privileged_step`, then `completed` by the operator; the person may cancel + while it is `scheduled`. The same create and cancel paths serve the live own, + administrator and retained-entry callers. +- **Tenant erasure.** One job per group takes the person's User fence and the tenant + key, then, in one transaction, revokes the person's export artifacts and unstarted + exports, removes the frozen Membership snapshot's assignments, clears its profile and + revokes it, revokes the pending invitations the person issued, records every + participant's retained report and parks the request. The Membership and Invitation + erasure operations run only under a sealed `DataErasureWitness` with one minting + source, and a forward migration + (`20261122203000_admit_erasure_profile_clearing`) admits one clearing UPDATE of a + Revoked Membership's profile columns while the request is `fulfilling` and both fences + are held. +- **Privileged redaction.** `IAuditRedactor` (SharedKernel) and its executor in the + Audit module redact in keyset batches on `(timestamp, id)`, at the pointers each + module's `IUserReferenceLocator` declares, and only where the value equals the + subject's identifier or a frozen Membership id. A batch is cut at 100,000 rows or 64 + MiB of decompressed payload in the request's reach. The report is aggregate and + closed; no subject identifier appears in it, in a payload or in a log. +- **Operator surface.** `GET /api/platform/v1/data-requests` (inspection; + `platform.data_request.read`) and + `POST /api/platform/v1/data-requests/{requestId}/complete-erasure` (completion; + `platform.data_request.write`), each through the operator gate for the operation + `platform.data_request.inspect` or `audit.redaction.apply`. A completion runs the + redaction, the request guard's platform arm and the result row in one platform + transaction + (`20261122200000_grant_platform_data_request_operations`). A closure's fan-out erasure + is refused here with `lockey_data_request_closure_fanout`. +- **Proof.** `DataErasureReplayFloorTests` run the real operator completion and then + replay the person's events, and an erasure never resets the replay floor + ([ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) § 9). + The runbook is [Data erasure](../runbooks/data-erasure.md). + +The decisions the code took that the ADR text does not state are items 21 to 55 of the +list under the closeout. + +### P03-10 Step 2 — review round 1 and its fixes (2026-11-23) + +Seven fresh read-only reviewers read the head of the five units by lens (audit +redaction, database guards, the erasure core, the operator surface, the API, test +adequacy and documentation) and every finding was checked against the code before it +was fixed. The ones that changed code: + +- **Fan-out refusal and guards (`b62a1122`).** The standalone completion refuses an + erasure born of a closure's fan-out, and the platform arm's arrow excludes that + origin; the request guard was hardened, the counter + `learnstack_platform_operator_data_requests_total` was added, the replay-floor test + was written and the runbook was corrected against the code. +- **Proof gaps (`7dd82523`).** The test additions the test-adequacy slice named, for the + erasure core and the redaction's pins. + +### P03-10 Step 2 — review round 2 and its fixes (2026-11-23) + +Six fresh reviewers read the head of round 1: a regression check of the fixes, the +database guards, the erasure core, the operator surface, test adequacy and +documentation, and a replay-floor strengthening agent. None found a blocker. The +verified findings were fixed in isolated clones and merged: + +- **A request born `fulfilling` (`1d1057bc`).** The request guard admits no request born + `fulfilling` in this step, because a closure's fan-out erasure would otherwise stand + in, with no window, for the witness of the profile clearing; Step 3 relaxes the INSERT + arm with its own witness. The contextual guard's witness also requires the request's + frozen snapshot to name the Membership. +- **The batch and its census (`a1af5c32`, `367bb9e4`).** A redaction batch is bounded by + payload bytes, not rows alone, and the budget counts decompressed bytes in the + request's reach (a heavy-payload tenant of 150,000 rows of about 100 KiB completes in + about four minutes with every statement under two seconds, where the row-only cut timed + out). The locator census is closed and an end-to-end test asserts no subject + identifier survives in a payload. +- **Proof and documents (`4bb52e4f`, `b3653eff`, `560cbed4`, `7d830535`).** The + replay-floor proof runs the real operator completion before the replay; the runbook, + the Audit and Identity module documents and the standards were corrected against the + code; a third wave of unit and integration tests closed the gaps the reviewers named. + +### P03-10 Step 2 — verification and closeout (2026-11-23) + +Step 2 is delivered and twice reviewed. The head of round 2 (`7d830535`) ran the full +architecture suite in a clean clone: 693 passed and one failed, 1 hour 25 minutes. The +failure was `BackgroundJobManifestBoundaryTests.JobManifestControllerActions`, a pin +that lacked the new erasure, closure and revocation actions of the data-request +controllers, fixed in `38c5c65c`. The same head ran the full integration suite in a +clean clone: 5,117 passed and 40 failed, 2 hours 17 minutes, and none of the 40 is a +defect of the packet: + +- Twenty-six need the frontend dependencies that a clean clone lacks (the native BFF + session, public rendering, admission and local launch fixtures). +- One fails only in a Release build, because FluentAssertions cannot name the subject + without the source path (`AuthenticatedHttpSurfaceRuntimeTests`, a federation census); + it passes in Debug. +- Thirteen are one pin, the Identity function census in `GlobalIdentitySchemaTests` and + `IdentityCommandQualificationTests`: the completed-export guard of Step 1 (`a0e560fc`) + and its constraint trigger were never counted, so the census asserted 39 functions + where the chain had 40. Step 1's targeted runs did not reach it. It is corrected in + `60eea19e` (Step 3), which also counts that unit's own definer. + +The head of Step 2 contains all of Step 1's code, so this run also closes Step 1's open +verification: no request, export, retained-scope or migration class failed apart from +the census above. The unit suite on the working tree passes (5,041), the contract suite +passes (15), and the OpenAPI document differs from the Step 1 head only by additions. + +Open for the maintainer, as the amendments the code needs and the choices the ADRs left +(numbers refer to the maintainer list kept with the PR): + +- **A person re-admitted during the 24-hour window is erased at execution** (34). + ADR-0106 § 3 holds "an administrator erases only for a Revoked Membership" at creation + only. Either add a closed refusal `blocked_membership_current` at execution, which + touches ADR-0106 §§ 7 and 8, the DDL vocabulary, one migration and the copy, or accept + that the person may cancel in the window. +- **`ip_address`, `user_agent` and `actor_email` become NULL on every selected row** + (38), also on a row whose actor is an administrator that the selection reached through + a payload reference, as ADR-0108 § 5 reads literally. Keep it, or narrow it to rows + whose actor is the subject. +- **The act is linear in the tenant's audit volume** (39, 49, 54): about 12 seconds + for 1.5 million ordinary rows, and a batch is cut at 100,000 rows or 64 MiB of + decompressed payload in the request's reach. A GIN index over payload identifiers + would remove the scan and needs its own decision. A client or gateway abort rolls the + act back. +- **The retained classes the list cannot count** (31, 47, 50): transport and execution + evidence, the idempotency cache, external copies and the invitation envelope have no + subject-keyed count, and a pending offer addressed to the person's e-mail address is + not locatable by person, so the receipt's list is partial and says so. The web copy of + Step 4 and Phase 11's counting beside the purge own it. +- **The 30-day target of an awaiting erasure has no automated detector** (53); Phase 11 + owns a backlog gauge and its alert rules. +- **Smaller text amendments:** the locator registrations fall under the no-cross-module + rule (32); the retained-entry set is larger than ADR-0106 § 9 counts (33); the + contextual guard's exception clears a Revoked parent only, so Active and Suspended + Memberships are cleared before they are revoked (30); a request is never born + `fulfilling` outside a closure's fan-out (44); the window's lower bound is judged + against `transaction_timestamp()` (45); the erasure holds the tenant's identity fence + exclusively while it computes the retained report (42); the completion replaces the + three audit kinds the participant counted and adds `unscoped_audit_rows` for an + administrator's request (50); an invitation-revocation `changes` array is elided + above about 700 offers by the 256 KiB audit cap (41); the redaction is a one-time + rewrite, so a later edit of a record the person created writes the identifier again + (37, 55). +- **Unreleased migrations of this packet:** `20261122200000` and `20261122203000` are + new, and four Step 1 migrations were edited in place; a development database created + from an intermediate commit of this branch must be dropped and migrated again. + +### P03-10 Step 3 — global account closure (2026-11-23) + +Step 3 delivers the closure half of +[ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) §§ 7 to +10: the person files a closure of their whole account, an operator Begins it, a +per-group fan-out erases each participant group's tenant-side data, and an operator +Finalizes it, which redacts the person's audit rows in every participant tenant and the +platform sentinel, deletes the identity-provider account and moves the User to Closed. +It landed in ten commits: `6c6d8389` (the ports), `877ffda1` (the Keycloak removal +adapter), `100ee968` (the closure redaction plans), `e807ad84` (the person's filing), +`60eea19e` (storage and guards), `38c5c65c` (the census), `25d0776e` (Begin), `b94e4290` +(the fan-out), `9e780196` (Finalize) and `056422ca`. + +Delivered: + +- **Filing.** The person alone files a closure, live + (`POST /api/v1/identity/me/data-requests/closures`) or through the retained entry + (`…/data-request-entry/closures`). An administrator never files, reads or cancels one. + The request waits 24 hours and is cancellable until a Begin commits. +- **Storage.** `20261123100000_admit_account_closure`: platform grants for the + person's status, subject key and Memberships; a `users` trigger exception that admits + Active to Closing and Closing to Closed only for the platform role with the person's + fence and every participant tenant's fence held on that connection (read from + `pg_locks`, never a flag); the request guard's closure arrows and the fan-out INSERT + witness; the definer `fn_identity_user_status`. A second migration + (`20261123110000`) refuses a delayed provider-event delivery about a person who is not + Active, and a third (`20261123120000`) lets the platform complete a closure that never + began, so a second closure inside its window cannot outlive the person. +- **Begin.** `POST /api/platform/v1/data-requests/{id}/begin-closure`: one platform + transaction takes the person's User fence and every participant tenant's fence + (`PlatformIdentityFences`, transaction-scoped, ordered, bounded by a three-second lock + timeout), judges the window, the hold port and the last administrator of every + participant tenant that allows ordinary work, moves the User to Closing and the + request to `fulfilling`, and commits; the fan-out follows. +- **Fan-out.** One admitted pipeline act per served group + (`identity.data_request.fan_out_closure`) creates or adopts the person's erasure of + that group, born `fulfilling` with no window; the operator act executor announces the + group's organization for this one operation. A repeated Begin resumes. +- **Finalize.** `POST …/finalize-closure`: transaction 1 redacts every participant + tenant and the sentinel and writes an attempt row; the provider account is deleted + with no transaction or lock held; transaction 2 takes the fences again, moves the User + to Closed with the raw provider subject removed, completes the participants' erasures + and every open closure of the person, and writes the result row. Every step repeats + safely. +- **The provider port.** `IIdentityProviderAccountRemoval` with the fail-closed default + and a Keycloak adapter whose confined realm client holds `manage-users` only; the + runbook is [Account removal client](../runbooks/account-removal-client.md) and the + operator's is [Account closure](../runbooks/account-closure.md). + +Decisions the code took that the ADR text does not state are items 56 to 70 of the +maintainer list; they are summarised under the closeout. + +### P03-10 Step 4 — the web surface (2026-11-23) + +Step 4 delivers the web surface of ADR-0106 and ADR-0107 on the native BFF in two +commits: `28e23840` (the person's own pages) and `bd996a0b` (the administrator's surface +in Studio). The person opens `/account/data` and sees their requests, files an export, +an erasure or a closure, cancels, revokes an export and downloads it as one attachment +relayed chunk by chunk under a short-lived ticket, with working forms and no required +script, in English and Turkish, in the live session or through the retained entry. An +administrator sees the requests of their scope in Studio, files an export or an erasure +for a Revoked member with an explicit confirmation, cancels what they filed and revokes +an available export. The SDK gains 24 wrappers over the committed OpenAPI; the copy has +one sentence for every refusal the API emits and a test that fails when the API gains a +key the copy lacks. + +### P03-10 Steps 3 and 4 — review round 1 and its fixes (2026-11-23) + +Fourteen fresh read-only reviewers read the head by lens: for Step 3 the database and +guards, the owner and fences, the fan-out and delayed consumers, the audit redaction, +the Keycloak adapter, the API and catalogue, the tests and the documents; for Step 4 the +BFF security, the SDK contract, the copy and accessibility, the Studio surface, the +frontend tests and the standards text. No Blocker was found; the verified findings were +fixed by six isolated units and merged. The ones that changed behaviour: + +- **A person Begin could strand in Closing** (found by four reviewers). Begin accepted + up to 1,024 participant groups while the fan-out refused more than 256, the redaction + plan refused more than 256 Memberships in one tenant, and a provider subject the + adapter refuses could never be deleted. Begin now judges every such bound and the + removal port's preflight before the irreversible move and writes nothing when it + refuses (`RefusedTooLarge`, `RefusedProvider`). One constant, `ClosureLimits`, holds + the bounds. +- **Finalize held every participant tenant's fence for the whole redaction.** Its first + transaction now takes only the person's User fence; the tenant fences are taken in the + second transaction, where the database witnesses need them. The second transaction + locks the awaiting erasures, accepts one the operator completed meanwhile, keeps a + now-unserved group with an open fan-out erasure required, and answers an audit failure + after the provider step as retryable. A forward migration + (`20261123130000_harden_closure_request_guard`) stops the application role writing a + begun closure and removes a status oracle. +- **The redaction and the adapter.** The payload filter has a hashed form from 128 + spellings (a closure tenant pass with 256 Memberships went from 76-80 s to 21-23 s), + the sentinel pass sizes no payload, a 404 is "absent" only with the provider's JSON + media type, the adapter's ceiling sits behind the pipeline timeout, and every refusal + logs one closed reason code. +- **The download relay.** The API admits 60 requests a minute per visitor and a chunk + read is one request, so an export above about 7.5 MiB could never finish; a 429, or a + 503 with `Retry-After`, is now a pause within the ticket's deadline, a stalled client + is cut after a no-progress limit, and a failure after the headers always destroys the + connection. +- **The Studio surface was unreachable.** A Revoked Membership's page is not readable, + so the erasure form never rendered; a successful revoke now leads to an erasure page + keyed by the Membership id. Every successful administrator action also failed in + production, because the BFF admission refused any redirect that carried a query; it + admits exactly the result targets now, with tests through the real middleware. +- **The person's page told some untruths.** A stopped erasure now shows its reason, the + retained intro no longer assumes a suspended membership, the closure warning names the + groups that keep their data, no sentence claims a retention rule that does not exist, + the retained pages state when the five-minute entry ends, and the Turkish copy was + revised for meaning and register. +- **Proof.** Test-only units closed the gaps the test reviewers named by value (each + participant tenant redacted, including an unserved one; each erasure's own counts; the + judgment order; a lost commit answer; Begin and Finalize racing another operator) and + frontend tests now post every route in both modes and drive the retained flows and the + owner-mode selection. + +### P03-10 Steps 3 and 4 — review round 2 and the usage limit (2026-11-23) + +Round 2 launched eight fresh Step 3 reviewers on the head of round 1. Their runs stopped +when the agent account reached its weekly usage limit, which resets on 2026-11-26: the +API and vocabulary slice and the Keycloak and operability slice reported in full, and +the database, owner and fences, red team, audit redaction, test adequacy and documents +slices did not. Round 2 for Step 4 was not started. Both are owed and are listed under +the closeout; nothing in them is treated as passed. + +What the two completed slices found and what changed: the removal port's preflight did +not cover an unusable secret (a masked or oversized secret would have admitted a Begin +that no Finalize could finish; `CanRemove` now requires a secret the client can +present); the served contract and the operator runbooks said "nothing changed" for a +Finalize that fails after the provider step, and an audit failure at its last row was no +longer counted (the text, the runbooks and the audit-failure counter are corrected); the +console search by identifier needs the `id:` form; and a few stale statements. The full +architecture and integration suites on the head of round 1 then found two regressions +the targeted runs had not: the fan-out's registration required the operator gate in +hosts that compose persistence alone, which stopped 224 HTTP integration tests from +starting, and the setter census matched the fence acquirer's `lock_timeout` bound. Both +are fixed (`ac687dc3`). + +### P03-10 — owed ADR amendments and maintainer decisions (2026-11-23) + +The list below collects what the implementation found that the Accepted ADR text does +not say, the decisions the code took and the choices left to the maintainer. The step +records above cite its item numbers. No Accepted ADR body was edited: each item that +changes a decision is owed a dated Amendment under +[ADR-0041](../decisions/0041-correcting-false-statements-in-accepted-adrs.md), written +once the maintainer has ruled; the items marked DECISION, OPEN or owed to the user need +a ruling first. Items 1 to 20 are Step 1, 21 to 55 Step 2, and 56 to 71 Steps 3 and 4 +with the review fixes; some earlier items were superseded by later ones, as item 52 +says. + +1. ADR-0107 § 8 platform UPDATE list lacks `last_refusal` (closure Begin refusal must + record it, § 7). Step 3: add `last_refusal` to the platform column UPDATE grant; the + platform arm of the request guard stamps `updated_at`/`updated_by` itself + (trigger-set NEW columns need no column grant). +2. ADR-0107 § 8 gives the platform role no privilege on `data_export_artifacts`, but + `inspect` (§ 8) lists expired artifacts not yet purged. Step 2: column-limited + platform SELECT on artifacts (id, tenant_id, request_id, status, expires_at: five + columns; the group comes from the joined request; no subject, no counts). +3. ADR-0106 § 8 "failed is read from the job phase" vs the one-active partial unique + index, which frees a slot only for a STORED terminal status. Resolution: + reconcile-on-observe (store failed/execution_failed when a dead job is observed by + the create path / operator inspect), receipt derives failed for display. Unit 2 + builds the reconciler. +4. ADR-0107 § 3 says a cap hit is stated "in the receipt"; the request `result` column + is the closed retained-kind vocabulary. Resolution: `truncation` jsonb on + `data_export_artifacts` (set at insert, closed shape). +5. Unit 1 deviations accepted: app UPDATE columns wider than § 8 text (last_refusal, + failure_reason, completed_at, updated_at, updated_by, purged_at); request guard + requires the User exclusive fence at creation; Down migration forward-only; platform + writes refused by the guard until Steps 2 and 3 add their arms; DELETE refused for + all roles. + +**Added by Step 1 review round 1 (2026-11-22)** +6. ADR-0107 § 3 / ADR-0108 § 4 say a self-requested export selects audit rows "across + the whole tenant". The export job runs as a background job: it has no Protected + tenant-wide read witness, so `app.scope` is never `tenant` and RLS shows an + organization group its own organization's rows plus tenant-level (NULL organization) + rows; a tenant-wide group sees only NULL-organization rows. Consequence: a + tenant-wide Membership holder who acted inside an organization context has audit rows + no export can reach (they hold no Membership of that group). Step 1 makes the reach + explicit in the bundle (`audit_scope`) and the docs. MAINTAINER DECISION (PR): either + amend § 3/§ 4 to the RLS-visible reach (current behaviour), or decide a sanctioned + tenant-wide read for the export job (needs an ADR; touches ADR-0047 trusted job + policy and the operation read witness). +7. ADR-0107 § 4: the ticket "authorizes the sequential chunk reads of one download"; + implemented as: any chunk index below the count, any order, until the final index is + served (then consumed); no position column exists (§ 8 grants only `consumed_at`). + Amend § 4 to say so; outstanding tickets per artifact are bounded (3) by this step. +8. ADR-0107 § 8 app-role UPDATE grants: the implementation also grants last_refusal, + failure_reason, completed_at, updated_at, updated_by (requests) and purged_at, + row_version, updated_at, updated_by (artifacts); exact lists are in + `DataRequestStorageDdl.Grants`. +9. ADR-0106 § 7 lets the retained path file "where the person has a request"; a request + needs >= 1 Membership snapshot and Memberships are never deleted, so a request-only + group is unreachable; eligibility requires a Membership row. +10. ADR-0106 § 8: an export reads `requested` until it completes (the job runs requested + -> fulfilling -> completed in one runtime transaction); `fulfilling` is not + observable for exports. +11. Retained path cannot revoke an artifact (`OwnDataRequestPurpose` has no Revoke); + ADR-0107 § 4 says "the subject may revoke". Decide at Step 2/4. +12. PRE-EXISTING (not this packet): `pg_current_xact_id()::text::xid` fails with 22003 + once the cluster passes its first xid epoch (verified on postgres:18.4: + `'4294967296'::xid` errors; `pg_current_xact_id()::xid` works). Sites: + TenancyAdministrationDdl.cs:52, TenancyRetainedDefaultDdl.cs:51, + ContextualIdentityStorageDdl.cs:173,391. P03-10 removes its own use; the four older + sites need a follow-up migration (owner: maintainer / next Identity-Tenancy packet). +13. Retained recheck (R3-1): `RetainedDataRequestAdmission.RecheckAsync` is + identity-only; Step 3 (user closure) must re-validate the binding and User status + under the User fence on both paths. +14. Expired-artifact purge has one scheduled job (6 attempts, ~1 h): no automated + sweeper; `inspect` (Step 2) lists expired-unpurged artifacts; the automated sweeper + is Phase 11 (retention purge, ADR-0107 § 6). + +**Added by Step 1 review round 2 (2026-11-22)** +15. New rule: an ADMINISTRATOR-origin export is refused (409, `errors.$` = + `lockey_subject_export_available`) while the subject holds a readable (available, + unexpired) artifact of any origin, because completing it revokes that artifact + (ADR-0107 § 4 "a new export revokes the previous"). A subject's own export is + unchanged. ADR-0106 § 7 / ADR-0107 § 4 amendment owed. +16. Ticket bounds: at most 3 open (unconsumed, unexpired) tickets per session binding + per artifact (`DataRequestLimits.MaximumOpenTicketsPerBinding`), at most 20 ever + minted per artifact (`MaximumTicketsPerArtifact`); distinct refusals + `data_export_unavailable` (artifact gone / key left the ring) vs + `data_export_ticket_limit`. Enforced in the application under the artifact row lock + (a DB guard would race). ADR-0107 § 4 amendment owed. +17. `audit_scope` in the bundle is a closed record `{"reach":…,"complete":false}`; audit + selection is windowed per branch (two disjoint partial indexes, measured 2.2-3.4 s + -> ~1 ms on 2.3M rows); `audit_metadata_reference` is a lower bound beyond a + 500k-row scan window. Counts of retained references are a partial list (a kind + absent is not zero). +18. Metrics/logs added: counter + `learnstack_data_export_downloads_total{operation,outcome}`, purge outcome `failed`, + event 7507; custody refusal logs Critical once per (artifact,key) pair per process, + Warning after. +19. A job-dead export is stored `failed/execution_failed` by the reconciler (create + path); a receipt can show `failed` while the stored row still reads `requested` + until observed (runbook documents it). +20. Four unreleased Step 1 migrations were edited in place (index, trigger, grants): dev + databases created from intermediate commits must be dropped and re-migrated. + +**Added by Step 2 planning (2026-11-22)** +21. ADR-0108 § 5: redaction at a declared pointer is conditional on value (equals the + subject's UserId or a frozen Membership id); an unconditional replacement would also + erase other people's values (an administrator's UpdatedBy). +22. ADR-0107 § 1: the erasure job runs every participant's Erase in the job's one + transaction (ADR-0047 gives one transaction per root attempt); only Identity writes + today; progress still names each participant. +23. ADR-0107 § 8 "in the style of ADR-0103 § 6" should read ADR-0103 Decision item 1 / + the `platform.delivery.inspect` row. +24. Audit slug placement: `platform.data_request.inspect` (module platform) and + `audit.redaction.apply` (module audit) are declared from the Tenancy catalogue + source with the other platform off-path slugs. +25. Operator-side status writes stamp `updated_by = UserId.SystemActor`; the operator + attribution is in metadata.operator. +26. ADR-0107 § 8: platform SELECT on data_export_artifacts is column-limited (no + subject, no counts) for `inspect`. + +**Added during Step 2 review round 1 (2026-11-22)** +27. ADR-0108 § 6: the redaction report and the request receipt carry no retention target + for the audit row's class; only the runbook links Audit Coverage § Retention. Owner: + P03-10 Step 4's receipt copy, or the amendment says a link suffices. +28. ADR-0108 § 8: "aggregated beyond 200 groups" is not implemented and not needed: the + report's keys are closed (< 1 KiB). +29. ADR-0107 § 1: "Audit's participant plans": the Identity owner builds the plan from + the locked request row (`new AuditRedactionPlan(request.Subject())`); the Audit + participant plans nothing. +30. ADR-0107 § 5: the contextual-guard exception covers "a Membership of any status" + only for a Revoked parent; Active and Suspended Memberships are cleared through the + ordinary path before `RevokeForErasure` (cleared, then revoked). +31. ADR-0107 § 9 / ADR-0107 § 6: "reported as retained transport evidence" has no + producer: `transport_evidence`, `execution_evidence`, `idempotency_cache`, + `external_copy` and `invitation_envelope` have no subject-keyed count (the app role + holds no SELECT on the envelope table). The list is partial; docs say so. Owners: + P03-10 Step 4 (the web surface names those classes in its copy) and Phase 11 + (counting beside the purge). `unserved_group` is Step 3's. +32. ADR-0010 Amendment 6: locator registrations fall under the no-cross-module-reference + rule (`No_Module_References_Another_Modules_User_Reference_Locator`). +33. ADR-0106 § 9: the closed retained-entry set is eight operations (list, discovery, + export creation, erasure creation, cancel, revoke, ticket, chunk) and keyed + operations 30, 31, 34, 35 (ADR-0106 § 9 says six). +34. DECISION OWED (maintainer): ADR-0106 § 3 holds "an administrator erases only for a + Revoked Membership" at creation only; a person re-admitted during the 24 h window is + erased at execution (artifacts, exports, issued invitations, and an + administrator-origin audit redaction in the group). Options: new closed refusal + `blocked_membership_current` at execution (ADR-0106 §§ 7/8, the DDL vocabulary, one + migration, copy) or accept (the person may cancel in the window). +35. Step 4 copy owed for every `errors.$` key of the data-request API: + `request_already_active`, `blocked_hold`, `blocked_last_administrator`, + `subject_export_available`, `subject_membership_current`, `data_export_unavailable`, + and the round-2 keys `data_request_window_ended`, `data_request_not_cancellable`, + `subject_is_requester`, `snapshot_too_large` (all with the `lockey_` prefix on the + wire). +36. ADR-0107 § 7/§ 8: the standalone `complete_erasure` refuses a closure's fan-out + erasure (409 `errors.origin` = `lockey_data_request_closure_fanout`, and the + platform arm's arrow excludes `origin = closure_fanout`); Step 3's Finalize extends + the one marked arrow condition. +37. ADR-0108 § 6: the redaction is a one-time rewrite; attribution columns stay on the + tenant's records, so a later edit of a record the person created or last updated + writes the identifier again. Runbook states it. +38. ADR-0108 § 5 read literally: `ip_address`, `user_agent` and `actor_email` become + NULL on EVERY selected row, including a row whose actor is an administrator (the + selection reached it through a payload reference): the administrator's address and + e-mail are lost with it. Maintainer decision: keep (literal) or narrow to rows whose + actor is the subject. +39. The act's duration is linear in the tenant's audit volume (~10 s per 1.5 M rows + measured); a GIN index over payload identifiers would remove the scan and needs its + own decision. A client or gateway abort rolls the act back. +40. ADR-0107 § 8: a per-outcome counter + `learnstack_platform_operator_data_requests_total{operation,outcome}` exists (not in + the ADR text). +41. Invitation revocation evidence: above ~700 pending offers one erasure's `changes` + array is elided by the 256 KiB cap (ADR-0044 § 7); the invitations' own `Revoked` + rows are the record. The job's time is not a limit (10 000 offers ~5 s). +42. The erasure job holds the tenant's identity fence exclusively while it computes + every participant's retained report (the Audit counts are up to a 15 s budget): + other identity writers wait 2 s then 503. Documented in the runbook. +43. Steps 1-2: Identity migrations `20261122200000` and `20261122203000` are new in this + packet; databases created from intermediate commits of this branch must be dropped + and re-migrated (as for item 20). +44. ADR-0107 § 7 / ADR-0106 § 8: the request guard admits no request born `fulfilling` + in Step 2 (a closure's fan-out erasure would otherwise stand in, with no window, for + the witness of the profile clearing); Step 3 relaxes the INSERT arm with its own + witness. The contextual guard's witness also requires the request's frozen snapshot + to name the Membership. +45. ADR-0106 § 5: the 24-hour window's lower bound is judged against + `transaction_timestamp()`, so a filing transaction held open for an hour commits a + request whose window already lost about an hour (low risk; not changed). +46. LATENT (C-4): the erasure withdraws only `available` artifacts; no path writes + `expired` today, and the purge job moves an expired artifact to `purged`. If a + future writer records `expired`, `FindAvailableArtifactsAsync` must include it. +47. ADR-0107 § 6: `invitation_record` counts the offers the person issued or accepted; a + pending offer addressed to their e-mail address is retained and not locatable by + person, so not counted (runbook, README and the OpenAPI `retained` text say so). +48. ADR-0108 § 6: the key of a second instance of a User or Membership that a row + carries (a person admitted again: the row's designated Membership is the first, the + second travels in `changes`) survives only as the instance segment of the `changes` + path (`/Membership//…`). It is the same pseudonymous key ADR-0108 § 6 retains as + `entity_id`, and is retained the same way (no value of it is redacted; the + end-to-end redaction test allows exactly those segments). Such a row is not counted + in `audit_entity_reference` for the second instance (a lower bound). +49. ADR-0108 § 4 / amend-u2 items 4 and 10: a selection batch is a half-open range on + `("timestamp", id)`, newest first, cut at 100 000 rows or 64 MiB of stored payload + (`pg_column_size` of the three payload columns, never detoasted), whichever is + first; a row larger than the budget is a batch of its own. Heavy-payload tenants + complete (150 k rows of ~100 KiB: ~4 min, every statement ≤ 2 s) where the earlier + row-only cut timed out. The act's duration is in stored bytes, not rows. +50. ADR-0107 § 6 / ADR-0108 § 6: the operator's completion REPLACES the three audit + kinds (`audit_actor_reference`, `audit_entity_reference`, + `audit_metadata_reference`) the Audit participant had counted while the request + waited with the redaction's exact counts (`audit_metadata_reference` goes from a + lower bound to exact) and ADDS `unscoped_audit_rows` for an administrator's request; + every other kind stays as its participant recorded it. A receipt's numbers change at + completion. +51. Step 4 copy also owes `lockey_data_export_ticket_limit` (the data-request API emits + it). +52. Superseded or obsolete list items: amend-u3 #10 (the actual-replay proof is + delivered: `DataErasureReplayFloorTests`, with the real operator completion before + the replay), amend-u3 #12 (the Standard 18 and Identity README carriers are + written), amend-u1 #7's last sentence, amendments-owed #39 and amend-u2 #4/#10 (see + #49: 100 000 rows or 64 MiB, duration in stored bytes). +53. ADR-0106 § 12 / Phase 11: the 30-day target of an awaiting erasure has no automated + detector; Phase 11 owns a backlog gauge and its alert rules (written into the Phase + 11 observability sentence). +54. ADR-0108 § 4 (supersedes the stored-bytes part of #49): the batch budget (64 MiB) + counts payload DECOMPRESSED and only for rows in the request's reach (a compressed + column is sized by the decompressed document; an uncompressed one by its stored + size; rows outside the reach count 0, because the selection never reads their + payload). Measured: 1.5 M ordinary rows ~12 s whole tenant (was ~8 s when counting + stored bytes), 30 000 × 250 KB compressible ~3-4 s, no statement above ~1.2 s + anywhere. A larger decompressed budget with a separate UPDATE chunk limit was + considered and not done. +55. The redaction covers rows committed before the act begins; a row committed during it + is not redacted (one-time rewrite, #37). Two requests for the same person (self + + administrator) can wait on or deadlock with each other: 503, retry. + +**Added during Step 3 and Step 4 implementation (2026-11-23)** +56. Step 4a: `RetainedDataRequestScopeResponse` carries no organization display name, so + a retained person with several organization groups sees "This institution as a + whole" or "Branch 1, 2, ..." and the copy says names cannot be shown. A label would + need the discovery definer to read Tenancy's `organizations` table (cross-module) or + a separate Tenancy read: needs its own decision (see `amend-s4a.md` § 4). +57. Step 4a: ADR-0106 § 9 lists a retained "read"; the API has no such operation (the + retained list carries the full receipt). Amend the list. +58. Step 3 A4 item 6 (a filing racing Begin/Finalize) is closed by A1 item 2a: the + request guard's INSERT arm reads `users.status` under the exclusive User fence, and + B2 maps its refusal to `lockey_subject_not_admitted` on every creation route. +59. Step 3 B2 findings not closed (owner Phase 11 or the maintainer): the invitation + e-mail jobs do not check the inviter's User status between Begin and that group's + fan-out erasure, and an export job filed before Begin may store an artifact before + the fan-out erasure withdraws it. + +**Added by review round 1 and its fixes (2026-11-23)** +60. ADR-0107 § 7 (dated amendment, from fx1): Begin refuses before the move, with + nothing written, a person with more than 256 participant groups or more than 256 + Memberships in one tenant (`ClosureLimits`; closed answer `errors.participants`), + and a person the removal port cannot delete (`CanRemove`: a subject the adapter + refuses, or no client configured; `errors.provider`); the Finalize bullet's first + transaction takes only the User fence and the second all fences (Standard 05 + erratum); readiness = newest erasure awaiting the privileged step or completed + at/after Begin with a covering snapshot, a now-unserved group with an open fan-out + erasure stays required; the second transaction locks the awaiting erasures and + accepts one the operator completed; an audit failure after the provider step answers + a retryable 503; the fan-out adopts a group that already holds a completed fan-out + erasure. +61. ADR-0106 § 8: the closure state table gains `scheduled -> completed` (platform role + only, Closed person, all fences), from Finalize; the application arm refuses any + UPDATE of a closure that has left `scheduled` (migration + `20261123130000_harden_closure_request_guard`). +62. ADR-0108 §§ 4-5: the payload filter has two forms (array test below 128 spellings, + hashed set lookup from 128: a closure tenant pass with 256 Memberships went from + 76-80 s to 21-23 s); the sentinel pass sizes no payload. Measured on a loaded host: + ratios hold, absolute seconds are rough. +63. ADR-0107 § 7 "a missing user is success" means the provider's own JSON 404 only; any + other 404 is a refusal (a proxy's 404 must not close a person whose account exists). + The adapter logs one closed reason code per refusal (event 7125). Real Keycloak + 26.7.5 answers `404 application/json {"error":"User not found"}` (evidence + `p0310/fx3-e2-evidence.txt`). +64. KNOWN LIMITS (no code): rows naming the person that an unserved tenant, a late job + or a late sign-in writes AFTER Finalize's redaction are not redacted (one-time + rewrite, #37/#55); an administrator filing for a Closed person's tombstone writes a + failure row naming the person's UserId (needs `fn_identity_user_status` outside + trigger depth); an unserved tenant's rewritten rows have no record in its own trail + (its fan-out request does not exist); a tenant administrator can see a fan-out + erasure (`origin = closure_fanout`) and learns a member is closing (intended; one + sentence in the Identity README, amendment to ADR-0106 § 3 "never reads a closure"). +65. ADR-0064 DECISION OWED (maintainer): the API budget is 60 requests/minute per + visitor IP and every chunk read is one request, so an export above about 7.5 MiB + takes minutes (the relay now pauses on 429/503 Retry-After and finishes within the + ticket deadline); a dedicated, larger budget for chunk reads, or larger chunks + (ADR-0107 § 4), is the real fix. Also: the production ingress idle timeout must + exceed ~70 s; browser behaviour on a destroyed connection (Chrome/Firefox/Safari) is + not verified. +66. WCAG 2.2.1 (maintainer): the retained entry (and the consent entry) is limited to 5 + minutes from sign-in, never extended; the page states the end time; an extension + mechanism or a recorded "essential" justification is owed. C20 exception record for + `/account/data` (locale from `Accept-Language`, fixed neutral stylesheet, Standard + 07). +67. ADR-0107 § 6 / Standard 04: idempotency rows are said to last 24 hours but expired + `idempotency_keys` rows (response bodies included) are never deleted: Phase 11 purge + or an amendment. +68. Contract asks from the web surface: a list/read of Revoked Memberships for an + administrator (today the erasure page is reached only from the revoke redirect or an + id from the audit row), a subject name on the administrator receipt, a + `membershipId` filter on `ListDataRequests`, an organization label on the retained + scope response (#56). The erasure page takes the Membership id as a query + (`/studio/data-requests/erasure?membership=`): a path id would survive + sign-in/re-authentication returns. +69. Owed to the user (a `.claude` file): `.claude/skills/local-dev-setup/SKILL.md:84` + omits `KEYCLOAK_ACCOUNT_REMOVAL_SECRET` (compose requires it). Turkish consent copy + in `auth.json` still says "izin" where the portal says "rıza"; the entry page's + consents link has the no-account 401 problem the data link had (not changed). +70. Chromium proof: no browser proof of `/account/data` or the Studio pages was run (the + proof views are unit-tested; `verify-bff-session.mjs` is not wired for them): a + Status-block item. +71. The Studio member page (Step 4) also reads the group's data requests, so each view + of a member page adds one MUST `identity.data_request.list` audit row and one call + under the 60/min visitor budget (ADR-0064). The warm-realm BFF proof counted both + exactly and failed on the extra row and then on a 429; it is corrected in + `a1ce6b12`. A `membershipId` filter on `ListDataRequests` (item 68) would let the + page ask for one member's requests only; the extra read per member page view stays + until a maintainer decides whether it is worth its audit row and permit. + +### P03-10 Steps 3 and 4 — verification and closeout (2026-11-23) + +Steps 3 and 4 are delivered and have had one review round each; the second round is +owed (see the round 2 entry above). The code head `ca2b08e0` ran the full architecture +and integration suites in clean clones, and the head `a1ce6b12` ran the unit, contract +and frontend suites in the working tree: + +- **Architecture:** 725 passed, none failed, 1 hour 51 minutes. +- **Integration, first run:** 4,754 passed and 618 failed, 1 hour 30 minutes. This was a + host failure, not a defect: 562 of the failures are `Can't assign requested address` + from the HTTP clients, the rest are cleanup failures of the same collections and two + Keycloak readiness timeouts, and the container runtime (OrbStack) had stopped when the + run ended and stopped twice more while it was restarted. After it stayed up, the 35 + failed classes that need no frontend dependencies were rerun serialized: 573 passed, + none failed, 40 minutes. +- **Integration, frontend-fixture classes:** the native BFF session, public rendering, + admission and local-launch classes need the frontend dependencies a clean clone lacks, + so they ran in the working tree with the runtime up: 39 of 40 passed. The one failure + was a defect of the packet's own proof, and is fixed (below). +- **Unit** 5,083 passed, **contract** 15 passed. **Frontend:** `pnpm typecheck` and + `pnpm lint` clean; `pnpm test` 5,222 passed in two packages with no skips; no Chromium + proof was run. +- One test fails only inside a full Release run, `AuthenticatedHttpSurfaceRuntimeTests` + `Production_endpoint_union_has_exact_patterns_methods_handlers_and_requests` + (Development). It asserts the text FluentAssertions builds from the source file, + passes alone in Release (7 of 7 in the same clean clone) and failed the same way at + the Step 2 head, so the Step 2 closeout's "only in a Release build" is narrowed here + to "only inside the full run"; the packet does not cause it. + +**The defect the frontend-fixture run found.** The Studio member page lists the group's +data requests, which adds one MUST `identity.data_request.list` audit row to the page +and one call under the 60/min visitor budget. `TenantBffSessionTests` pins both: it +expected seven selected-page audit rows and ended its first budget window after the +replacement check, which used exactly the sixty permits, so it failed on the eighth row +and then on a 429. `a1ce6b12` expects eight rows and ends the window before the +replacement check. The base commit `211b9fd3` passes the unchanged test with the same +instrumented counts (22 anonymous and 8 authenticated reads), so the difference is the +one extra call (item 71). Step 4's targeted runs could not reach this test because it +needs the frontend dependencies; a frontend-fixture run belongs to every later change +of a native page. + +Open for the maintainer: the rulings listed under "P03-10 — owed ADR amendments and +maintainer decisions" above (items 1 to 71), and the round 2 that the usage limit +stopped. Nothing in this packet's review is treated as passed beyond what is recorded. diff --git a/docs/roadmap/phase-03-identity-admin.md b/docs/roadmap/phase-03-identity-admin.md index eb95ac64c..3f521c58e 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-22).** 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), 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's decisions are Accepted and its implementation is in progress; P03-11 remains unstarted. > > | Packet | Title | State | > |---|---|---| @@ -37,8 +37,8 @@ > | 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-10 | DSAR and global account closure | Not started | +> | 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 | In progress — G15 and the G16 workflow Accepted ([package](phase-03-delivery-log.md#p03-10-decision-package-and-acceptance-2026-11-22)); Steps 1 (request core and export) and 2 (tenant erasure and privileged audit redaction) delivered and twice reviewed ([Step 1](phase-03-delivery-log.md#p03-10-step-1--verification-and-closeout-2026-11-22), [Step 2](phase-03-delivery-log.md#p03-10-step-2--verification-and-closeout-2026-11-23)); Steps 3 (global account closure) and 4 (web surface) delivered and reviewed once ([Step 3](phase-03-delivery-log.md#p03-10-step-3--global-account-closure-2026-11-23), [Step 4](phase-03-delivery-log.md#p03-10-step-4--the-web-surface-2026-11-23)); their second review round ran only in part ([record](phase-03-delivery-log.md#p03-10-steps-3-and-4--review-round-2-and-the-usage-limit-2026-11-23)) and the rest is owed; the suites and the defect they found are in the [closeout](phase-03-delivery-log.md#p03-10-steps-3-and-4--verification-and-closeout-2026-11-23) | > | P03-11 | Exit enforcement | Not started | ## Goal @@ -150,10 +150,10 @@ 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) | -| 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 | +| 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 | 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 @@ -713,23 +716,17 @@ and export/downloads as applicable MUST `read-sensitive` acts. No failed write i hidden by a duplicate HTTP/application audit or a generalized assertion budget. Extend every affected module matrix, including consent and federation changes. -**The erasure's audit redaction owes a decision before its handler lands.** The handler -[Audit Subsystem § 10](../architecture/31-audit-subsystem.md#10-gdpr--pii-redaction) -sketches writes its `audit.redaction.apply` row on the platform transaction that does the -redaction, before that transaction commits — a MUST row never follows the commit it -describes. `IAuditStore.WritePlatformScopeAsync` is the write that takes a caller's -platform transaction, and its contract admits one caller, the scope's own entry row. This -phase amends [ADR-0044 § 10](../decisions/0044-audit-write-path.md) to admit the redaction -result as a second, bounded caller or to give it a method of its own, and settles the -inbox boundary with it: the inbox mark lives on another connection, so a redelivery must -find the result row already written rather than record a second one. - -The same decision must account for immutable `actor_user_id`, entity/causation -identifiers and new `metadata.causal_actor_user_id` references. Current redaction -permits only `actor_email`, `ip_address`, `user_agent`, `before_state`, -`after_state` and `changes`; `metadata` is outside the column grant. Preserve -those boundaries until the bounded decision and any required migration ship. -Redacting the six columns alone does not establish complete anonymisation. +**The erasure's audit redaction is decided.** +[ADR-0044](../decisions/0044-audit-write-path.md) Amendments 17 to 19 added the +witness-bound result and intent writes, so `IAuditStore.WritePlatformScopeAsync` keeps +its one caller and no store method was added, and +[ADR-0108](../decisions/0108-privileged-audit-redaction.md) (Accepted 2026-11-22) +settles the rest: the redaction runs in one platform transaction, its result row names +the tenant, the grant stays at the six columns, and `actor_user_id`, entity and +causation identifiers and `metadata` stay outside it as pseudonymous keys, so the +redaction at each module's declared pointers is conditional on value. Redacting the six +columns alone does not establish complete anonymisation, and ADR-0108 § 6 states what +is retained. ### DSAR fulfillment and global closure @@ -756,6 +753,10 @@ remain their respective authorities. Before making a User nonadmitting, P03-10 takes the canonical User fence, then all affected exclusive Tenant keys, and retains them through completion under [Standard 05](../standards/05-database.md#lock-snapshot-and-adoption-conditions). + *Erratum (2026-11-23, [ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) + § 7):* "through completion" means through each nonadmitting transaction, Begin's and + Finalize's second. Advisory transaction locks end at a commit, so Finalize takes the + fences again after the provider call. Final-admin recovery/termination still requires its separately accepted contract. - Include ADR-0097's provider receipts, retained targets and their transport/Audit links in the subject-store inventory. P03-6 supplies receipt subject-key/User @@ -840,7 +841,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/roadmap/phase-09-billing-integrations-analytics.md b/docs/roadmap/phase-09-billing-integrations-analytics.md index 6ce9acaa9..a05d7b403 100644 --- a/docs/roadmap/phase-09-billing-integrations-analytics.md +++ b/docs/roadmap/phase-09-billing-integrations-analytics.md @@ -86,6 +86,11 @@ integration tests run against. - Subscription placeholder. - Coupon / discount placeholder. - Manual payment approval. +- The first `IDataRequestHoldSource` implementation + ([ADR-0106](../decisions/0106-subject-data-requests-authority-and-status.md) § 7): the + first aggregate here that can carry a hold (a payment dispute or a legal hold) reports + it, so an erasure or a global closure of that person stops with `blocked_hold` until + it clears. Phase 03 ships the port with the default `NoHoldSource`. ### Integrations diff --git a/docs/roadmap/phase-11-production-hardening.md b/docs/roadmap/phase-11-production-hardening.md index 29f2177cb..0bce54b4d 100644 --- a/docs/roadmap/phase-11-production-hardening.md +++ b/docs/roadmap/phase-11-production-hardening.md @@ -329,7 +329,9 @@ bounds request *cost* once a request is inside. Neither substitutes for the othe the realm must issue it; builds the database adapter for operator grants on its trigger, audited runtime grant changes; pins the operator OpenAPI document under a gate of its own; decides durable denial evidence if security monitoring requires it; - alerts on the operator counters; and owns the read-only dashboard decision, job + alerts on the operator counters and on a backlog gauge of data requests awaiting their + privileged step (the 30-day target of ADR-0106 § 12 has no automated detector until + then); and owns the read-only dashboard decision, job reconciliation and recurrence recovery that [ADR-0103](../decisions/0103-operator-recovery-of-asynchronous-work.md) leaves absent. - Secret management: Vault rotation cadence (90 days for provider keys, yearly for @@ -705,6 +707,21 @@ new erasure permission. Retention must preserve deduplication throughout the maximum redelivery window; erasure cannot release unresolved reservations or prove external quiescence. - Recording retention and purge jobs. +- The hand-offs of Phase 03's subject data requests + ([ADR-0106](../decisions/0106-subject-data-requests-authority-and-status.md), + [ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) §§ 6, 7 + and 10): the data of an `unserved_group` (a participant group whose tenant or + organization did not allow ordinary work when a global closure finished) and + whole-tenant offboarding; closure of a person with no Membership, of a person past the + closure's bounds (more than 256 participant groups or 256 Memberships in one tenant) + and of a person whose provider identifier the account-removal client refuses; the + retained classes no subject-keyed count reaches (transport and execution evidence, the + idempotency cache, external copies and the invitation e-mail envelopes); the purge of + expired export artifacts; the backlog gauge and alert rules for an erasure that waits + more than 30 days for its operator step; production provisioning of the + `learnstack-account-removal` realm client and retention of the identity provider's + admin events. Phase 03 ships the writers and their runbooks; this phase owns the + production operation and the first request that triggers each item. - `audit_log` retention and partition lifecycle — see **Demand-gated building blocks** above; the jobs and their cadence are specified by [ADR-0028](../decisions/0028-audit-log-partition-management.md). Per-tenant retention diff --git a/docs/runbooks/README.md b/docs/runbooks/README.md index fe0343dec..dfc104595 100644 --- a/docs/runbooks/README.md +++ b/docs/runbooks/README.md @@ -14,3 +14,7 @@ begins this directory with the platform operator runbooks; | [Identity issuer rebind](identity-issuer-rebind.md) | The tenant identity provider keeps its realm and users but changes address, and the stored issuer must follow without re-keying anyone | | [Operator recovery](operator-recovery.md) | An event or delivery is dead-lettered, a job is quarantined, and an operator must inspect it or reset one delivery or outbox row under a fence | | [Federation operator](federation-operator.md) | A tenant's identity-provider broker is orphaned, unreadable or nonconforming, and an operator must report it, remove it or disable it, and an account review is owed | +| [Data erasure](data-erasure.md) | A tenant erasure awaits its privileged step and an operator must redact the person's audit rows and complete it, or a data request is overdue, stuck or has an unpurged artifact | +| [Data export](data-export.md) | The data export key ring must be rotated or a key was lost or exposed, an export request never finishes, a download hit a ticket bound or lost its last chunk, an expired artifact was not purged, the export definitions are being deployed, or a process dump was taken | +| [Account closure](account-closure.md) | A person's closure request is past its window and must be confirmed with them and begun, a Begin was refused or answered incomplete, or a begun closure must be finalized, its groups are pending or its provider step did not finish | +| [Account removal client](account-removal-client.md) | The credential that deletes a person's identity-provider account is being provisioned, verified or rotated, it may have leaked, or a closure's last step answered refused, unavailable or uncertain | diff --git a/docs/runbooks/account-closure.md b/docs/runbooks/account-closure.md new file mode 100644 index 000000000..2be2df3fc --- /dev/null +++ b/docs/runbooks/account-closure.md @@ -0,0 +1,537 @@ +# Account closure: Begin and Finalize + +How an operator closes one person's account across every tenant they belong to: the +confirmation with the person, the Begin that makes the account stop working and fans +the closure out to each of the person's groups, and the Finalize that finishes it. +Decided in +[ADR-0107 § 7](../decisions/0107-data-request-fulfillment-and-account-closure.md) and +§ 8. There is **no dashboard**: this is an API and this document. + +## What exists + +| Route | Does | Permission | +|---|---|---| +| `GET /api/platform/v1/data-requests` | Lists the requests that need an operator, closures included (the [inspection](data-erasure.md#inspect)) | `platform.data_request.read` | +| `POST /api/platform/v1/data-requests/{requestId}/begin-closure` | Fences the person, judges the closure, makes the account Closing and fans the closure out (a **Begin**) | `platform.data_request.write` | +| `POST /api/platform/v1/data-requests/{requestId}/finalize-closure` | Redacts the person's audit rows, deletes their identity-provider account, makes the account Closed and completes every request of the closure (a **Finalize**) | `platform.data_request.write` | + +Authentication, the token profile and how a grant is given are in +[Platform operator access](operator-access.md). The served operator document, +`platform-v1`, is the contract for these routes, and it is the only client there is. + +Begin runs on `ConnectionStrings:PlatformAdmin` and needs the Identity migrations up to +`20261123130000_harden_closure_request_guard` applied: without +`20261123100000_admit_account_closure` the platform role cannot read the person's +Memberships, and the act fails with a permission error, a `500` named in the API's log. +Its fan-out runs on the application role, as each group's own act, and needs +`ConnectionStrings:Default`. A host with no fan-out registered refuses every Begin with +a `500` before it enters the platform scope, so nothing changes. Begin also asks the +[account removal client](account-removal-client.md) whether it could ever delete the +person's identity-provider account: with no client secret configured, or for a provider +identifier the client refuses, a Begin of a closure that has not begun is refused on +`errors.provider` before anything changes (a repeat of a begun closure resumes and +asks nothing). Finalize runs on the same credential and migrations, and deletes the +account through that client. + +## What the person already did + +The person filed the closure themselves, from one of their groups, its originating +group: through their session or the retained entry. No administrator files, reads or +cancels a closure. The request is `scheduled` with an `executeAt` 24 hours after it +was filed, its earliest Begin. The person may cancel it until a Begin commits, also +after `executeAt`. While the account is Active the person reads the request's receipt, +which shows `lastRefusal` when a Begin was refused; once a Begin commits the account +admits no session, and no in-product status remains +([Identity module](../modules/identity/README.md#account-closure-filing-p03-10-step-3)). + +## What is not here + +- **A closure of a person with no Membership.** They hold no tenant data and cannot + file one; + [Phase 11](../roadmap/phase-11-production-hardening.md) data operations own them. +- **A closure of a person past its bounds.** One closure is admitted for at most 256 + participant groups, served or not, and at most 256 Memberships of any status, Revoked + ones included, in one participant tenant. Begin refuses a person past either with + `409` on `errors.participants` while their account is still Active, and nothing + changes; + [Phase 11](../roadmap/phase-11-production-hardening.md) data operations serve them. +- **Undoing a closure.** Once a Begin commits, the account is Closing and nothing + returns it to Active: no route, no repeat, no database change. A person who changes + their mind needs a new account. +- **A fan-out route.** The per-group fan-out is an act Begin performs; repeat Begin to + repeat it. +- **The data of a group whose tenant is suspended or archived, or whose organization is + not Active** (an `unserved_group`). No fan-out runs there; the data stays and is + reported, and [Phase 11](../roadmap/phase-11-production-hardening.md) offboarding + owns it. +- **A read of one request.** As in [data erasure](data-erasure.md#what-is-not-here), + the lists are oldest due first and cannot be filtered by tenant or person. +- **Restoring a deleted account.** Once Finalize's provider step deleted the person's + identity-provider account, nothing here recreates it. +- **Two delayed consumers that do not read the account's status.** Between a Begin and + the erasure job of a group, an invitation e-mail the person issued in that group may + still be sent (the job then revokes the invitation, and its acceptance is refused), + and an export the person filed before the Begin may still store its artifact (the job + then withdraws it). You need do nothing: the group's erasure job ends both. Closing + them needs a read of the person's account status in those two jobs, which + [Phase 03](../roadmap/phase-03-identity-admin.md) owns. +- **Three records this closure leaves as they are.** An administrator who files an + export or an erasure for a closed person's Revoked Membership is refused with `409` + `lockey_subject_not_admitted`, and the refusal's row in that tenant names the + person's identifiers, written after the closure's redaction. A person's or an + administrator's own erasure in an unserved group whose job finished between Finalize's + two transactions is completed with the others, and the rows its job wrote then are + not redacted. An unserved group's tenant has its audit rows redacted by Finalize with + no row of its own saying so: the intent row under the platform sentinel lists each + tenant redacted, up to 200, and your ticket holds the rest. + +## When to look + +- At least once a day: a closure not `completed` 30 days after it was filed is a defect + ([ADR-0106 § 12](../decisions/0106-subject-data-requests-authority-and-status.md)), + and the window takes the first day. +- `overdue_scheduled` lists every request still `scheduled` once its window ended, + closures (`kind` `closure`) among them: each is a closure waiting for your Begin. +- `stuck_fulfilling` lists a begun closure still `fulfilling` two hours after its + `executeAt`, which every closure is until its Finalize, so a begun closure listed + there is no escalation by itself, and a closure's fan-out erasure still running two + hours after it was created. Repeat the closure's Begin to see where its groups stand. +- `awaiting_privileged_step` lists each fan-out erasure (`origin` `closure_fanout`) + whose group finished; only its closure's Finalize completes it. + +## Before you begin + +1. **You hold `platform.data_request.write`** and a token with a second factor, as for + an erasure completion. The read and the write are separate grants. +2. **The account removal client is configured** in this deployment and passes + [its verification](account-removal-client.md#verify-the-confined-client). Without it + a first Begin is refused on `errors.provider` and nothing changes, because no + Finalize could delete the account. +3. **Confirm the request with the person** through the e-mail address the identity + provider holds for them, before the first Begin of the closure. A repeated Begin of a + closure that began needs none, and the query below returns no row for it. This is the + control a hijacked session cannot supply: a session can file a closure, and only the + mailbox's owner answers you. LearnStack stores no e-mail address, so read it in the + realm console: + 1. A database administrator holding the `learnstack_platform` credential reads the + person's provider subject, the identity provider's own user identifier, for the + request. The role's column grants cover exactly these columns. + + ```sql + -- as learnstack_platform + SELECT u.provider_subject + FROM data_subject_requests AS r JOIN users AS u ON u.id = r.subject_user_id + WHERE r.id = '' AND r.kind = 'closure' AND r.status = 'scheduled'; + ``` + + 2. In the realm console of the tenant realm, open **Users**, type `id:` immediately + followed by that identifier into the search box (a bare identifier finds + nothing), and read the user's e-mail address there. The console also opens the + user directly at + `/admin/master/console/#/learnstack/users//settings`. + 3. Write to that address, name the closure's request identifier and its + consequences (the account stops working at once, for every tenant, and cannot be + reopened), and wait for the person's explicit answer from that address. + + Write the provider subject and the address nowhere: not in a ticket, not in the + Begin's ticket, not in a log. If the person does not confirm, do not begin; they may + cancel the request themselves while their account is Active. +4. **Send a ticket** for the act whenever your change process has one, 1 to 64 letters, + digits or `.` `_` `:` `/` `#` `-`. It is recorded on the scope's entry row and on + the Begin's result row, both under the platform sentinel, which no tenant reads. + +## Begin + +```sh +curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ + "$API/api/platform/v1/data-requests/$REQUEST/begin-closure" -d '{"ticket":"CHG-123"}' +``` + +The body is `{}` or `{"ticket":"..."}`. In order: + +1. The platform scope is entered: its entry row, under the platform sentinel with the + reason `closure_begin`, your attribution and your ticket, commits first and stays + whatever happens next. +2. The request is read. An absent request, one that is not a closure, a closure that + is `completed` or `cancelled`, and one whose person is already Closed are refused, + and nothing else is written. +3. A closure already `fulfilling` was begun earlier: skip to step 9. +4. **Could it ever finish.** The account removal client is asked, with the person's + provider identifier and without any call to the provider, whether it could delete the + account. If it could not, the act answers `409` on `errors.provider` and writes + nothing more; the request records no code, because the repair is yours. +5. **The fences**, on one transaction: the person's User fence, then the participant + groups read under it (every tenant and organization, or none, in which the person + holds a Membership of any status, a Revoked one included) with the Memberships the + person holds in each, then the fence of every participant tenant, in a fixed order. + A person in more than 256 participant groups, or with more than 256 Memberships in + one participant tenant, is refused before any tenant fence, with `409` on + `errors.participants` and nothing more written: no later step of the closure could + finish for them. Each fence waits at most three seconds for another act that holds + it. While they are held, every Membership, invitation and data request write of the + person, and every identity write in those tenants, waits. +6. The request is locked and read again, with the person's account status: what step 2 + read may have changed while the fences were awaited. +7. **The judgment**, the first refusal standing: + - `blocked_window`: the request's `executeAt` has not come, by the database clock. + - `blocked_hold`: a hold source reports a hold for the closure. No hold source exists + yet; [Phase 09](../roadmap/phase-09-billing-integrations-analytics.md) owns the + first. + - `blocked_last_administrator`: the person is the only eligible tenant-wide + administrator (an Active account with an Active tenant-wide administrator + Membership) of a participant tenant that allows ordinary work (`Trial` or + `Active`). A tenant that is suspended or archived is not judged. + + A refusal is recorded on the request as its `last_refusal`, with a result row; the + account is untouched and the request stays `scheduled`. A refusal for the code + already standing writes nothing more. +8. **The transition**: the account moves from Active to Closing, and the request from + `scheduled` to `fulfilling`. If the account is already Closing, because another of + the person's closures began, only the request moves. The result row, + `platform.closure.begin`, is written under the platform sentinel with your ticket, + `before_state` `{"status":"scheduled","account":"active"}` and `after_state` with + the status, `"account":"closing"` and the counts of served and unserved groups; no + person and no tenant is named. All of it commits together, and the fences end with + that commit. +9. **The fan-out**, after the commit: each served group, one tenant with one + organization or none, whose tenant allows ordinary work and whose organization is + Active, gets its own act in its own transaction, admitted for you by the gate with + the same key and ticket. It creates the group's erasure (`origin` + `closure_fanout`, born `fulfilling`, with no window) and enqueues its job, or adopts + the erasure the group already has in flight. Each group's act writes its own MUST + rows in its own tenant, which is that tenant's evidence of the closure. + +The database checks every part of step 8 itself: it admits the account's move only from +the platform role, only Active to Closing, and only with the person's fence and every +participant tenant's fence held by the moving connection; and the request's move only +after its `executeAt`, for a Closing person, under the same fences. + +## Answers + +| Answer | Meaning | +|---|---| +| `200`, `outcome: begun`, `complete: true` | This call made the account Closing, and every served group's erasure was started or adopted | +| `200`, `outcome: resumed`, `complete: true` | The closure had begun (by an earlier call, or the account was already Closing for another closure of the person), and every served group is started or adopted | +| `200`, `complete: false` | The Begin stands, and some served group is `waiting` or `failed`: see [A partial answer](#a-partial-answer) | +| `404` | No request has that identifier, or the identifier is not a UUID at all (the route does not match) | +| `409`, `errors.refusal` = `lockey_data_request_closure_refused` | The closure was refused; `params.cause` is the code now recorded on the request: `blocked_window`, `blocked_hold` or `blocked_last_administrator`. Nothing else changed. See [A refused Begin](#a-refused-begin) | +| `409`, `errors.kind` = `lockey_data_request_not_closure` | The request is an export or an erasure. Nothing changed | +| `409`, `errors.status` = `lockey_data_request_closure_not_beginnable` | The closure is `completed` or `cancelled`; `params.cause` is its stored status. Nothing changed | +| `409`, `errors.account` = `lockey_data_request_closure_account_closed` | The person's account is already Closed by an earlier closure. Nothing changed | +| `409`, `errors.participants` = `lockey_data_request_closure_too_large` | The person is in more than 256 participant groups, served or not, or holds more than 256 Memberships in one participant tenant. Nothing changed, no code was recorded, and the account stays Active. See [A refused Begin](#a-refused-begin) | +| `409`, `errors.provider` = `lockey_account_removal_unavailable` | The account removal client is not configured, or would refuse the person's provider identifier, so no Finalize could delete the account. Nothing changed, no code was recorded, and the account stays Active. See [A refused Begin](#a-refused-begin) | +| `400` | The request identifier is a UUID but not a UUIDv7 (or is the nil or the sentinel identifier), or the body or the ticket is malformed | +| `401`, `403`, `413`, `415`, `429` | As in [operator recovery](operator-recovery.md#act): the credential, the grant (`platform.data_request.write`), the body size or type, or the request budget | +| `503`, `audit_unavailable` | The entry row or the result row could not be written: no effect of the act committed. Retry after the delay; error line 7105 is in the API's log | +| `503`, `dependency_unavailable` | Another act held one of the person's fences for more than three seconds (a running erasure job of the person, a Membership change in one of their tenants), or the database could not be reached. Nothing committed; retry after the delay. The cause is in the API's log (warning 7110) | +| `503`, `dependency_unavailable` with `errors.outcome` = `lockey_outcome_unknown` | The commit was sent and its answer was lost. It **may have landed**: see [An unknown outcome](#an-unknown-outcome) | +| `500` | An unexpected failure or a deployment defect: no fan-out registered, or a missing grant or migration. The API's log names it. Nothing committed beyond the entry row, and a host with no fan-out writes not even that | + +The answer's `groups` carries closed counts and never an identifier: `served`, +`started`, `adopted`, `waiting`, `failed` and `unserved`. `correlationId` is on every +row the act and its fan-out wrote. + +## A refused Begin + +The request stays `scheduled` with its code, which the person sees on their receipt as +`lastRefusal` while their account is Active. Tell the person through the address you +confirmed against: + +- `blocked_window`: the 24 hours have not passed. Begin again after `executeAt`. +- `blocked_last_administrator`: the person is the last administrator of a tenant that + is in use. They hand the administration over in that tenant first (another person's + administrator Membership, admitted by the tenant), then you begin again. You learn + neither the tenant nor its other members from the answer; the person knows which + tenants they administer. +- `blocked_hold`: something the platform must keep holds the closure. Escalate it. + +A refused Begin is repeated as it is: the request is judged again, and a refusal for a +different reason replaces the recorded code. + +Two refusals record nothing on the request, because neither is the person's to act on, +and the account stays Active: + +- `errors.participants`: the person is in more participant groups, or holds more + Memberships in one participant tenant, than one closure is admitted for. Do not + repeat it: escalate it to the deployment's owner with the request identifier; + [Phase 11](../roadmap/phase-11-production-hardening.md) data operations serve such a + person. +- `errors.provider`: the account removal client is not configured, or it would refuse + the person's provider identifier because the identifier is not in the canonical form + the provider issues (an imported user's, say). Configure and verify the client by + [its runbook](account-removal-client.md#verify-the-confined-client) and Begin again. A + configured client that still refuses is an escalation to the deployment's owner: no + Finalize could delete that account. + +## A partial answer + +`complete: false` means the account is Closing and the request `fulfilling`, so the +closure stands and cannot be cancelled, and some served group is not yet started: + +- `failed`: that group's act did not report a start or an adoption (its tenant changed + its lifecycle, a fence was busy, the gate refused you, or the act failed). Repeat + Begin: it judges nothing again, takes no fence on the platform connection, and runs + the fan-out again, which adopts what started and retries the rest. Why a group failed + is in the API's log, never in the answer: warning 7542 names the closed refusal key or + the exception type, and information 7541 each group that finished. Attach the 7542 + lines to an escalation. +- `waiting`: the group has an erasure the person or an administrator filed whose window + has ended and whose job has not run. Repeat Begin once that job has run; the + [erasure runbook](data-erasure.md#inspect) shows its request under + `overdue_scheduled` meanwhile. + +Repeat until `complete: true`. A served group's erasure then runs its job in that +group and ends `awaiting_privileged_step`, after which the closure is finalized. + +## An unknown outcome + +Repeat the same Begin. If the first landed, the repeat answers `200 resumed` and runs +the fan-out, which the first never reached; if it did not, nothing of it committed and +the repeat begins the closure now. A client that never received an answer (a timeout, +a gateway error) is in the same position: repeat it. + +## How long it takes + +A Begin's transaction takes milliseconds when no other act holds a fence; each fence +waits up to three seconds and then answers `503`. While it is open, other identity +writes in the person's tenants wait for it. The fan-out then runs one act per served +group in turn, each a short transaction, and does not wait for the erasure jobs it +enqueues. + +A Finalize's first transaction lasts as long as its redaction: one pass over each +participant tenant's audit rows, about as long as +[an erasure's](data-erasure.md#how-long-it-takes) over the same tenant and up to about +twice that where the person holds hundreds of Memberships, and one over the platform +sentinel tenant's, a few seconds for 1.5 million global creation rows. It holds +the person's User fence only, so the person's own identity writes wait and no tenant's +do. The second transaction takes milliseconds under every fence. A client or gateway +timeout shorter than the first transaction rolls it back on every attempt, so run a +Finalize from a client whose timeout outlasts it; the API sets no request timeout of its +own. Once the first transaction committed, a repeat's redaction finds nothing left to +change and takes the time of a read. + +## When to finalize + +Finalize once every required group's erasure has run: the Begin answered +`complete: true` (or a repeat did), and each group's erasure job has finished, so that +group's newest erasure of the person awaits its privileged step, or completed after the +Begin through an [erasure completion](data-erasure.md#complete-an-erasure). The groups' +erasures, `origin` `closure_fanout` or the person's own adopted one, appear under +`awaiting_privileged_step` in the [inspection](data-erasure.md#inspect). You need not +check them one by one: a Finalize before they are ready answers `409` on `errors.groups` +and changes nothing. Every served group is required. An unserved group needs no erasure, +unless its group stopped allowing ordinary work after the Begin while its fan-out +erasure was still running: that erasure stays required until its job reaches the +privileged step, because nothing completes it once the account is Closed. Such a +closure stays pending while the group's tenant or organization does not allow work; +escalate it to the deployment's owner. + +A required group is not ready while its newest erasure is still `scheduled` or +`fulfilling`, failed or was cancelled, completed before this closure began (the person +was admitted to the group again since), or does not hold every Membership the person has +in the group. Each is repaired by a repeated Begin, whose fan-out starts a new erasure +or re-queues a dead job, followed by that group's job. A person's own erasure that +awaits its privileged step but holds fewer Memberships than the person has in the group +is adopted as it is by the fan-out. The `409` names no group, and the inspection cannot +be filtered by person, so complete every due erasure of `origin` `self` or +`administrator` listed under `awaiting_privileged_step` through the +[erasure completion](data-erasure.md#complete-an-erasure), which is your routine duty +anyway, then repeat Begin: its fan-out replaces a completed short erasure with a +fan-out of the whole group. + +## Finalize + +```sh +curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ + "$API/api/platform/v1/data-requests/$REQUEST/finalize-closure" -d '{"ticket":"CHG-9"}' +``` + +The body is `{}` or `{"ticket":"..."}`. In order: + +1. The platform scope is entered: its entry row, under the platform sentinel with the + reason `closure_finalize`, your attribution and your ticket, commits first. +2. The request is read. An absent request, one that is not a closure, a closure never + begun (`scheduled`) or cancelled are refused, and nothing else is written. A closure + already `completed` whose person is Closed answers `200 already_finalized` with what + it recorded, and writes nothing more. +3. **The first transaction.** The person's User fence alone (it waits at most three + seconds) and the participant groups read under it; the request locked and read again + with the person's account; and every required group's readiness. A group not ready + refuses the act with nothing written. No participant tenant's fence is taken: this + transaction changes no account and no request, so the tenants' identity writes do + not wait for its redaction. +4. **The redaction**, on that transaction: the person's audit rows in every participant + tenant, served or not, by the person and every Membership they hold there, then in + the platform sentinel tenant by the person's subject key + ([ADR-0108](../decisions/0108-privileged-audit-redaction.md) § 4). The intent row, + `platform.closure.finalize_attempt`, is written under the sentinel with your ticket + and the summed counts, and commits with the redaction. The fence ends there. +5. **The provider** deletes the person's account through the + [account removal client](account-removal-client.md). A missing account is success. + Nothing is held in the database while it runs. +6. **The second transaction.** The person's User fence and every participant tenant's + fence, as Begin takes them, and everything judged again under them. The account + moves from Closing to Closed and its raw provider subject is removed; every + participant group's erasure that awaits its privileged step is locked and completed + with its tenant's retained audit counts, unless an + [erasure completion](data-erasure.md#complete-an-erasure) finished it meanwhile, + which leaves it as it completed; this closure and every other open + closure of the person, begun or not, are completed with the summed audit counts and + the number of unserved groups; and the result row, `platform.closure.finalize`, is + written under the sentinel with your ticket and closed counts. All of it commits + together. + +The database checks every part of step 6 itself: it admits the account's move to +Closed only from the platform role, only from Closing, only with the raw subject +removed, and only with the person's fence and every participant tenant's fence held by +the moving connection; a closure's completion only for a Closed person under the same +fences; and a fan-out erasure's completion only for a Closing or Closed person under the +person's fence and its own tenant's. A person's or an administrator's own erasure is +completed through the erasure completion's arm, which constrains only its result. + +## Answers to a Finalize + +| Answer | Meaning | +|---|---| +| `200`, `outcome: finalized` | This call finished the closure: see [Reading the result](#reading-the-result) | +| `200`, `outcome: already_finalized` | An earlier call finished it. `retained` is what it recorded. Nothing was written but the entry row, unless this call found the finalization only after its own provider step, when it also wrote its intent row and a result row saying so | +| `404` | No request has that identifier, or the identifier is not a UUID at all | +| `409`, `errors.kind` = `lockey_data_request_not_closure` | The request is an export or an erasure. Nothing changed | +| `409`, `errors.status` = `lockey_data_request_closure_not_finalizable` | The closure was never begun (`scheduled`) or was cancelled; `params.cause` is its stored status. Begin it first, or, once another closure of the person is finalized, it is completed with that one | +| `409`, `errors.groups` = `lockey_data_request_closure_groups_pending` | A required group is not ready: see [When to finalize](#when-to-finalize). `params` holds the closed counts `served`, `ready`, `pending` and `unserved`, and no group is named; `ready` and `pending` count the required groups | +| `400` | The request identifier is a UUID but not a UUIDv7 (or is the nil or the sentinel identifier), or the body or the ticket is malformed | +| `401`, `403`, `413`, `415`, `429` | As in [operator recovery](operator-recovery.md#act) | +| `503`, `audit_unavailable` | The entry row or the intent row could not be written: the provider was not asked, and nothing of the closure changed. Retry after the delay; error line 7105 is in the API's log | +| `503`, `dependency_unavailable` | Another act held one of the person's fences for more than three seconds, the database could not be reached, or the result row of the second transaction could not be written after the provider step. Nothing of the closure's state changed, but after the provider step the person's identity-provider account may already be deleted. A redaction that had committed with its intent row is repeated harmlessly, and a repeat that finds the account absent finishes the closure. Retry after the delay; warning 7110 is in the API's log | +| `503`, `dependency_unavailable` with `errors.provider` | The provider did not delete the account: see [When the provider step does not finish](#when-the-provider-step-does-not-finish) | +| `503`, `dependency_unavailable` with `errors.outcome` = `lockey_outcome_unknown` | The final commit was sent and its answer was lost: see [An unknown outcome of a Finalize](#an-unknown-outcome-of-a-finalize) | +| `500` | An unexpected failure or a deployment defect (a missing grant or migration, a state no admitted path writes, which error line 7122 names without the person: a person past the closure's bounds, which Begin refuses, is `participants_beyond_bound` or `redaction_plan_refused`). Nothing of the closure changed since its last commit | + +## When the provider step does not finish + +The redaction and its intent row committed, a result row records where the act stopped, +the closure stays `fulfilling` and the account Closing: the person is already locked out +everywhere. `errors.provider` names the provider's closed answer, and warning 7121 the +same in the API's log: + +- `lockey_provider_refused`: nothing was deleted. Begin admits only a closure the + client could delete, so the client's configuration has changed since the Begin (the + secret removed or wrong, the client disabled or broadened, the admin address + blocked); there is nothing to delete by hand. Repair the client by + [its runbook](account-removal-client.md#when-a-closures-last-step-does-not-finish) and + repeat. +- `lockey_provider_unavailable`: no deletion was confirmed; the provider was + unreachable or busy. Repeat after the delay: a deletion that had landed is found + absent. +- `lockey_provider_outcome_unknown`: the deletion was sent and its answer was lost, so + the account may be gone. Repeat: a deleted account is found absent, which is success. + +Every repeat redacts again, which changes no row, writes an intent row of its own and +asks the provider again. + +## An unknown outcome of a Finalize + +Repeat the same Finalize. If the second transaction had landed, the repeat answers +`200 already_finalized` and asks the provider nothing; if it had not, the repeat +redacts again (a no-op), finds the account absent at the provider and finishes. A +client that never received an answer is in the same position. + +## Reading the result + +The answer of a finalization carries closed counts and no person: + +- `groups`: `served`, `ready` and `pending` (zero), which count the required groups, an + unserved group whose fan-out erasure was still open included, `unserved`, + `erasuresCompleted` (the erasures this call completed, not one an erasure completion + finished meanwhile) and `closuresCompleted` (this closure and every other open one of + the person). +- `unservedGroups`: each unserved group by `tenantId` and `organizationId`. Their data + stays and is reported; [Phase 11](../roadmap/phase-11-production-hardening.md) + offboarding owns it. Their tenants' audit rows were redacted all the same, with no row + in those tenants saying so: record the list on your ticket. +- `redaction`: this call's passes summed: the participant `tenants` redacted, the + `rowsSelected`, the rows changed per column (zero on a repeat, whose earlier attempt's + intent row holds the counts that changed rows) and the retained references per kind. +- `retained`: the closure request's recorded result: the audit log's retained kinds + summed over every pass, and `unserved_group`. + +What remains of the person is the tombstone: the `users` row with its identifier, its +subject key, its authority and its creation evidence, Closed and with no raw provider +subject; each served group's Revoked Membership; the requests as receipts; and in the +audit log the actor and entity identifiers and all of `metadata`, which stay linkable +through the subject key and are never called anonymous +([ADR-0108](../decisions/0108-privileged-audit-redaction.md) § 6). The person has no +in-product status: confirm the completion to them through the address you confirmed the +request against. + +**A second closure.** A person may have filed a closure in more than one group. Begin +any one of them; Finalize of the one you began completes every other open closure of +the person with it, also one never begun or still in its window. A second closure that +is `fulfilling` because you began it too may be finalized instead; the first is then +completed with it. Finalizing a closure that was never begun answers `409` on +`errors.status`. + +## Targets and escalation + +- Begin every confirmed closure soon after its `executeAt`, and finalize it well inside + the 30 days of + [ADR-0106 § 12](../decisions/0106-subject-data-requests-authority-and-status.md); + the count starts when the request was filed. +- A Finalize that keeps answering `errors.provider` = `lockey_provider_refused` after + the client was checked, one that still answers `lockey_provider_unavailable` or + `lockey_provider_outcome_unknown` a day after its first such answer, and a group that + stays pending over several repeated Begins and jobs, an unserved one whose fan-out + erasure is still open included, are escalations to the deployment's owner, with the + request identifier and the `correlationId` of each call. +- A Begin refused on `errors.participants`, and one refused on `errors.provider` while + the client passes its verification, are escalations to the deployment's owner with + the request identifier. +- A Begin that keeps answering `503` or `500`, a group that stays `failed` over several + repeats (attach its warning 7542 lines), and a closure listed under `stuck_fulfilling` + whose groups are all started but whose erasures do not finish are escalations to the + deployment's owner, with the request identifier and the `correlationId` of each call. +- Never change a User, a Membership or a request by hand. The database refuses the + closure's changes without the fences, and a change outside the acts writes no record. + +## Signals + +`learnstack_platform_operator_admissions_total{outcome,operation}` counts the acts +admitted or refused at the gate, with `operation` `platform.closure.begin`, and each +group's fan-out act under its own operation; +`learnstack_platform_operator_results_total{operation="platform.closure.begin"}` counts +the Begins that committed a change, a recorded refusal included, and a resume that +changed nothing is not one; +`learnstack_platform_operator_data_requests_total{operation,outcome}`, with +`operation` `platform.closure.begin`, counts every call that reached the owner by how +it ended: `begun`, `begun_partial`, `resumed`, `resumed_partial`, `blocked_window`, +`blocked_hold`, `blocked_last_administrator`, `refused_too_large`, `refused_provider`, +`not_found`, `not_closure`, `not_beginnable`, `account_closed`, `audit_unavailable`, +`unavailable`, `commit_unknown` and `failed` (an unexpected failure, answered `500`). A +`*_partial` outcome is a Begin that owes a repeat. With `operation` +`identity.data_request.fan_out_closure` the same counter counts each group's fan-out act +by its outcome: `fan_out_started`, `fan_out_adopted`, `fan_out_waiting` and +`fan_out_failed`; information 7541 logs each group that finished and warning 7542 each +that failed, with the closed refusal key or the exception type and never the person, the +group or the ticket. A fan-out that threw after its Begin committed logs error line +7120. With `operation` `platform.closure.finalize` the same counter's +outcomes are `finalized`, `already_finalized`, `not_found`, `not_closure`, +`not_finalizable`, `groups_pending`, `provider_refused`, `provider_unavailable`, +`provider_uncertain`, `audit_unavailable`, `unavailable`, `commit_unknown` and `failed`; +`learnstack_platform_operator_results_total{operation="platform.closure.finalize"}` +counts the Finalize transactions that committed a result row, a stop at the provider +included. A Finalize logs warning 7121 when it stops at the provider, warning 7124 when +the provider port threw (its exception's type only), warning 7125 when the account +removal adapter refused the deletion (a closed reason code; see its +[runbook](account-removal-client.md#when-a-closures-last-step-does-not-finish)), error +7122 for a state no admitted +path writes, and critical 7123 when a stop's result row could not be written; none names +the person, a tenant or the ticket. The admission and refusal counters are in +[Platform operator access](operator-access.md#signals). + +## Not recoverable here + +- An account that is Closing or Closed: it never returns to Active. +- An identity-provider account Finalize deleted. +- The data of an unserved group, until + [Phase 11](../roadmap/phase-11-production-hardening.md) offboarding. +- A dashboard. diff --git a/docs/runbooks/account-removal-client.md b/docs/runbooks/account-removal-client.md new file mode 100644 index 000000000..405cfbe5d --- /dev/null +++ b/docs/runbooks/account-removal-client.md @@ -0,0 +1,232 @@ +# Account removal client: the confined deletion credential + +How an operator provisions, verifies, rotates and, after a leak, contains the one +credential that can delete a person's identity-provider account: the realm client the +closing step of a global account closure uses. Decided in +[ADR-0107 § 7](../decisions/0107-data-request-fulfillment-and-account-closure.md). The +closure's own steps and their operator routes are in +[Data erasure](data-erasure.md) and the [closure runbook](account-closure.md); this +document is about the credential. There is **no route of its own**: the credential is +used by one caller, the closure's Finalize, through one port method. + +## What exists + +| Item | Value | +|---|---| +| Port | `IIdentityProviderAccountRemoval`: `RemoveAsync` deletes the account whose provider subject is given; `CanRemove` is the pure check Begin asks before it moves anyone | +| Default | `RefusingIdentityProviderAccountRemoval`: every call answers refused, nothing is sent | +| Adapter | `KeycloakAccountRemoval`, selected when `AccountRemoval:ClientSecret` is configured | +| Realm client | `learnstack-account-removal` in the `learnstack` realm, role `realm-management/manage-users` only | +| Secret | `KEYCLOAK_ACCOUNT_REMOVAL_SECRET` in the realm's private source; the API reads the same value as `AccountRemoval__ClientSecret` | +| Calls | One token request, then `DELETE users/{id}` for a canonical lowercase UUID; nothing else | +| Resilience | `Resilience:accountRemoval`, fixed: no retry, 5-second call ceiling, breaker on, one call at a time | +| Log | One Warning, event 7125, per refusal, carrying one closed reason code ([below](#reading-a-refusal-in-the-log)) | + +The adapter refuses a malformed subject and a missing or unusable secret before any +request leaves the process, and a token wider than the role before the deletion is +sent. It never logs, audits or returns the subject or the secret, and a refusal logs +its reason code only. With no secret configured every first Begin is refused on +`errors.provider`, nothing changes and nothing reaches the provider. + +## What the credential can do + +**`manage-users` is not deletion-only.** It is a realm-wide role in the one realm every +tenant shares. A leaked secret lets its holder, in every tenant's realm: + +- **create** users and **update** them, including the profile attributes the realm + declares admin-editable (the identity attributes among them); +- **reset credentials**, and so sign in as anyone who has no second factor; +- **delete** any user, and so any person's account. + +The integration proof `AccountRemovalProviderTests` shows the create, update and +credential reset against the pinned provider rather than asserting them. Whether the +role also lists users was not exercised; assume it can. It does **not** reach +identity-provider brokers, clients, realm settings or authentication flows: the same +proof shows each answers `403`. + +The adapter confines what LearnStack sends: one deletion of one validated identifier. +It cannot confine what the credential could do if it leaves LearnStack. ADR-0107 § 7 +accepts that, with three mitigations: the secret store, rotation by this runbook and +the provider's own admin-event stream. The committed realm does not enable that stream, +and its retention is +[Phase 11](../roadmap/phase-11-production-hardening.md)'s; until then the review in +[Leak response](#leak-response) rests on the provider's own logs. + +**Fine-grained admin permissions are not relied on.** The pinned Keycloak image +(`26.7.5`, the digest in `infra/compose/dev.yml`) lists `admin-fine-grained-authz` at +versions `v1` and `v2` (read from `kc.sh start --help` on that image), and the +development compose file enables the feature. Keycloak's version 2 permissions grant +`manage` on a user set, and `manage` covers update as well as delete; there is no +deletion-only scope to adopt, and none was exercised here. The adapter therefore +holds `manage-users`. If a later pinned Keycloak exposes a scope that permits deletion +alone, ADR-0107 § 7 gains a dated amendment, and the realm client, the adapter's token +check and this section change together. + +## Provision it + +Development provisioning is the realm reconciler's: `make dev`, `make seed` and +`make demo` create the client when it is absent and verify it exactly when present. + +1. Add `KEYCLOAK_ACCOUNT_REMOVAL_SECRET` to the selected private source: 16 to 1,024 + bytes, not `**********`, not beginning `${`, and distinct from the web, admin, + event-reader and federation admin secrets. Add the same value as + `AccountRemoval__ClientSecret` for the API. +2. Start the provider. Compose refuses to start without the variable; the import + carries only the placeholder `${KEYCLOAK_ACCOUNT_REMOVAL_SECRET}`. +3. Run the reconciler. It refuses an existing client that differs (`secret_conflict`, + an extra role, scope or mapper) and never repairs or rotates one. + +A production realm is provisioned by Phase 11. Whatever provisions it creates the client +with exactly these properties, and nothing broader: + +- a confidential client with a service account, and **no** standard flow, implicit + flow, direct access grants, redirect URIs, web origins, default or optional client + scopes, and **full scope off**; +- one protocol mapper emitting `realm-management` client roles into the access token + only, as `resource_access.realm-management.roles`; +- the service account holding the single client role `realm-management/manage-users` + and no realm role, group or other client role, and that role as the client's only + scope allowance. + +Store the secret in the deployment's secret provider under `AccountRemoval:ClientSecret` +and set `Authentication:Tenant:Issuer` to the realm's issuer; the adapter reads both and +selects no other target. A configured secret with an issuer the adapter refuses (not +HTTPS, or not ending `/realms/learnstack`) stops the API from building the closure's +operations at all: Begin and Finalize both answer `500` and nothing changes. Fix the +issuer; do not clear the secret to get past it. + +## Verify the confined client + +The adapter refuses a token that is not exactly this client's, but check the client +yourself after provisioning and after any provider upgrade. Run the steps from the host +or network position the API uses for its own egress: the adapter reaches the issuer's +token endpoint and its admin address and nothing else, and a check from another network +may pass where the API is refused. `ISSUER` below is the value +of `Authentication:Tenant:Issuer`, and `ADMIN` is its admin address: +`ADMIN="${ISSUER%/realms/learnstack}/admin/realms/learnstack"`. + +1. In the realm console the client has service accounts on, every browser flow off, no + client scopes and full scope off. Its service account has one role mapping, + `manage-users`, and no group. +2. Put the secret in a file, never on the command line or in shell history, and without + a trailing newline: curl sends a file's newline as part of the value (`%0A`), and the + provider then refuses a correct secret. + + ```bash + umask 077 + printf 'Client secret: '; read -r -s SECRET; echo + printf %s "$SECRET" > account-removal.secret; unset SECRET + ``` + + Request a client-credentials token and read its claims: + + ```bash + TOKEN=$(curl --silent --data-urlencode grant_type=client_credentials \ + --data-urlencode client_id=learnstack-account-removal \ + --data-urlencode client_secret@account-removal.secret \ + "$ISSUER/protocol/openid-connect/token" | jq -r .access_token) + printf %s "$TOKEN" \ + | jq -R 'split(".")[1] | gsub("-"; "+") | gsub("_"; "/") | @base64d | fromjson + | {azp, realm_access, resource_access}' + ``` + + `azp` is `learnstack-account-removal`, `realm_access` is absent or has no roles, and + `resource_access` has one entry, `realm-management`, whose roles are exactly + `["manage-users"]`. Delete the secret file afterwards. +3. The token is refused for brokers and clients: + `GET $ADMIN/identity-provider/instances` and `GET $ADMIN/clients` with it answer + `403`. +4. The deletion route answers as the provider itself. Ask it to delete an identifier no + user has: + + ```bash + curl --silent --include --request DELETE --header "Authorization: Bearer $TOKEN" \ + "$ADMIN/users/$(uuidgen | tr 'A-Z' 'a-z')" + ``` + + The answer is `404` with `Content-Type: application/json` and the body + `{"error":"User not found"}` (read from the pinned Keycloak, `26.7.5`). A `401` or + `403` means the token or its role is wrong: repeat the steps above. Any other answer + (an HTML or empty page, other JSON) means a proxy or gateway in front of the provider + answers for it: fix that route before the first closure. The adapter refuses a `404` + that is not JSON (`delete_not_found_foreign`), but it cannot tell a gateway's JSON + `404` from the provider's own and would report the account absent. + +## Rotate it + +Rotate on schedule, on any suspicion, and whenever someone who held the value leaves. + +1. Generate the new value (same bounds as above). +2. Set it at the provider: regenerate or replace the client secret in the realm console. +3. Set the same value in the private realm source (`KEYCLOAK_ACCOUNT_REMOVAL_SECRET`), + the secret store and the API's `AccountRemoval__ClientSecret`, then restart the API. +4. Run the reconciler: it verifies the provider's secret equals the private source and + refuses with `secret_conflict` if they differ. It never rotates. + +Between steps 2 and 3 the provider refuses the old secret and every closure stops with +a refused answer. Nothing is lost: a closure's last step is repeated after rotation. + +## Leak response + +Treat a suspected leak of `AccountRemoval:ClientSecret` as a realm-wide credential +compromise. + +1. **Stop the credential.** Disable the client in the realm console (new tokens stop at + once). A token already issued works until it expires; the committed realm's access + token lifespan is 900 seconds. +2. **Rotate.** Follow [Rotate it](#rotate-it) with a new value, then re-enable. +3. **Review the realm.** From the last time you know the secret was held only by + LearnStack, list the users the client's service account created, updated, disabled, + deleted or gave a new credential, from the provider's admin events or its logs. + Treat every account whose credentials or profile attributes changed in that window + as compromised: reset its credentials and required actions, and check its identity + attributes against the LearnStack binding. +4. **Account for deletions.** A user the client deleted that no closure explains is a + data event: check the retained closure requests and the tenants' audit rows for the + subject, and report it under your incident process. +5. **Closures in flight** are unaffected by a rotation: repeat their last step. + +## When a closure's last step does not finish + +The closure's Finalize reports what the provider answered; the +[closure runbook](account-closure.md#when-the-provider-step-does-not-finish) says what +each answer does to the closure. The adapter's answers mean: + +| Answer | Meaning | What to do | +|---|---|---| +| refused | Nothing changed. The secret is missing, unusable or wrong; the client is disabled or broader than `manage-users`; the subject is not a provider user identifier; the provider answered `401`, `403` or another `4xx`; or a `404` came back that is not the provider's own JSON | Read the reason code in the API's log ([below](#reading-a-refusal-in-the-log)), fix that cause, then repeat the step. Repeating without a repair answers the same | +| unavailable | No deletion was confirmed: the provider was unreachable, it or a hop in front of it answered `5xx`, `429`, `408` or `425`, the breaker is open after repeated faults, or another deletion is in flight | Wait (the breaker closes after its break duration, 30 seconds by default) and repeat. A deletion that had landed is found absent, which is success | +| uncertain | The deletion may have happened and its answer was lost: a timeout, a connection that failed or broke while the deletion was being sent, or an answer that is not a deletion's | Look the person up in the realm console with the e-mail you confirmed the request against, then repeat the step. A repeat reports the account absent, which is success | + +There are no automatic retries by design: a repeat is the operator's, so a lost answer +is never hidden behind a quiet success. A missing account is success, but only the +provider's own answer counts: a `404` that is not JSON is a refusal, because a proxy +or gateway in front of the provider may be answering for it. + +### Reading a refusal in the log + +Every refusal writes one Warning, event 7125, `The account removal adapter refused the +deletion: `, with one of these closed codes. The line carries no subject, address, +secret or provider text. The closure's own line (warning 7121) follows it. + +| Code | Cause | What to do | +|---|---|---| +| `subject_shape` | The person's provider subject is not a lowercase hyphenated UUID, so no request is sent | Nothing in the realm or the secret changes this answer, and a hand deletion in the realm console does not either: the account cannot be deleted through LearnStack. Escalate to engineering | +| `secret_unusable` | `AccountRemoval:ClientSecret` is empty, blank, over 1,024 bytes, the mask literal or a `${` reference | Set it as in [Provision it](#provision-it), then restart the API | +| `token_refused` | The token endpoint answered `4xx` or a redirect: the secret is wrong, or the client is disabled | Compare the secret with the provider's ([Rotate it](#rotate-it)); enable the client | +| `token_malformed` | The token endpoint answered `200` but not a usable token response (not JSON, too large, no access token, not a JWT) | A proxy or a wrong `Authentication:Tenant:Issuer` is answering for the provider: check the address | +| `token_not_confined` | A usable token that is not exactly this client's: another issuer or client, a realm role, or roles other than `manage-users` | The client is misprovisioned: repeat [Verify the confined client](#verify-the-confined-client) and repair it | +| `delete_unauthorized` | The deletion answered `401` or `403` | The role is missing or the realm differs from the issuer's, or a proxy or firewall in front of the admin path refuses the API: repeat the verification from the API's network position | +| `delete_redirect` | The deletion answered a redirect, which is never followed | A proxy is redirecting the admin path: fix the route | +| `delete_rejected` | The deletion answered another `4xx` | Read the provider's own log for the cause | +| `delete_not_found_foreign` | The deletion answered `404` in a type other than JSON | A proxy or gateway hides the admin path: fix the route (verification step 4) | +| `unclassified` | A refusal that named no cause: a defect of the adapter | Report it with the log line | + +## What is not here + +- **Realm provisioning in production.** Phase 11 owns it; this document states the + properties it must produce. +- **The admin-event stream and its retention.** Phase 11 owns them; see above. +- **Reading or listing realm users from LearnStack.** The adapter reads and lists none; + the confirmation of a closure request against the provider's e-mail is yours, in the + realm console. diff --git a/docs/runbooks/data-erasure.md b/docs/runbooks/data-erasure.md new file mode 100644 index 000000000..38e099ca2 --- /dev/null +++ b/docs/runbooks/data-erasure.md @@ -0,0 +1,405 @@ +# Data erasure: the privileged step + +How an operator finds the data requests that need a person and completes an erasure: the +audit redaction only an operator may run, the request's completion and its record, in +one transaction. Decided in +[ADR-0107 § 8](../decisions/0107-data-request-fulfillment-and-account-closure.md) and +[ADR-0108](../decisions/0108-privileged-audit-redaction.md). There is **no dashboard**: +this is an API and this document. + +## What exists + +| Route | Does | Permission | +|---|---|---| +| `GET /api/platform/v1/data-requests` | Lists the requests and export artifacts that need an operator (an **inspection**) | `platform.data_request.read` | +| `POST /api/platform/v1/data-requests/{requestId}/complete-erasure` | Redacts the subject's audit rows and completes an erasure awaiting its privileged step (a **completion**) | `platform.data_request.write` | + +Authentication, the token profile and how a grant is given are in +[Platform operator access](operator-access.md). The served operator document, +`platform-v1`, is the contract for these routes, and it is the only client there is. + +Both run on `ConnectionStrings:PlatformAdmin` and need the Identity migration +`20261122200000_grant_platform_data_request_operations` applied; without it the +`expired_artifact` list fails with a permission error and a completion with the request +guard's refusal, both a `500` named in the API's log. The erasure job itself needs +`20261122203000_admit_erasure_profile_clearing`: without it the profile clearing raises +`P0304` and the job dies after its attempts. A completion also needs the Audit +module's redaction executor registered (`IAuditRedactor`): without one it answers `500`, +the log names the port, and nothing changes. + +## What the tenant side already did + +An erasure is filed for one scope group, by the person or by an administrator for a +Membership that is already Revoked, and waits its 24-hour cancellable window. A job in +that group then revokes the person's export artifacts and unstarted exports, erases the +Membership (its assignments removed, its profile cleared, a Revoked tombstone kept), +revokes the pending invitations the person issued, records what the group retains, and +leaves the request `awaiting_privileged_step` +([ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) § 5 and +§ 6). An administrator's erasure is filed only for a Membership that is already +Revoked, and that is checked when it is filed: if the person is admitted to the group +again during the 24 hours, the job still runs, and the person, who may cancel the +request in the window, is the safeguard. While it runs, the job holds the tenant's +identity fence exclusively, the Audit participant's counts included, so other +Membership, invitation and data-request writes in the tenant wait up to two seconds and +then answer `503` for a retry; the hold lasts seconds, and longer in a tenant with +millions of audit rows. What it cannot touch is the audit log: no tenant connection may +change an audit row, and `learnstack_platform` alone may update six of its columns. +That is the step left to you. + +## What is not here + +- **A global account closure** + ([ADR-0107 § 7](../decisions/0107-data-request-fulfillment-and-account-closure.md)). + Its acts are in [Account closure](account-closure.md), and these routes never act on + a `closure` request or on a closure's fan-out erasure: the completion refuses the + latter, which only its closure's Finalize completes. A person's own erasure that a + closure adopted can still be completed here; the closure's Finalize completes it with + the others if it still awaits its privileged step. The two delayed jobs that do not + read a closing person's status are listed in that runbook's + [What is not here](account-closure.md#what-is-not-here). +- **Cancelling or failing a request.** The person, or the administrator who filed it, + cancels within the window. A request `blocked`, `failed` or `cancelled` is terminal; + the person files a new one. +- **Anonymity.** The completion redacts what is not needed to say who did what. It never + makes the person anonymous: see [Reading the result](#reading-the-result). +- **A read of one request.** The lists are oldest due first and cannot be filtered by + tenant or person, so finding one request means paging; each page is one audited scope. + A request's identifier reaches you from the inspection or from the tenant, never with + the person's identity. +- **Undoing a redaction.** LearnStack keeps no copy of a redacted value; backups, WAL + archives and row versions awaiting vacuum can still hold one (see + [Not recoverable here](#not-recoverable-here)). + +## When to look + +- At least once a day: an erasure not `completed` 30 days after it was filed is a defect + ([ADR-0106 § 12](../decisions/0106-subject-data-requests-authority-and-status.md)), + and the window and the job take the first day. +- A person or a tenant asks why an erasure is not complete. +- `learnstack_job_failed_total` rises with a `job_name` of an + `identity.data_erasure_*` definition, `learnstack_job_oldest_eligible_age_seconds` or + `learnstack_job_state_count` shows an erasure job late or dead, or a quarantined + erasure job appears in the [operator recovery](operator-recovery.md) inspection. + Nothing alerts on the `awaiting_privileged_step` list itself: a person polls it, and + [Phase 11](../roadmap/phase-11-production-hardening.md) owns an automated gauge and + its alert rules. + +## Before you complete + +- You hold `platform.data_request.write` and a token with a second factor. The keys are + given through `PlatformOperator:Grants` and evaluated on every act + ([how a grant is given](operator-access.md#giving-and-withdrawing-a-grant)); they are + never assignable to a tenant role, and the shipped demo operator holds neither. The + read and the write are separate grants: an operator who may list may not complete. +- You may send a ticket for the act, 1 to 64 letters, digits or `.` `_` `:` `/` `#` `-`. + Send one whenever your change process has one: it is recorded on the scope's entry row + only. +- The request is listed under `awaiting_privileged_step`. You send nothing else: the + completion reads the person, the group, the request's origin and its frozen + Memberships from the request row itself, and never from the call. You do not learn, + and need not know, who the person is. + +## Inspect + +Each page is one entered platform scope, so each page writes one +`platform.admin_scope.enter` audit row with the reason `data_request_inspect`, your +attribution and your ticket. It does not say which list you read or how far you paged. +Pass the ticket as `?ticket=`, and percent-encode `#` as `%23`. + +```sh +curl -s -H "Authorization: Bearer $TOKEN" \ + "$API/api/platform/v1/data-requests?state=awaiting_privileged_step&limit=20&ticket=CHG-123" +``` + +| `state` | Lists | What to do | +|---|---|---| +| `awaiting_privileged_step` (default) | Erasures whose tenant side finished | [Complete](#complete-an-erasure) each whose `origin` is `self` or `administrator`. A `closure_fanout` item is completed only by its closure and answers `409` here | +| `overdue_scheduled` | Requests still `scheduled` once their window ended (`executeAt`), with no grace | Every erasure is listed here for the moments between the end of its window and its job's pickup. One still listed after a few minutes has a late or dead job. The [quarantined-jobs inspection](operator-recovery.md) shows only quarantined jobs, not one still retrying or out of attempts, so read the job table as [Data export § A stuck or dead export request](data-export.md#a-stuck-or-dead-export-request) does, with the definition keys `identity.data_erasure_tenant.v1` and `identity.data_erasure_organization.v1`. A dead job's request reads `failed` on the person's receipt and stays `scheduled` here until the person files again, which frees the slot and is the recovery: [tell them so](#when-a-person-asks) and escalate the job | +| `stuck_fulfilling` | Requests still `fulfilling` two hours after they fell due (`executeAt`, or `createdAt` when there is no window) | An erasure job commits `fulfilling` only together with `awaiting_privileged_step`, so a dead run rolls back to `scheduled` and is listed above, never here. This list holds a request that starts `fulfilling` and whose job then stopped half-way (a closure's fan-out, [ADR-0107 § 7](../decisions/0107-data-request-fulfillment-and-account-closure.md)). Two hours outlast the job runtime's whole retry schedule: find the job and escalate. A begun closure (`kind` `closure`) is also listed here until its Finalize, which is no escalation by itself: see [Account closure § When to look](account-closure.md#when-to-look) | +| `expired_artifact` | Export artifacts past `expiresAt` whose purge has not run | See [Data export § An expired artifact whose purge died](data-export.md#an-expired-artifact-whose-purge-died) | + +- `limit` is 1 to 100 (default 20; a larger value is clamped, and zero or less is + refused with `errors.limit`). An unknown `state` is refused with `errors.state` and a + malformed or foreign `cursor` with `errors.cursor`. Only `state`, `limit`, `cursor` + and `ticket` are accepted; any other parameter is refused with `errors.query` and + nothing is read. The + answer holds `items` and a `pageInfo` with `nextCursor` and `hasNext`; send + `nextCursor` back as `cursor`. A cursor belongs to the list that issued it. +- Each item carries `requestId`, `tenantId`, `organizationId` (null for the tenant-wide + group), `kind`, `origin`, `status`, `createdAt`, `executeAt`, `completedAt`, + `lastRefusal`, `failureReason`, and on `expired_artifact` the `artifact` + (`artifactId`, `status`, `expiresAt`). It never carries the person, the Memberships, a + requester, a progress record, a result or an artifact's content: the inspection + selects none of them, and the platform role holds no grant on the requester, the + actor stamps or the artifact's person, size or key. The completion reads the person, + the Memberships and the result of the one request it completes, because it needs + them, and never returns them. +- Items come oldest due first: by `executeAt`, or `createdAt` when there is no window, + then by request identifier; artifacts by `expiresAt`. + +## Complete an erasure + +```sh +curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \ + "$API/api/platform/v1/data-requests/$REQUEST/complete-erasure" -d '{"ticket":"CHG-123"}' +``` + +The body is `{}` or `{"ticket":"..."}`. In order, and in one transaction: + +1. The platform scope is entered: its entry row, under the platform sentinel with the + reason `erasure_complete`, your attribution and your ticket, commits first and stays + whatever happens next. +2. The request is locked and read whole. An absent request, one that is not an erasure, + a closure's fan-out erasure and one that is not awaiting its privileged step are + refused, and nothing else is written. A completed one answers its recorded result + (`already_completed`). +3. The redaction is planned from the row. A request the person filed selects the + person's audit rows across the whole tenant. A request an administrator filed selects + only the rows of its group's organization, or the rows with no organization for the + tenant-wide group, so an organization administrator's request never changes another + branch's record ([ADR-0108 § 4](../decisions/0108-privileged-audit-redaction.md)). +4. The audit rows are redacted by the Audit module's one executor: on every selected row + `ip_address`, `user_agent` and `actor_email` become NULL, and in `before_state`, + `after_state` and `changes` a value at a reference a module declares becomes + `***REDACTED***` when it is the person's identifier or one of the request's + Memberships. Another person's value at the same reference, such as an administrator + who updated the record, is left as it is. +5. The request moves to `completed`. The database stamps `completedAt` and the system + actor itself. The request's audit kinds are replaced by the redaction's exact counts + (the Audit participant's counts from before the act were a lower bound), and every + other kind stays as its participant recorded it. +6. The result row, `audit.redaction.apply`, is written in the **request's tenant**: no + actor, the reason `erasure_complete`, the correlation id, your attribution and **no + ticket**, `before_state` `{"status":"awaiting_privileged_step"}` and `after_state` + the closed report. +7. All of it commits together, or none of it does. + +| Answer | Meaning | +|---|---| +| `200`, `outcome: completed` | The act committed. `rowsSelected` and `redacted` (rows changed per column, every column listed) are the redaction's; `retained` is the request's whole recorded report, the audit log's kinds included; `completedAt` is the database's | +| `200`, `outcome: already_completed` | The request was already completed, by you or another operator. Its recorded `retained` and `completedAt` are returned, nothing was redacted and **no second result row** was written; `rowsSelected` and `redacted` are null, and the first act's counts are on its result row | +| `404` | No request has that identifier, or the identifier is not a UUID at all (the route does not match) | +| `409`, `errors.kind` = `lockey_data_request_not_erasure` | The request is an export or a closure. Nothing changed | +| `409`, `errors.origin` = `lockey_data_request_closure_fanout` | The erasure is a closure's fan-out, which only that closure's finalization completes. Nothing changed | +| `409`, `errors.status` = `lockey_data_request_not_awaiting_privileged_step` | The erasure is not awaiting its privileged step; `params.cause` is its stored status. `scheduled`: its window has not ended, or its job is late or dead (look at `overdue_scheduled`). `fulfilling`: a closure's fan-out still running or stopped (look at `stuck_fulfilling`). `blocked`, `failed`, `cancelled`: terminal, nothing is left to complete; the person files a new request. Nothing changed | +| `400` | The request identifier is a UUID but not a UUIDv7 (or is the nil or the sentinel identifier), or the body or the ticket is malformed. A refusal at the gate carries no per-field errors | +| `401`, `403`, `413`, `415`, `429` | As in [operator recovery](operator-recovery.md#act): the credential, the grant (`platform.data_request.write` for a completion, `platform.data_request.read` for a list), the body size or type, or the request budget | +| `503`, `audit_unavailable` | The entry row or the result row could not be written: no effect of the act committed (the entry row stays, or was never written). Retry after the delay; error line 7105 is in the API's log | +| `503`, `dependency_unavailable` | The database could not be reached, a redaction statement ran out of time, or another operator's completion of the same request still holds it (see [How long it takes](#how-long-it-takes)). No effect committed and the request is still awaiting; retry after the delay, because the redaction's statements are idempotent. The cause is in the API's log (warning 7110) | +| `503`, `dependency_unavailable` with `errors.outcome` = `lockey_outcome_unknown` | The commit was sent and its answer was lost. It **may have landed**: see [An unknown outcome](#an-unknown-outcome) | +| `500` | An unexpected failure or a deployment defect: no redaction executor registered, a refused credential, a missing grant or migration. The API's log names it. No effect of the act committed (the entry row stays) | + +## An unknown outcome + +Repeat the same completion. If the first landed, the repeat answers +`200 already_completed` with the recorded result and writes no second result row; if +it did not, nothing of it committed and the repeat completes the request now. To tell +your act from another operator's, read the tenant's result row by the `correlationId` +of the failed response, as in [Reading the result](#reading-the-result). A client that +never received an answer (a timeout, a gateway error) is in the same position. + +## How long it takes + +The redaction reads the tenant's audit rows in batches of at most 100,000 rows or 64 MiB +of payload, measured decompressed and counted only for the rows in the request's reach, +so the act takes time in proportion to the payload it must read: about twelve seconds +for 1.5 million ordinary rows (1.5 GB stored), about four seconds for 30,000 rows of +250 KB that compress well, about four minutes for a tenant whose rows carry 100 KiB of +incompressible payload (14 GB stored), and the request row stays locked throughout. Each +statement stays at about two seconds or less whatever the tenant's size; only the number +of batches grows. The act redacts the rows committed before it begins. Use a client with +no short timeout. A call dropped before the commit (a client or gateway timeout, a +closed connection) rolls the whole act back, and a retry starts again from the +beginning, so a gateway that cuts the call off earlier than the act ends can never +succeed. Two operators who complete the same request at once are serialized on its row: +the second waits for the first and then answers `already_completed`, unless the first +outlasts the platform connection's command timeout (30 seconds unless `Command Timeout` +is set in `ConnectionStrings:PlatformAdmin`), when the second answers `503 +dependency_unavailable`: repeat it after the first finished. Two requests for the same +person (one filed by the person, one by an administrator) wait on each other's rows the +same way, and a deadlock between them answers `503` too: repeat it. + +## Reading the result + +The response, and the result row's `after_state`, hold closed counts and never a person +identifier: `rows_selected`, `redacted` per column (`ip_address`, `user_agent`, +`actor_email`, `before_state`, `after_state`, `changes`) and `retained` per kind. The +audit log's retained kinds are: + +| Kind | Counts | +|---|---| +| `audit_actor_reference` | Selected rows whose `actor_user_id` is the person, which stays | +| `audit_entity_reference` | Selected rows whose `entity_id` is the person or one of their Memberships, which stays | +| `audit_metadata_reference` | Every row of the request's reach whose `metadata` names the person, selected or not, because the metadata stays (exact) | +| `unscoped_audit_rows` | For an administrator's request, rows outside the group's organization whose actor or entity is the person or one of their Memberships, which the selection does not reach (at least: payloads and metadata outside the reach are not read) | + +What survives on every row, by decision +([ADR-0108 § 6](../decisions/0108-privileged-audit-redaction.md)): `actor_user_id`, +`entity_id`, all of `metadata` (the causal actor, the authorization references and the +identity subject key among it), the causation and correlation identifiers, the module, +the operation, the outcome and the timestamps. The person's `UserId` stays a +pseudonymous identifier that the subject key keeps linkable: **never call the erased +person anonymous**, in a reply to the person, to the tenant or in a ticket. The +request's other retained kinds are the tenant side's report, and it is a partial list: a +kind it leaves out is retained and uncounted, never zero. The tenant side counts the +consent evidence, the invitation records (the offers the person issued or accepted, not +a pending offer addressed to their address), the request receipts, the attribution +references, the federation actor references and the provider event records of the group +([ADR-0107 § 6](../decisions/0107-data-request-fulfillment-and-account-closure.md)). +It does not count the transport and execution evidence, the idempotency cache, the +external copies or the invitation envelopes, so do not tell anyone that those were +reported or that none exist. The retention target of each audit row's class is in +[Audit Coverage § Retention](../standards/18-audit-coverage.md#retention), which no code +enforces yet: [Phase 11](../roadmap/phase-11-production-hardening.md) owns the purge. + +The redaction rewrites the rows that exist when it runs. The tenant's records keep their +creator, updater and deleter attribution, so a later edit of a record the person created +or last updated writes their identifier again, in a new audit row. Never tell the person +that no row will ever carry their identifier again. + +The result row is in the **tenant's** trail. There is no audit API: read it as the +application role announcing the tenant (keep the `tenantId` of the inspection item), by +the response's `correlationId`, with the digest recipe of +[Tenant onboarding](tenant-onboarding.md#reading-the-record) and this select list, which +adds the request and the closed report to it: + +```sql +BEGIN; +SELECT set_config('app.tenant_id', '', true); +SELECT timestamp, operation, outcome, reason, entity_id, before_state, after_state, + metadata->'operator' AS operator +FROM audit_log WHERE correlation_id = '' ORDER BY timestamp; +COMMIT; +``` + +`entity_id` is the request, `before_state` the status it was awaiting from and +`after_state` the report. Your ticket is not on the row, because the tenant can read it; +it is on the entry row, under the platform sentinel. Record the `correlationId` against +your own ticket. + +## When a person asks + +A person or a tenant asks why an erasure is not complete. The person's own receipt is +the status source: they ask for it under the identifier the request answered with, and +it shows the status and `executeAt`, the end of the 24-hour window in which they may +cancel. No e-mail is sent when an erasure finishes +([ADR-0107 § 10](../decisions/0107-data-request-fulfillment-and-account-closure.md)). A +request cannot be read by identifier through these routes, and the completion is not a +read: never call it to look. Say only what is true: the person's name, profile values +and role assignments in that group were erased, the IP address, user agent and e-mail +on the audit rows that concern them were removed once the operator step ran (backups +and archives are kept and purged on their own schedule), and their identifier stays as +a pseudonymous reference; never say they are anonymous. A `failed` +receipt means the job died: the person files again, and the old request stops blocking +them. + +## What an administrator sees + +A Membership has a page in Studio only while it is Active or Suspended, so an +administrator files an erasure in two acts: they revoke the Membership on the member's +page, which is recorded as its own `identity.membership.change_status` row, and Studio +then opens the erasure page `/studio/data-requests/erasure?membership=`. +That page reads nothing about the Membership; it files the erasure after the +administrator confirms a statement of what is erased, what is kept, the 24-hour window, +that the person may cancel in it, and that a re-admission within it does not stop the +erasure +([Frontend Architecture § Subject data requests](../standards/07-frontend-architecture.md#subject-data-requests)). +The API refuses it while the person still holds an Active or Suspended Membership of the +group. For a Membership revoked earlier, the same address takes its identifier: give the +administrator the `entity_id` of the revocation's `identity.membership.change_status` +row. Studio does not list Revoked members. The request's page in `/studio/data-requests` +then shows `Scheduled` and the end of the window, with a cancel form for the +administrator who filed it; `Starting soon` once the window has passed and the job has +not run; `Waiting for an operator` while it waits for you; and `Completed` with the +retained counts after your completion. A blocked erasure says why (a hold, or the person +is the last administrator). Studio never reads a Revoked Membership, so the list names +the person of an administrator's erasure, and of an erasure that has run, as a revoked +member, without a link. A closure is never listed; a closure's fan-out erasure is, filed +by the person's account closure and with no cancel form. If an administrator asks why an +erasure is not complete, the status on that page is what they see; answer as in +[When a person asks](#when-a-person-asks). + +## Deploying + +Every API host must run a build that registers the erasure definitions +(`identity.data_erasure_*`) before anyone files an erasure, and none may roll back to an +older build while an erasure is `scheduled`: a job is queued 24 hours ahead, and an +older host that claims one does not know its definition, treats it as an invalid +envelope and ends it terminal (`invalid_envelope`). A later version of a definition +keeps the old one registered for at least the window. + +## A dead erasure job + +A job that exhausted its attempts, or was quarantined, rolled every write back, so its +request stays stored `scheduled`: the person's receipt reads `failed` (the status is +derived from the job once its window has ended), the request cannot be cancelled after +`executeAt`, and the inspection keeps listing it under `overdue_scheduled`. Nothing +here repairs the job. The recovery is a new filing by the person, or by the +administrator who filed the first one: it stores the old request `failed` with +`execution_failed`, frees the one-active slot and schedules a new job. Tell them so, and +escalate the cause with the request identifier and the job's definition key. The job +logs its run as event 7511 (finished, with the outcome), 7512 (not yet due) and 7513 +(an attempt failed, with the exception type only). + +## Erasure never resets replay + +[ADR-0107 § 9](../decisions/0107-data-request-fulfillment-and-account-closure.md) sets +the floor. An erasure never rewrites or deletes an outbox, delivery, inbox or job row: +those are retained as `transport_evidence` and `execution_evidence`. A delivery an +operator replays or resets later re-runs its handler under that handler's own subject +rules, which refuse a Closing or Closed User but not a tenant-erased person, whose User +stays Active. So a replayed delivery about the person may write rows for them again in +that tenant; those rows are retained transport evidence that no report counts, and they +are not undone. A delivery about a person whose closure has begun, or was finalized, +runs its handler, which refuses the person and writes nothing. Before a +[replay or a producer reset](operator-recovery.md#choose-replay-or-reset) in a tenant +where an erasure completed, ask whether the event concerns the erased person. + +## Targets and escalation + +- Complete every listed erasure well inside the 30 days of + [ADR-0106 § 12](../decisions/0106-subject-data-requests-authority-and-status.md); the + count starts when the request was filed. +- An erasure that keeps answering `503` or `500`, one listed under `overdue_scheduled` + or `stuck_fulfilling`, and a quarantined erasure job are escalations to the + deployment's owner, with the request identifier and the `correlationId` of each failed + call. Nothing here repairs a job. A closure listed under `stuck_fulfilling` is not an + erasure: [Account closure](account-closure.md#targets-and-escalation) says when it is + an escalation. +- Never change an audit row or a request by hand. A statement outside the executor and + the request guard's one arrow writes no record, and the guard refuses every other + change to a request. + +## Signals + +`learnstack_platform_operator_admissions_total{outcome,operation}` counts the acts +admitted or refused at the gate, with `operation` `platform.data_request.inspect` or +`audit.redaction.apply`; +`learnstack_platform_operator_results_total{operation="audit.redaction.apply"}` counts +the completions committed, and a repeat that answers `already_completed` is not one; +`learnstack_platform_operator_data_requests_total{operation,outcome}` counts every call +that reached the owner by how it ended (an inspection's `ok` or `invalid_cursor`; a +completion's `completed`, `already_completed`, `not_found`, `not_erasure`, +`closure_fanout` or `not_awaiting`; either's `audit_unavailable`, `unavailable` and +`failed` (an unexpected failure, answered `500`), and a completion's `commit_unknown`), +so a refused, repeated or unknown-outcome act leaves a signal; +`learnstack_platform_operator_audit_failures_total` counts the refusals for an audit +failure. Each inspection page and each completion logs the scope-entry line 7001, a +refused audit write the error line 7105, and an unavailable database or redaction the +warning line 7110, whose exception holds the cause. The admission and refusal counters +are in [Platform operator access](operator-access.md#signals). + +## Not recoverable here + +- A redacted value: LearnStack keeps no copy, but backups, WAL archives and row versions + awaiting vacuum can still hold one. +- What survives by decision: `actor_user_id`, `entity_id`, `metadata` and the + identifiers of every audit row. +- A request that is `blocked`, `failed` or `cancelled`: the person files a new one. A + `blocked` receipt shows why in its `lastRefusal` (`blocked_last_administrator` or + `blocked_hold`): the person or the tenant resolves that first. +- Copies outside the database, such as the identity provider's events, backups, WAL + archives and mail copies (`external_copy`): + [Phase 11](../roadmap/phase-11-production-hardening.md) owns their purge. +- A dashboard. diff --git a/docs/runbooks/data-export.md b/docs/runbooks/data-export.md new file mode 100644 index 000000000..de52af4a1 --- /dev/null +++ b/docs/runbooks/data-export.md @@ -0,0 +1,291 @@ +# Data export + +Operating the subject data export of +[ADR-0107 § 4](../decisions/0107-data-request-fulfillment-and-account-closure.md): its +key ring, a lost or exposed key, a request that never finishes, an artifact whose purge +died, deployments, capacity, and the memory of the processes that handle it. The +request, artifact and download model is in the +[Identity module](../modules/identity/README.md); the settings are in +[Identity providers § Configuration surface](../modules/identity/providers.md#configuration-surface-and-source-bindings). + +## What it needs + +- `DataExport:KeyRing` (environment `DataExport__KeyRing`), a secret resolved through + `ISecretProvider`: + `{ "active": "
_tenant_id_organization_id`: its readers are tenant-scope, so the arm that -fires is `app.scope = 'tenant'`, which no index serves, and a fifth index on a +fires is `app.scope = 'tenant'`, which no index serves, and such an index on a high-volume append-only table is a write cost paid on every row for a predicate arm -nothing shipped takes. The four indexes it does carry, and the reasoning, are in +nothing shipped takes. The indexes it does carry, and the reasoning, are in [Audit Subsystem § 7](../architecture/31-audit-subsystem.md). They ship in a **fourth migration chain**, owned by @@ -1094,13 +1094,17 @@ Step 3; contextual Membership/Role grants are implemented in Step 4. | Table | `learnstack_app` | `learnstack_platform` | `learnstack_outbox_admin` | |---|---|---|---| | `identity_authority` | `SELECT` | — | — | -| `users` | `SELECT` and only the [initial INSERT columns](#global-owners-and-privileges); no UPDATE/DELETE/TRUNCATE | — | — | -| `memberships` | `SELECT, INSERT, UPDATE`; no DELETE/TRUNCATE | — | — | +| `users` | `SELECT` and only the [initial INSERT columns](#global-owners-and-privileges); no UPDATE/DELETE/TRUNCATE | `SELECT` of `id`, `status`, `provider_subject` and `subject_key`; `UPDATE` of `status` and `provider_subject`, which the [closure's trigger exception](#the-users-trigger-exception) admits for two transitions only | — | +| `memberships` | `SELECT, INSERT, UPDATE`; no DELETE/TRUNCATE | `SELECT` of `id`, `tenant_id`, `organization_id`, `user_id`, `status` and `deleted_at` only ([closure participants](#the-platform-grants)) | — | | `membership_profiles` | `SELECT, INSERT, UPDATE`; no DELETE/TRUNCATE | — | — | -| `membership_role_assignments` | `SELECT, INSERT, DELETE`; no UPDATE/TRUNCATE | — | — | -| `roles` | `SELECT, INSERT, UPDATE`; no DELETE/TRUNCATE | — | — | -| `role_permission_grants` | `SELECT, INSERT, DELETE`; no UPDATE/TRUNCATE | — | — | +| `membership_role_assignments` | `SELECT, INSERT, DELETE`; no UPDATE/TRUNCATE | `SELECT` of `tenant_id`, `membership_id` and `role_id` only ([last-administrator read](#the-platform-grants)) | — | +| `roles` | `SELECT, INSERT, UPDATE`; no DELETE/TRUNCATE | `SELECT` of `id`, `tenant_id`, `built_in_key`, `permission_scope`, `deleted_at` and `deleted_by` only ([last-administrator read](#the-platform-grants)) | — | +| `role_permission_grants` | `SELECT, INSERT, DELETE`; no UPDATE/TRUNCATE | `SELECT` of `tenant_id`, `role_id`, `permission_scope` and `permission_key` only ([last-administrator read](#the-platform-grants)) | — | | `federation_connections` | `SELECT, INSERT, UPDATE`; no DELETE/TRUNCATE, because the row ends as a tombstone | `SELECT` of `id`, `tenant_id`, `state` and `deleted_at` only ([ADR-0099](../decisions/0099-confined-tenant-federation.md) Amendment 11); exact [projection grant](#federation-operator-projection) | — | +| `data_subject_requests` | `SELECT, INSERT`; `UPDATE` of the status, `row_version`, progress, result, refusal, failure, completion and update-stamp columns; no DELETE | `SELECT` of sixteen closed columns, no requester or actor stamp; `UPDATE` of status, `row_version`, `completed_at`, `result` and `last_refusal`, which the guard's [platform arm](#data-request-operator-storage) admits for the erasure's completion and the [closure's arrows](#the-request-guards-closure-arrows) only | — | +| `data_export_artifacts` | `SELECT, INSERT`; `UPDATE` of status, `purged_at`, `row_version` and the update stamps | `SELECT` of `id`, `tenant_id`, `request_id`, `status` and `expires_at` only ([ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) § 8) | — | +| `data_export_tickets` | `SELECT, INSERT`; `UPDATE (consumed_at)` | — | — | +| `data_export_chunks` | `SELECT, INSERT, DELETE` | — | — | | `tenants` | `SELECT, INSERT, UPDATE` | `SELECT, INSERT, UPDATE, DELETE` | Lifecycle-column `SELECT` only; exact [projection grant](#job-lifecycle-projection) | | `organizations` | `SELECT, INSERT, UPDATE, DELETE` | `SELECT, INSERT, UPDATE, DELETE` | Lifecycle-column `SELECT` only; exact [projection grant](#job-lifecycle-projection) | | `tenant_domains` | `SELECT, INSERT, UPDATE, DELETE` | `SELECT` | — | @@ -3917,6 +3921,7 @@ CREATE INDEX ix_background_jobs_parent ON background_jobs (tenant_id, parent_job CREATE INDEX ix_background_jobs_recipient ON background_jobs (tenant_id, recipient_id); CREATE INDEX ix_background_jobs_current_attempt ON background_jobs (tenant_id, id, current_attempt_id); CREATE INDEX ix_background_jobs_final_outcome ON background_jobs (tenant_id, id, final_outcome_attempt_id); +CREATE INDEX ix_background_jobs_definition ON background_jobs (tenant_id, definition_key, organization_id); CREATE INDEX ix_background_job_attempts_outcome ON background_job_attempts (tenant_id, job_id, final_outcome_attempt_id); CREATE INDEX ix_background_job_reservations_capacity ON background_job_reservations (tenant_id, capacity_group); CREATE INDEX ix_background_job_recipients_job ON background_job_recipients (tenant_id, accepted_job_id); @@ -4745,8 +4750,8 @@ UserId. The global class is not an exemption from transaction/capture guards. | `identity_authority` | Platform-scoped singleton, `id = 1` primary key and CHECK; immutable unique `authority_id uuid`; one current exact issuer URI. No tenant filter and no User/person fields. | | `users.id` | Permanent UserId UUIDv7 primary key, allocated through the existing injected ID source only after serialized absence is established. | | `users.authority_id`, `subject_key` | AuthorityId references the singleton's stable authority UUID; `subject_key bytea` has exactly 32 bytes. Unique `(authority_id, subject_key)` has no partial predicate and survives closure. | -| `users.provider_subject` | Nullable, sensitive exact opaque provider subject. Active requires a nonempty value; Closed requires NULL. Closing permits NULL and retains a bounded nonempty value only while the separately admitted closure owner needs it. | -| `users.status` | Closed CHECK set `Active`, `Closing`, `Closed`; ordinary bootstrap inserts Active only. Closing and Closed refuse new admission. | +| `users.provider_subject` | Nullable, sensitive exact opaque provider subject. Active requires a nonempty value; Closed requires NULL. Closing permits NULL; the closure's [trigger exception](#the-users-trigger-exception) keeps the value from Active to Closing, for the provider removal, and removes it from Closing to Closed. | +| `users.status` | Closed CHECK set `Active`, `Closing`, `Closed`; ordinary bootstrap inserts Active only. Closing and Closed refuse new admission. Only the platform session's closure moves it, Active to Closing and Closing to Closed, under the [trigger exception](#the-users-trigger-exception); nothing returns to Active. | | `users.creation_audit_id`, `creation_audit_timestamp` | Immutable complete central-audit key, allocated centrally with timestamp normalized once to PostgreSQL microsecond precision. Deferred creation guards verify it before commit; no perpetual cross-module foreign key or purge veto. | | User audit/concurrency fields | All six inherited audit columns and the existing row-version convention. CHECK requires `deleted_at` and `deleted_by` to remain NULL: closure uses status, not soft deletion. | @@ -4846,7 +4851,11 @@ BEFORE DELETE and BEFORE TRUNCATE guards preserve bindings for every role, including owner/definer execution. FORCE RLS does not govern TRUNCATE, and absent app grants do not constrain the owner. DDL-capable disabling/dropping of guards is outside this trust boundary; no admitted definer body performs such DDL. -Later lifecycle/profile writers need separately accepted grants and guards. +Later lifecycle/profile writers need separately accepted grants and guards. The one +lifecycle writer is the platform session's closure, under its column grant and the +[trigger exception](#the-users-trigger-exception) of +[Account closure storage](#account-closure-storage); the policy and the application +role are unchanged by it, and the platform role bypasses the policy. @@ -5040,6 +5049,21 @@ complete ordered User/tenant plan is preheld. The exclusive User fence remains held transactionally through check and completion. Profile-only updates, suspension/revocation and assignment removals do not automatically acquire a User fence; their required tenant mode still follows actual protected changes. +The one exception to a Revoked Membership's immutability is the erasure's clearing +([ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) § 5): +the guard passes an `UPDATE` of a Revoked Membership's profile that sets the display +name and the locale to NULL and the custom values to `[]`, and only while the +subject's exclusive User fence is held on the connection and that subject's `erasure` +request for the Membership's group is `fulfilling` and names that Membership in its +frozen snapshot; such an update requires the tenant key EXCLUSIVE. The request guard +admits a request born `fulfilling` only as a closure's fan-out erasure of a subject who +is Closing ([the User status witness](#the-user-status-witness)), so the application +role cannot create that witness for a person no closure has begun. Every other write +under a Revoked parent still raises `P0304`, apart from the assignment removals the +guard already admitted; the profile's `DELETE` is refused earlier, by the missing +grant. +`DataErasureGuardTests` removes each condition alone as `learnstack_app`, and +`EducationStructureTests` pins the function body. Exclusive User mode retains the adopted per-User admission serialization, rather than merely excluding closure. A shared admission alternative needs a separate decision. No additional callable User reader or synthetic preparation trigger is @@ -5055,7 +5079,23 @@ 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. The database witness of +that order is the closure's [trigger exception](#the-users-trigger-exception): it +refuses the status change unless the User key and every participant tenant key are +held exclusively on the writing connection. + +> **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. The Finalize that makes the User Closed holds the User key alone +> through its first transaction, the redaction with its intent row, which moves no User +> and no request, and the User key with every participant tenant key through its second, +> the move to Closed with the completions, and no key between them, while the identity +> provider deletes the account (2026-11-23). + They cannot make the final administrator ineligible without a separately accepted recovery/termination contract; closure and Archived status are not implicit exceptions. @@ -5131,8 +5171,10 @@ transition. The fixture migration owner obeys the same User-then-affected-tenant order; it supplies no isolation proof. Actual Membership mutations still run as `learnstack_app`. Restore guard/policy in `finally` and verify exact restored body/ACL/trigger/policy census plus owner UPDATE refusal. Dirty/clean controls -prove both the accommodation and restoration. No production status writer or -grant follows; eligibility is otherwise immutable in this foundation. +prove both the accommodation and restoration. The fixtures add no status writer or +grant; the one production writer is the platform session's closure under the +[trigger exception](#the-users-trigger-exception), and eligibility is otherwise +immutable in this foundation. @@ -5702,8 +5744,15 @@ 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 -resolved context is a fifth logical writer of the context accessor, beside the four of +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 [User status witness](#the-user-status-witness) of the data-request guard +is the eighteenth definer; it adds no logical tenant setter. The +[delayed mirror's subject status](#the-delayed-mirrors-subject-status) is the nineteenth +definer; it adds no logical tenant setter either. 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 describe their own slices @@ -6346,8 +6395,8 @@ 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 - function and of its port by + 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). A Membership written under that answer still passes the ordinary admission guard, which @@ -6503,8 +6552,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 @@ -6593,3 +6641,475 @@ 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`, `chunk` and `revoke` 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. 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 + +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; the head pin is in `MigrationRollbackTests`. + +## Data-request operator storage + +**Derives from:** +[ADR-0107 § 8](../decisions/0107-data-request-fulfillment-and-account-closure.md) and +[ADR-0108](../decisions/0108-privileged-audit-redaction.md) § 8 and § 9. The operator's +data-request inspection and erasure completion run on `learnstack_platform` in the +platform scope. The Identity migration +`20261122200000_grant_platform_data_request_operations` carries the guard arm, the grant +and the two indexes below; it is forward-only, and the head of the Identity chain is +pinned in `MigrationRollbackTests`. + +### The request guard's platform arm + +`fn_identity_data_request_guard` gains one branch for a session whose `session_user` and +`current_user` are both `learnstack_platform`, ahead of the application role's arms, +which are unchanged character for character: a unit test compares them with the +definition the request storage migration installed. The +[account closure migration](#account-closure-storage) replaces the function again: it +keeps this arrow as it is, adds the closure's arrows to the same branch and changes the +application's INSERT arm in one pinned place. The branch admits an `UPDATE` and nothing +else, and only: + +- the arrow `erasure: awaiting_privileged_step → completed` of an erasure whose origin + is not `closure_fanout`, and the + [closure's arrows](#the-request-guards-closure-arrows); every other arrow, status and + kind is refused (`Data request transition refused.`); +- with every column but the status, `row_version`, `completed_at`, `result` and + `last_refusal` unchanged as the statement presents them, `updated_at` and `updated_by` + included, and `row_version` stepped by exactly one + (`Data request immutable state refused.`); `last_refusal` changes on a closure's + refusal record alone (`Data request refusal record refused.`); +- with `result` changed only in the audit log's four retained kinds, + `audit_actor_reference`, `audit_entity_reference`, `audit_metadata_reference` and + `unscoped_audit_rows`, so the tenant side's record stays as its participants wrote it + (`Data request result refused.`). + +The branch stamps `updated_at` from the database clock, never earlier than the row's +last stamp, `updated_by` as `UserId.SystemActor` and `completed_at` as that +`updated_at`, overriding whatever the statement set. Columns a trigger assigns need no +column grant, so the platform role's `UPDATE` grant is the four columns ADR-0107 § 8 +lists and the closure's `last_refusal`. The role holds no `INSERT` or `DELETE`; the +application role cannot take the platform's arrow, and the platform role cannot take +one of the application's. The arrow refuses an erasure whose origin is +`closure_fanout`, which only a closure's Finalize completes (ADR-0107 § 7), under the +[closure's arrows](#the-request-guards-closure-arrows) the same branch carries. + +### The artifact read + +`learnstack_platform` holds `SELECT` of `id`, `tenant_id`, `request_id`, `status` and +`expires_at` on `data_export_artifacts`: what the inspection's expired-artifact list +filters, joins, orders and shows, with the group read from the joined request. No +subject, size, key version, truncation, actor or purge time is granted, because the +lifecycle CHECK makes `status IN ('available','expired')` the rows with no `purged_at`, +and nothing on `data_export_tickets` or `data_export_chunks`. Column privileges are read +from the attribute ACLs, as for every column-grant table. + +### The inspection indexes + +```sql +CREATE INDEX ix_data_subject_requests_operator_due ON public.data_subject_requests + (status, (COALESCE(execute_at, created_at)), id) + WHERE status IN ('scheduled','fulfilling','awaiting_privileged_step'); +CREATE INDEX ix_data_export_artifacts_unpurged_expiry ON public.data_export_artifacts (expires_at, id) + WHERE status IN ('available','expired'); +``` + +Each request list filters one status and orders by when the request fell due, then by +its identifier; the artifact list orders by expiry. A keyset cursor seeks past the last +row. A test asks PostgreSQL for the plan of each statement the inspection runs, with and +without a cursor, and requires an ordered scan of its index with no sort. The migration +builds both without `CONCURRENTLY`, inside its transaction, as the earlier operator +indexes were. + +### Proof + +Real PostgreSQL as each role: + +- `DataRequestStorageControlTests`: on erasures the application role created and moved + through its own arrows, the platform role completing one through the arm and the + stamps it writes, and each refused variant: a missing or doubled version step, a + result that changes, drops or adds a tenant-side kind, every other arrow from the + awaiting state, an application arrow on a scheduled erasure, a column outside the + grant, a `DELETE` and a second completion; and the application role refused the + platform's arrow and a result change. +- `DataRequestStorageTests`: the exact grant matrix of the four tables, the five + artifact columns, and the platform role refused every other column, table and an + export's arrow. +- `DataRequestOperatorOperationsTests`: the four lists and their order, the cursors, the + entry row, the plans, and the completion's one transaction from the row's own subject, + its result row, its repeat, its refusals, its failures, a lost commit and two + concurrent completions. +- `PlatformAdminScopeTests`: the redaction bound to its operation, on the scope's own + transaction and before the result row, faulting the scope when it fails, and refused + without an executor. +- `PlatformOperatorHttpTests` and `PlatformAdminGateTests`: the routes, their statuses + and contract, and the pair of permissions, each held alone. + +## Account closure storage + +**Derives from:** +[ADR-0107 §§ 7 and 8](../decisions/0107-data-request-fulfillment-and-account-closure.md) +and [ADR-0072 Amendment 8](../decisions/0072-application-owned-identity-bootstrap.md). +A global account closure moves a User Active to Closing and Closing to Closed on +`learnstack_platform` in the platform scope, and erases each participant group as the +application role. The Identity migration `20261123100000_admit_account_closure` +carries the grants, the trigger exception, the request guard's closure arrows and the +User status witness below. The forward migration `20261123120000_admit_closure_finalize` +then replaces the request guard so that Finalize's arrow also takes a closure of the +subject that was never begun, and grants the request's update stamp; and +`20261123130000_harden_closure_request_guard` replaces it once more, so that the +application role writes no closure that left `scheduled` and asks the subject's status +only after the snapshot. All three are forward-only, and the head of the Identity chain +is pinned in `MigrationRollbackTests`. +Every arrow reads its witnesses in SQL on the +connection that writes: the subject's User status, the request's own state and the +advisory fences that connection holds. None of them trusts a flag a caller passes. + +### The closure's fences + +A closure's fences are the subject's User key and the key of every tenant in which the +subject holds a Membership of any status, a Revoked tombstone included, each held +exclusively on the writing connection, with the canonical key of +[Lock, snapshot and adoption conditions](#lock-snapshot-and-adoption-conditions). Each +check below observes them with `fn_identity_lock_held` and acquires none. It reads the +participant tenants from `memberships` through `ix_memberships_user_id`, once per +distinct tenant. Memberships are never deleted and a new one needs the subject's +exclusive User key, so the participant set cannot change while that key is held. +Transaction-level keys end at the commit, so a second transaction takes them again. + +**The acquirer.** One class takes them on the platform connection, +`PlatformIdentityFences` in the Identity infrastructure, through the platform scope's +statement facade and nothing else: first it refuses any transaction whose +`transaction_isolation` is not `read committed`, because the participant read must take +its snapshot after the User key is granted; then +`SELECT pg_catalog.set_config('lock_timeout', '3s', true)`, so every wait of the +transaction is bounded; then `pg_catalog.pg_advisory_xact_lock` of the subject's User +key; then the participant groups, read under that key in one grouped statement through +`ix_memberships_user_id` with the Memberships the subject holds in each, at most one +group past the closure's bound; then, only for a person within +[`ClosureLimits`](../../backend/src/LearnStack.SharedKernel/DataProtection/ClosureLimits.cs) +(256 participant groups and 256 Memberships in one participant tenant), the key of +every participant tenant and of the request's own tenant, ascending by key. A person +past the bounds takes no tenant key, and Begin refuses them with nothing written. It +takes no shared and no session-level key. A key not granted within three seconds fails +its statement with `55P03`, which abandons the scope, and the act answers the retryable +unavailable. It is not `IIdentityMutationLocks`, which fences one tenant inside a +tenant-announced application transaction; `IdentityPlatformFenceConventionTests` pins +it as the one platform acquirer and the order it takes the keys in. + +**Fences per transaction.** The acquirer has two forms. `AcquireAsync` takes every key, +for a transaction that moves the User or a closure's request, which the checks below +admit only under all of them. `AcquireUserAsync` takes the User key alone and reads the +participants under it, for a transaction that moves neither. A closure's Begin runs +one transaction with every key. Its Finalize runs two platform transactions around the +identity provider's account deletion: the first, the redaction with its intent row, +holds the User key alone, so no participant tenant's identity writes wait for the +redaction while the User key keeps the participant set fixed; the second takes every +key before the User moves to Closed. Each transaction's keys end at its commit, so none +is held while the provider runs. `IdentityPlatformFenceConventionTests` pins the two +calls, their forms and their order; the second transaction's changes are refused +without its own keys. + +**Finalize's reads.** Each reads the person's own rows by the person's indexes: +`AccountClosureOperatorOperations.ReadinessSql`, each participant group's newest erasure +of the person with whether it completed at or after the closure's Begin and whether its +frozen Memberships include every Membership the person holds in the group, through +`ix_data_subject_requests_subject_user_id` and `ix_memberships_user_id`; +`MembershipsSql`, every Membership of the person by tenant for the tenant passes, +through `ix_memberships_user_id`, bounded at what an admitted closure can hold +(`ClosureLimits.MaximumMemberships`, 65,536); and `OpenClosuresSql`, the person's other +open closures, locked, through `ix_data_subject_requests_subject_user_id` and bounded by +the group bound. The erasures the second transaction completes are locked by primary +key first, so one an erasure completion finished meanwhile is read as it committed and +left as it is. `AccountClosureFinalizeTests` asks PostgreSQL for the plans of these and +of the acquirer's grouped participant read over thousands of other people's rows in the +same groups. A begun closure's Begin moment is its own `updated_at`: the Begin arrow +stamps it from the database clock, and no arrow writes the row again until Finalize +completes it, because the application role writes no closure that left `scheduled`. + +**The last-administrator read.** A closure's Begin judges each participant tenant that +allows ordinary work with `AccountClosureOperatorOperations.AdministratorStandingSql`: +the administrator predicate of the deferred complete-graph guard, with +`users.status = 'Active'`, which the application role's read cannot see, read under the +fences. `AccountClosureAdministratorParityTests` proves it answers as the guard over +Active, Suspended, Revoked and Closing administrators, an organization administrator, a +tenant-wide learner and a Role missing a kernel grant. Its index path is the current +`TenantAdmin` Role of each tenant (`ux_roles_current_builtin_scope`), its assignments +(`ix_membership_role_assignments_tenant_id_role_id`), and the Memberships, grants and +Users by their keys. + +### The platform grants + +`learnstack_platform` bypasses row security, so these column grants are its whole +bound; none is table-wide: + +| Object | Granted to `learnstack_platform` | +|---|---| +| `users` | `SELECT` of `id`, `status`, `provider_subject` and `subject_key`; `UPDATE` of `status` and `provider_subject` | +| `memberships` | `SELECT` of `id`, `tenant_id`, `organization_id`, `user_id`, `status` and `deleted_at` | +| `membership_role_assignments` | `SELECT` of `tenant_id`, `membership_id` and `role_id` | +| `roles` | `SELECT` of `id`, `tenant_id`, `built_in_key`, `permission_scope`, `deleted_at` and `deleted_by` | +| `role_permission_grants` | `SELECT` of `tenant_id`, `role_id`, `permission_scope` and `permission_key` | +| `data_subject_requests` | `SELECT` of `updated_at`, a begun closure's Begin moment; `UPDATE` of `last_refusal`, beside the four columns of the [platform arm](#data-request-operator-storage) | +| `fn_identity_lock_held`, `fn_identity_contextual_lock_key` | `EXECUTE`; both read only the calling backend's own `pg_locks` rows | + +`provider_subject` is what Finalize removes from the identity provider, and +`subject_key` is what its redaction selects the sentinel tenant's rows by +([ADR-0108](../decisions/0108-privileged-audit-redaction.md) § 4). The assignment, +Role and grant columns are exactly those the administrator predicate of +`fn_identity_complete_graph_guard` reads, so a participant tenant's last-administrator +judgment runs on the platform connection, for any tenant, with no announcement. The +predicate's `member.deleted_by IS NULL` is neither granted nor needed: +`ck_memberships_lifecycle` makes both deletion columns NULL for every Active +Membership. Nothing of `membership_profiles` or `identity_authority` is granted. + +### The `users` trigger exception + +`fn_identity_user_immutable` still backs `tg_users_no_update`, `tg_users_no_delete` +and `tg_users_no_truncate`. A `DELETE`, a `TRUNCATE` and every `UPDATE` whose +`session_user` and `current_user` are not both `learnstack_platform` stay refused +(`Identity bindings have no admitted update or removal owner.`), the migration +owner's included. The platform session's `UPDATE` passes only when all of these hold, +each refused with its own `23514` message: + +- no column but `status` and `provider_subject` differs + (`User closure column refused.`); +- the transition is Active to Closing with `provider_subject` unchanged, or Closing to + Closed with `provider_subject` NULL; Closing never returns to Active and Closed never + changes (`User closure transition refused.`); +- the subject's User key is held exclusively (`User closure fence refused.`); +- the subject holds a Membership (`User closure participant refused.`): a person with + no Membership files no closure, and Phase 11 owns theirs + ([ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) + § 10); +- every participant tenant's key is held exclusively + (`User closure tenant fence refused.`). + +The function then stamps `row_version` one higher, `updated_at` from the database +clock, never earlier than the row's last stamp, and `updated_by` as +`UserId.SystemActor`, so the column grant stays at the two columns. The `users` policy +and the application role's grants are unchanged. Its body reads rows through existence +tests only, as the function census of the first Identity migration requires. + +### The request guard's closure arrows + +The platform arm of `fn_identity_data_request_guard` carries four arrows beside the +erasure completion of [Data-request operator storage](#data-request-operator-storage), +under that arm's common rules: an `UPDATE` only, every column outside the arrow as the +statement presents it, the version stepped by one, `last_refusal` changed on the +refusal record alone, and the update stamps and, on a completion, `completed_at` +written by the guard. + +| Arrow | Admitted only when | `result` | +|---|---|---| +| Closure `scheduled → scheduled`, the refusal record | the new `last_refusal` is `blocked_window`, `blocked_hold` or `blocked_last_administrator` and differs from the standing one; `completed_at` unchanged | unchanged | +| Closure `scheduled → fulfilling`, Begin | `clock_timestamp()` is at or past `execute_at`; the subject is Closing; the User key, the request's tenant key and every participant tenant key are held exclusively; `completed_at` unchanged | unchanged | +| Closure `fulfilling → completed` or `scheduled → completed`, Finalize | the subject is Closed; the fences of Begin | changes only in the four audit kinds and `unserved_group` | +| Erasure of origin `closure_fanout`, `awaiting_privileged_step → completed` | the subject is Closing or Closed; the User key and the request's tenant key are held exclusively | changes only in the four audit kinds | + +A refusal record is set or replaced, never cleared: a Begin that succeeds later moves +the request on, and recording the standing code again, which the aggregate treats as +no change, is refused. The new refusals are `Data request refusal record refused.`, +`Data request closure window refused.`, `Data request closure subject refused.`, +`Data request closure user fence refused.` and +`Data request closure tenant fence refused.`. Begin reads the subject Closing, so it +follows the User's move in its transaction; Finalize reads it Closed, so it follows +the move to Closed. Finalize's arrow takes a closure from `scheduled` too: a person may +hold an open closure in each group, and once the subject is Closed none of them can be +begun, so Finalize completes every one of them with the one it finalizes, under the +same witnesses, and none stays open behind a closed account. Every other arrow, kind, +origin and status stays refused. The +application role's arrows include none of these four, and its `UPDATE` arm refuses +every write of a closure's row but one that keeps it `scheduled` or cancels it +(`Data request transition refused.`), so a closure the platform made `fulfilling` is +written by these arrows alone; its own refusal record +([ADR-0106](../decisions/0106-subject-data-requests-authority-and-status.md) § 7) +still admits a code on a scheduled request, a closure's included, and no +application path writes one on a closure. + +### The User status witness + +The application's INSERT arm admits one request born `fulfilling`: a closure's fan-out +erasure, of kind `erasure` and origin `closure_fanout`, with no `execute_at`, no +requester and the system actor as `created_by`. Every other origin, a closure and an +export are still born `scheduled` or `requested`, and a fan-out is born nothing else +(`Data request initial state refused.`). After its existing tenant fence and exclusive +User fence, and after its exact snapshot check, so a refused snapshot is answered +before any status is asked, the arm then admits every request only +for a subject in the one status its origin allows: Closing for a closure's fan-out, +Active for every export, erasure and closure of the person or an administrator +(`Data request subject is not admitted.`). The status is read under the User fence, so +a filing admitted while the person was Active whose transaction reaches the fence only +after a Begin or a Finalize committed inserts nothing: no closure stays `scheduled` +behind a closed account, and no administrator files for a person whose account is +closing. A Closed subject has no request of any origin. + +The application role cannot read another person's `users` row, so the arm asks +`public.fn_identity_user_status(target uuid)`, which returns `text`: a `plpgsql` +`VOLATILE` definer owned by the NOBYPASSRLS `learnstack_migration`, with a fixed +`search_path=pg_catalog`, `REVOKE ALL FROM PUBLIC` and `EXECUTE` to `learnstack_app` +only. It reads `users` through the table's owner arm and returns the subject's status +and nothing else, or NULL for no such User, outside a trigger, or unless the calling +backend holds the subject's User key exclusively, so inside the guard it reads only the +status of the subject the writing transaction fences. The confinement is the guard's, +not the caller's: a session that takes the key, which any application session may, and +fires a trigger of its own can read that one closed status, as +`fn_identity_admin_admission_state` already reads an administrator's. + +### The delayed mirror's subject status + +A delayed delivery refuses a person whose User is no longer Active, as intake does +([ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) §§ 7 and +9). The tenant mirror of a provider fact reads its retained target on the application +role, which cannot read the affected person's `users` row, so the Identity migration +`20261123110000_refuse_closing_provider_event_delivery` adds +`public.fn_identity_provider_event_subject_status(target uuid)`, which returns `text`: a +`plpgsql` `VOLATILE STRICT` definer owned by the NOBYPASSRLS `learnstack_migration`, +with a fixed `search_path=pg_catalog`, `REVOKE ALL FROM PUBLIC` and `EXECUTE` to +`learnstack_app` only. It answers for one target only: one of the tenant the transaction +announced (`app.tenant_id`), already enqueued, whose affected person it names. It then +takes that person's User key shared, transaction-scoped, as intake's +`fn_identity_provider_event_accept` does, and returns the person's status and nothing +else, or NULL for any other target. The shared key orders the read against a closure's +Begin and Finalize, which hold the key exclusively: a delivery that read Active commits +before the User leaves Active, so its row is one Finalize's redaction selects, and a +delivery that waited reads the status they committed. It is the only key the delivery +takes, so it orders no cycle; the delivery's five-second command budget bounds the wait. +The fact reader selects it with the target in one statement through the target's primary +key and the `users` primary key; the Audit subscriber withholds the observation of a +person it does not report Active, so the delivery completes with its inbox row and no +audit row. + + +### Proof + +Real PostgreSQL as each role, in `AccountClosureStorageTests`, each case on its own +disposable copy of the seeded schema: + +- the trigger exception admitted with the User key and every participant tenant key, + a Revoked tombstone's tenant included, and the stamps it writes; refused with each + key removed alone or held shared, for every other transition, for a third column + under a widened grant, for the application role and the migration owner holding + every fence, for a superuser session switched to the platform role, for `DELETE` and + `TRUNCATE` under widened grants, and for a subject with no Membership; +- Begin, the refusal record, Finalize from `fulfilling` and from `scheduled`, and the + fan-out completion admitted with their exact witnesses and refused with each removed + alone: a missing or shared fence, a + subject in the wrong state, a closure still in its window, a result changing a kind + outside its arrow, a column outside the grant, a missing version step, a refusal + record cleared or repeated, and `INSERT` and `DELETE` under a widened grant; the + application role refused every closure arrow; +- the fan-out born `fulfilling` for a Closing subject in a tenant-wide and an + organization group, and refused for an Active and a Closed one, without either + fence, outside its closed values, and for every other origin and status; every kind + and origin the CHECKs admit filed for an Active subject and refused for a Closing + and a Closed one, the fan-out the other way round for Active and Closing; a filing + that waited on the User fence behind a committing Begin refused; the witness + function's answers inside and outside a trigger, and its ACL; +- the platform grants read from the attribute ACLs, the participant read and its index, + and the last-administrator predicate answering on the platform connection as on the + announced application connection. +- the delayed mirror's refusal through an actual replay, in + `DataErasureReplayFloorTests`: a delivery dead-lettered while the person was Active + and replayed after the User became Closing, and again Closed, runs the handler, which + writes no audit row, fails nothing and advances the replay count once, and the subject + status definer is in the definer census; and again after the person's real Begin, + fan-out, erasure jobs and Finalize; +- Finalize itself, in `AccountClosureFinalizeTests` and `AccountClosureEndToEndTests`: + the User moved to Closed with the raw subject removed only under the second + transaction's own keys, every participant erasure and every open closure completed, + and the readiness, the plans and the races above; and `DataRequestStorageLiteralTests` + pins that the Finalize migration's guard is the earlier guard but for the one arrow + condition. + +`DataRequestStorageLiteralTests` pins the guard's application arms to the request +storage migration's text but for the INSERT arm's one block, and the definer and +function censuses are in `GlobalIdentitySchemaTests`. diff --git a/docs/standards/07-frontend-architecture.md b/docs/standards/07-frontend-architecture.md index 1d5e6b22c..b242cc697 100644 --- a/docs/standards/07-frontend-architecture.md +++ b/docs/standards/07-frontend-architecture.md @@ -136,10 +136,10 @@ evidence belongs to the [delivery record](../roadmap/phase-02d-delivery-log.md#r - Admit GET/HEAD on HTTP paths reaching the native listener callback before Next dispatch, including matcher-exempt health/assets and exact scaffolds. - The existing ADR-0070 sign-in/sign-out/extend POSTs, the exact ADR-0078/0079 - [entry/administration form set](#native-entry-and-administration) and ADR-0093's - [invitation form set](#verified-invitation-experience) are the only - additional admitted methods, with their closed proof/body rules. All other + The existing ADR-0070 sign-in/sign-out/extend POSTs and the closed POST set of + [Native Entry and Administration](#native-entry-and-administration), with the + sections it names, are the only additional admitted methods, with their + closed proof/body rules. All other methods receive masked no-store 404 without bootstrap or Next method conversion. HEAD is bodyless; Node owns malformed protocol input. Adding the new form set requires atomic ingress/route/CSRF/owner qualification; acceptance @@ -229,7 +229,9 @@ server caller in `apps/web/src/server/configured-public-client.ts`. - The root exports generated types and the exact authenticated path/operation contract. `/authenticated-server` supplies the injected AccountSite method; `/administration-server` supplies the closed ADR-0078/0079 administration - operations, with no-store requests and bounded response parsing. Aggregate + operations and their later closed extensions, the ADR-0106/0107 data-request + operations and the export ticket and chunk reads among them, with no-store + requests and bounded response parsing. Aggregate versions remain canonical decimal strings through JSON, ETag and If-Match; creation preserves 201/Location and replay preserves its explicit header. The native configured caller owns credentials and the @@ -293,8 +295,10 @@ native AccountSite/session entry. The source credential, subject association, live candidate and exact host ceiling follow Security 11. Public wrappers remain anonymous; no browser-controlled header, cookie or hidden field selects authority. -The P03-3 additional native POST set is below; ADR-0093 extends it only with the -[invitation form set](#verified-invitation-experience). +The P03-3 additional native POST set is below; ADR-0093 extends it with the +[invitation form set](#verified-invitation-experience), ADR-0099 with the +[federation forms](#tenant-federation) and ADR-0106 with the +[data-request forms](#subject-data-requests). | Path | Fixed operation | |---|---| @@ -329,8 +333,9 @@ closed switch operation. The P03-3 protected document set is `/studio`, `/studio/members`, `/studio/members/{MembershipId}`, `/studio/roles`, `/studio/roles/{RoleId}`, `/portal` and `/portal/profile`, with canonical resource IDs. Only member-list -GET in that set accepts cursor/limit; the invitation documents below extend the -set. Exact route/query/history censuses reject alternatives. +GET in that set accepts cursor/limit; the invitation documents below and the +[data-request documents](#subject-data-requests) extend the set. Exact +route/query/history censuses reject alternatives. An actual native-captured `RSC: 1` request may additionally carry one nonblank safe-ASCII `_rsc` transport value of at most 128 characters. Remove only that field for route-query validation; keep the signed raw target and the native @@ -1214,3 +1219,135 @@ idempotency key. A secret is never prefilled, echoed into a recovery document or retried. Refusals and unsettled outcomes (failed, uncertain, drift, expired, superseded) render a localized explanation and a link back to the page; nothing is resubmitted, and Resume settles an uncertain write. + +## Subject data requests + +**Derives from:** +[ADR-0106](../decisions/0106-subject-data-requests-authority-and-status.md) §§ 9–11 and +[ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) §§ 4, 6 +and 7; the administrator surface from ADR-0106 §§ 3, 6 and 13 and the +[ADR-0079](../decisions/0079-bounded-identity-administration.md) form rules. The +[Phase 03 Status](../roadmap/phase-03-identity-admin.md) owns qualification. + +`GET /account/data` is a fixed native document served before Next, like the consent +entry, with no public-site bootstrap. Its owner selects its mode and the browser selects +none: a live `__Host-ls-entry` owner serves the retained own scope of ADR-0106 § 9 (the +person's retained groups, then one named group); otherwise a live session serves its own +context's group. No tenant, organization, credential or owner comes from the browser; a +retained group (`tenant` or an organization UUIDv7) is proved by the API for the entry +owner on every operation. The document lists the requests with their closed status, +dates, next step and retained kinds, offers the filings, and shows the erasure and +closure confirmations as GET steps of their own. Continuation cursors are sealed to the +owner and purpose. The data-request forms join the closed POST set: + +| Path | Operation | +|---|---| +| `/api/account/data-requests/export` | Own export | +| `/api/account/data-requests/erasure` | Own erasure, with a required confirmation | +| `/api/account/data-requests/closure` | Own account closure, with two required confirmations | +| `/api/account/data-requests/cancel` | Cancel a request at its version | +| `/api/account/data-requests/revoke` | Delete an available export at its artifact version | +| `/api/account/data-requests/download` | Mint a ticket and relay the export | +| `/api/auth/entry/data-requests` | View one retained group | +| `/api/auth/entry/data-requests/{export,erasure,closure,cancel,revoke,download}` | The same in that group, on the entry owner | + +Each form carries the owner's CSRF proof and the exact Origin, strict single-valued +fields and, when keyed, a fresh opaque idempotency key; a confirmation the server does +not find refuses before the API. Success is a 303 to the fixed GET with a closed +`result`. A refusal is a no-store document with one localized sentence for each API +reason (`errors.$` or `errors.artifact`), a generic sentence for an unknown reason, and +its own sentence for an unconfirmed outcome; nothing is retried or replayed. Its way +back never repeats a submitted group: it is the fixed page (in the session mode a +refused confirmation's own step) and the mode's exit, account entry or portal. The one +nonce-bound history guard veils a leaving or restored document and returns to +`/account/data`, or from a retained group's document to that group's +`/account/data?group=` page, never to a result, step or cursor. The copy is +`i18n/messages/{en,tr}/data.json`, a closed key set that native startup refuses when +incomplete, parameterized or marked up. + +[Security](11-security.md#retained-consent-subject-admission) owns the owner rules: +which owner serves a document, the fallback from a stale entry, the pin to the +owner's life and the ticket's confinement. A retained document states the instant its +entry ends. The language follows `Accept-Language` alone in both modes, Turkish when +the first range is Turkish and English otherwise, as the consent entry decides, and +the stylesheet is fixed and neutral: the document reads no site, branding or +Membership preference. It is served without the public-site bootstrap, so no site or +theme read stands between a person and their data request, and a retained person's +Membership may have ended and carry no preference; the protected pages' preferred +locale and tenant theme therefore do not apply to it. + +**Download.** The POST mints a ticket and proves the first chunk (index, count, exact +size) before it answers one `attachment` with the bundle's +`application/json; charset=utf-8`, the exact `Content-Length`, `no-store` and a sandbox +policy. It relays one chunk at a time, each after the previous write settled, and +zeroes each decoded buffer; the native transport zeroes the response bytes it read. A +refused ticket or first chunk is an ordinary refusal document; any later failure +destroys the connection, so a short body never completes. Nothing outlives the +relay's deadline: the ticket's expiry, fifteen minutes, or the end of the owner the +response is pinned to, whichever is first. The retained entry's owner ends five +minutes after its sign-in began and is never extended: the document states that +instant once, and the download and the confirmation steps each say they must finish +before it. The ticket stays inside the relay: never in a URL, header, page or log. + +- **Resume.** The API answers every chunk refusal with the same `404`: a refreshed + credential ends the ticket, and a chunk the API cannot open answers alike. Any `404` + mints a new ticket and resumes at the failed index, at most twice per download. Each + mint counts against the + [ticket bounds](../modules/identity/README.md#subject-data-request-api-p03-10-step-1) + (three open per session binding until consumed or expired, twenty per artifact). A + chunk whose ciphertext fails to open therefore leaves three open tickets after one + download, and the person's next attempt within 15 minutes is refused as the ticket + limit; a key that left the ring refuses the renewal itself + (`data_export_unavailable`). +- **Pause.** Every chunk read is one API request under the admission budget of + [ADR-0064](../decisions/0064-tenant-api-authentication-boundary.md): 60 a minute per + visitor and 600 per physical peer, which for the BFF is the BFF node. A bundle above + about 7.5 MiB therefore meets `429`. A `429`, or a `503` that names its + `Retry-After`, is a pause, not a failure: the relay waits the advertised seconds (at + least one, at most 60, five when a `429` names none) and repeats the same call. A + chunk read keeps its index and its ticket, which a refusal at admission or a + rolled-back read did not consume; a renewal is minted again. A pause spends no + resume. A pause that would reach the deadline is not taken, and before the headers + the first chunk must start within one minute, so the person gets the refusal + document rather than a long wait. +- **Stall.** A write or the end that makes no progress for 60 seconds, or is still + pending at the deadline, destroys the connection like any failure after the headers: + a client that stops reading holds no snapshot credit or plaintext beyond it. + +**Administrator surface.** `/studio/data-requests` (only an opaque `cursor`, a fixed +page of 20), `/studio/data-requests/{RequestId}` (only a closed `result`) and +`/studio/data-requests/erasure` (only one canonical `membership`; without it the page +offers no form) are protected Studio documents shown to holders of the advisory +`canManageMemberships` capability and denied before any data-request read without it; +the API authorizes every operation. They list the context group's exports and erasures, +never a closure or a bundle. A receipt names its subject only by Membership, so the list +reads a member detail exactly as the member page does and keeps only what the member +list shows (name, status, branch or institution). The audited reads are bounded: at most +one per distinct first frozen Membership of the page's 20 requests, four at a time, and +none for a subject known to be Revoked (an administrator's erasure, or an erasure +awaiting the operator or completed), whose read the API refuses and records as a denial; +that subject is labelled as revoked, with no link. A Membership another request's read +already named names its request too. A session failure or cancellation fails the page; a +`429`, a `5xx` or a transport failure only stops the further reads and leaves the rest +unnamed, and the member page's own list degrades the same way. + +The member page adds that member's requests in the exact group and the export filing for +that Membership. A member page exists only for an Active or Suspended Membership, so a +successful revocation answers a 303 to the erasure page of that Membership instead. That +page reads nothing about the Membership: it states that the membership was revoked, what +is erased and what is kept, the 24-hour window and that the person may cancel, and holds +the confirmed erasure form; its refusals recover to it. A Membership revoked earlier is +reached by the same address with its identifier. A result notice and the title prefix +show only while the request is still in the state the result describes. The erasure +page, and the forms that join the closed POST set under the administration form rules: + +| Path | Operation | +|---|---| +| `/studio/data-requests/erasure?membership={MembershipId}` | GET: the erasure page of a Revoked Membership, which reads nothing about it | +| `/api/studio/data-request-export` | Export for a Membership of the group, from the member page | +| `/api/studio/data-request-erasure` | Erasure for a Revoked Membership, from the erasure page, with a required confirmation | +| `/api/studio/data-request-cancel` | Cancel a request the caller filed, at the request version | +| `/api/studio/data-request-revoke` | Delete the file of an export the caller filed, at the artifact version | + +A closed refusal (`errors.$` or `errors.artifact`) renders its own sentence and offers +no retry; success is a 303 to the request's page with a closed `result`. diff --git a/docs/standards/10-observability.md b/docs/standards/10-observability.md index 2630d9e87..7ad1dc60a 100644 --- a/docs/standards/10-observability.md +++ b/docs/standards/10-observability.md @@ -480,6 +480,7 @@ backend treat business rejections as system failures. | `learnstack_platform_operator_results_total` | counter | operation | | `learnstack_platform_operator_federation_total` | counter | operation (`platform.federation.report`, `platform.federation.remove`, `platform.federation.disable`), outcome (a report's `ok`, `invalid_cursor`, `unavailable`; an act's `applied`, `already_applied`, `not_found`, `not_owned`, `live_connection`, `not_applicable`, `refused`, `unavailable`, `uncertain`; [runbook](../runbooks/federation-operator.md#signals)) | | `learnstack_platform_operator_recoveries_total` | counter | operation (`platform.delivery.replay`, `platform.delivery.reset`), outcome (`applied`, `stale_fence`, `not_recoverable`, `not_found`, `unavailable`, `commit_unknown`; [runbook](../runbooks/operator-recovery.md#signals)) | +| `learnstack_platform_operator_data_requests_total` | counter | operation (`platform.data_request.inspect`, `audit.redaction.apply`, `platform.closure.begin`, `platform.closure.finalize`, `identity.data_request.fan_out_closure`), outcome (an inspection's `ok`, `invalid_cursor`; a completion's `completed`, `already_completed`, `not_found`, `not_erasure`, `closure_fanout`, `not_awaiting`; a closure Begin's `begun`, `begun_partial`, `resumed`, `resumed_partial`, `blocked_window`, `blocked_hold`, `blocked_last_administrator`, `refused_too_large`, `refused_provider`, `not_found`, `not_closure`, `not_beginnable`, `account_closed`; a closure Finalize's `finalized`, `already_finalized`, `not_found`, `not_closure`, `not_finalizable`, `groups_pending`, `provider_refused`, `provider_unavailable`, `provider_uncertain`; each's `audit_unavailable`, `unavailable` and `failed` (an unexpected failure, answered 500), and a completion's, a Begin's or a Finalize's `commit_unknown`; one per participant group of a closure's fan-out, `fan_out_started`, `fan_out_adopted`, `fan_out_waiting` or `fan_out_failed`; runbooks [data erasure](../runbooks/data-erasure.md#signals) and [account closure](../runbooks/account-closure.md#signals)) | | `learnstack_platform_operator_audit_failures_total` | counter | operation | | `learnstack_platform_operator_metadata_failures_total` | counter | none | | `learnstack_identity_rebind_runs_total` | counter | outcome (`applied`, `already_applied`, `unknown`, or a `refused_` class; [runbook](../runbooks/identity-issuer-rebind.md#when-it-refuses)) | @@ -527,6 +528,26 @@ backend treat business rejections as system failures. | `learnstack_identity_lock_refusals_total` | counter | `lock_kind`, `reason` | | `learnstack_entitlement_source_total` | counter | `source` | | `learnstack_entitlement_unresolved_total` | counter | — | +| `learnstack_data_export_total` | counter | outcome (`completed`, `failed_too_large`, `noop`, `failed`) | +| `learnstack_data_export_duration_seconds` | histogram | outcome | +| `learnstack_data_export_bundle_bytes` | histogram | — | +| `learnstack_data_export_truncations_total` | counter | — | +| `learnstack_data_export_purges_total` | counter | outcome (`purged`, `noop`, `not_due`, `failed`) | +| `learnstack_data_export_downloads_total` | counter | operation (`mint`, `chunk`), outcome (`served`, `refused`, `limit`, `custody_failed`) | + +### Data export signals + +[ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) § 2–§ 4's +export and purge jobs record five of the `learnstack_data_export_*` instruments above on +the `learnstack.data_export` meter, and the ticket mint and chunk read record the +sixth, the download counter. Each outcome is the one the handler reached inside its +transaction (a commit that then fails is the job runtime's own signal, or the request's +`503`); a failed attempt is counted `failed`, and a run its host cancelled is not +counted. Each job run also writes one line (events 7501–7507): the request or artifact +identifier, the kind, the closed outcome, the byte and chunk counts and the duration, +and for a failed export or purge attempt only the exception's type name. No subject, +group, section content, address or other person's identifier is a label or a log +value. ### Identity lock signals diff --git a/docs/standards/11-security.md b/docs/standards/11-security.md index d5b94c2a4..e38a52664 100644 --- a/docs/standards/11-security.md +++ b/docs/standards/11-security.md @@ -185,7 +185,11 @@ LearnStack runs **two Keycloak realms** per credential is an operator-supplied `view-users` client for the new realm, created for the run and deleted after it; it is not a LearnStack runtime or federation credential, and [ADR-0099](../decisions/0099-confined-tenant-federation.md)'s refusal - of user-level authority for LearnStack is unaffected. + of user-level authority for the federation credential is unaffected. The one LearnStack + runtime credential with user-level authority is the account-removal client of + [ADR-0107 § 7](../decisions/0107-data-request-fulfillment-and-account-closure.md), held + by the closure's Finalize alone + ([Standard 20](20-infrastructure-stack.md#confined-account-removal-adapter)). General rules: @@ -768,24 +772,24 @@ 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. -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 -discovery reader; their source bounds are in the -[owner census](#owner-and-setter-census). ADR-0077's confined evidence methods and -ADR-0080's scope-only enable/clear sites do not add logical Tenant setters. The set -is closed +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 discovery reader; their source +bounds are in the [owner census](#owner-and-setter-census). ADR-0077's confined evidence +methods and ADR-0080's scope-only enable/clear sites do not add logical Tenant setters. +The set is closed ([ADR-0040 § Who sets `app.tenant_id`, completely](../decisions/0040-ambient-unit-of-work.md), -with its dated Amendments, is the authority; it is reproduced here because this -section is the placement authority). Two set it on the **ambient** transaction; -eight own a **short transaction of their own** under their exact source contract; -ADR-0093 adds one **operation-bound invitation witness** setter and ADR-0095 -one **operation-bound consent-subject witness** setter. Both use the existing -physical unit-of-work writer with the exact operation mode below: +with its dated Amendments, is the authority; it is reproduced here because this section +is the placement authority). Two set it on the **ambient** transaction; eight own a +**short transaction of their own** under their exact source contract; ADR-0093 adds one +**operation-bound invitation witness** setter and ADR-0095 one **operation-bound +consent-subject witness** setter. Both use the existing physical unit-of-work writer +with the exact operation mode below: | Setter | Transaction | Why it is not `TransactionBehavior` | |---|---|---| @@ -803,6 +807,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,9 +832,9 @@ 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 -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) +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. Because every `current_setting` read is called with its missing-OK argument (`true`) @@ -840,47 +845,46 @@ leak — but an empty result set arriving from production is an outage, so the `SET LOCAL` pair on this transaction before any command a module `DbContext` issues runs on it. -**Keyed on the transaction, not on the table**, and marked through the ambient -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 -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 -closes these implementations without adding another logical setter. Durable -idempotency activation/proof belongs to the -[phase Status block](../roadmap/phase-03-identity-admin.md). The five original raw paths, -`OrganizationScopeValidator`, -the two standalone audit writers and the two cached-projection loaders, issue raw -`NpgsqlCommand`s on connections of their own, which EF interception never sees. -The ninth and tenth use their confined common-owner announcement seams and exact -source/generation guards. The eleventh consumes its operation-bound invitation -witness through the existing physical unit-of-work writer. The preliminary -offer function owner closes before that consumer owner starts. The twelfth -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 +**Keyed on the transaction, not on the table**, and marked through the ambient 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 +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 closes these implementations +without adding another logical setter. Durable idempotency activation/proof belongs to +the [phase Status block](../roadmap/phase-03-identity-admin.md). The five original raw +paths, `OrganizationScopeValidator`, the two standalone audit writers and the two +cached-projection loaders, issue raw `NpgsqlCommand`s on connections of their own, which +EF interception never sees. The ninth and tenth use their confined common-owner +announcement seams and exact source/generation guards. The eleventh consumes its +operation-bound invitation witness through the existing physical unit-of-work writer. +The preliminary offer function owner closes before that consumer owner starts. The +twelfth 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. -`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 -announces no tenant by design, is invisible to the guard by construction rather than by a -hand-written exception. The concern the earlier wording had — that naming -`TransactionBehavior` alone would reject legitimate transport and audit writes, -and the durable idempotency store's writes on its own short transaction — is real, -and is answered by the guard reading a marker rather than a behavior's name: -a setter marks the transaction it -opens if and only if it reaches EF. The audit store's writers have landed and reach none; -the durable idempotency store must mark its own whenever it does. It throws +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 announces no tenant by +design, is invisible to the guard by construction rather than by a hand-written +exception. The concern the earlier wording had — that naming `TransactionBehavior` alone +would reject legitimate transport and audit writes, and the durable idempotency store's +writes on its own short transaction — is real, and is answered by the guard reading a +marker rather than a behavior's name: a setter marks the transaction it opens if and +only if it reaches EF. The audit store's writers have landed and reach none; the durable +idempotency store must mark its own whenever it does. It throws `TenantContextMissingException` when it has not, which [`Tenant_Context_Guard_Fires_Only_On_An_Unmarked_Transaction`](21-architecture-tests-catalogue.md) -asserts in both directions. **Packet 7 owns it**: Packet 6 ships -the setter (`IUnitOfWork.SetTenantContextAsync`) and the policies it will back up, and -the first tenant-owned read on a request path is Packet 7's, which is where the guard -belongs. It cannot be a connection-checkout interceptor, for the same reason it cannot be -a `DbConnectionInterceptor` that *sets* the values: checkout precedes the transaction, so +asserts in both directions. **Packet 7 owns it**: Packet 6 ships the setter +(`IUnitOfWork.SetTenantContextAsync`) and the policies it will back up, and the first +tenant-owned read on a request path is Packet 7's, which is where the guard belongs. It +cannot be a connection-checkout interceptor, for the same reason it cannot be a +`DbConnectionInterceptor` that *sets* the values: checkout precedes the transaction, so the transaction-local value is not there to be observed ([05-database.md § Connection Management](05-database.md)). @@ -1950,6 +1954,49 @@ 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 nine operations (list, export, erasure and account-closure creation, cancel, revoke, +ticket, chunk, and the discovery of the person's groups) under +`/api/v1/identity/data-request-entry/`; the closure creation is +[ADR-0107 § 7](../decisions/0107-data-request-fulfillment-and-account-closure.md)'s +filing by the person alone. 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. A filing admitted while the person +was Active whose transaction takes the subject's User fence only after a closure's Begin +committed stores nothing: the request guard reads the User status under that fence, and +the creation answers `lockey_subject_not_admitted`. 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. + +The native `/account/data` document and its closed POSTs +([ADR-0106](../decisions/0106-subject-data-requests-authority-and-status.md) § 9, +[ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) § 4, +[Frontend Architecture § Subject data requests](07-frontend-architecture.md#subject-data-requests)) +have exactly two owners. A document prefers a live `__Host-ls-entry` owner and falls +back to the live session's owner only when the entry is absent, revoked or expired; +any other owner failure is the answer. A POST names its owner by its path, the entry +under `/api/auth/entry/data-requests` and the session under +`/api/account/data-requests/`, and never falls back. The response is pinned to that +owner for at most its remaining life, the entry's fixed deadline (at most five minutes +from the start of sign-in, never extended) or the session's effective expiry, and holds +one snapshot credit from the first read to the last byte, a download's ticket mint and +every chunk included. The export ticket stays inside the BFF's download relay: it never +appears in a URL, header, page, form or log. As for the consent entry, no branding or +public configuration read is admitted, and every POST proves the exact Origin and the +owner's CSRF token before any API work. + 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/12-infrastructure.md b/docs/standards/12-infrastructure.md index d30550bf1..a4379c22a 100644 --- a/docs/standards/12-infrastructure.md +++ b/docs/standards/12-infrastructure.md @@ -297,12 +297,14 @@ See [10-observability.md](10-observability.md). - P02b-6's development realm uses `KEYCLOAK_WEB_CLIENT_SECRET` as a private import/reconciliation source and the enabled P02b-7 native BFF runtime source. Never pass it or Keycloak admin credentials to the API, public-only process or - .NET Seeder. The API receives exactly two machine-client secrets of its own: - `IdentityEvents__ClientSecret` ([ADR-0097](../decisions/0097-retained-provider-events-and-tenant-audit-mirror.md)) - and `Federation__ClientSecret`, the value of the realm's - `KEYCLOAK_FEDERATION_ADMIN_SECRET` ([ADR-0099](../decisions/0099-confined-tenant-federation.md)); - neither is a web, master or admin credential, and neither reaches the web process - or the Seeder. Existing confidential secrets are verified, never silently + .NET Seeder. The API receives exactly three machine-client secrets of its own: + `IdentityEvents__ClientSecret` ([ADR-0097](../decisions/0097-retained-provider-events-and-tenant-audit-mirror.md)), + `Federation__ClientSecret`, the value of the realm's + `KEYCLOAK_FEDERATION_ADMIN_SECRET` ([ADR-0099](../decisions/0099-confined-tenant-federation.md)), + and `AccountRemoval__ClientSecret`, the value of the realm's + `KEYCLOAK_ACCOUNT_REMOVAL_SECRET` ([ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) + § 7, [runbook](../runbooks/account-removal-client.md)); none is a web, master or admin + credential, and none reaches the web process or the Seeder. Existing confidential secrets are verified, never silently rotated. The [accepted package](../roadmap/phase-02b-delivery-log.md#p02b-6-decision-package-2026-10-20) owns bounded tooling, selected-target validation and the no-credential-output contract; the [realm guide](../../infra/keycloak/README.md) owns local setup. diff --git a/docs/standards/18-audit-coverage.md b/docs/standards/18-audit-coverage.md index fbd4c50ad..a842323b8 100644 --- a/docs/standards/18-audit-coverage.md +++ b/docs/standards/18-audit-coverage.md @@ -248,7 +248,28 @@ will raise them — which this standard requires it to do. scope handle's checkpoint, with the outcome `indeterminate`, committed before the provider call ([ADR-0044 Amendment 18](../decisions/0044-audit-write-path.md)), and a completion row on their own slug. Both rows name the tenant the owner marker names - and carry no ticket and no tenant-authored text. + and carry no ticket and no tenant-authored text. The operator data-request + operations of [ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) + § 8 and [ADR-0108](../decisions/0108-privileged-audit-redaction.md) are `(off-path)` + too: `platform.data_request.inspect` is audited by the platform scope's entry row, + and `audit.redaction.apply` writes one result row under the request's real tenant, + with no actor, no ticket and the operator attribution in `metadata`, on the + transaction that redacts the audit rows and completes the request. A global account + closure's acts are `(off-path)` in the same way, and their rows name the platform + sentinel tenant and so carry the ticket: `platform.closure.begin` writes one result + row for a Begin or a refusal it records, and none for a repeat that changes nothing + or a refusal it does not record (a closure past its bounds, or one the provider's + port could never finish), whose entry row is its record, and + `platform.closure.finalize` writes an intent row on + `platform.closure.finalize_attempt` at the scope handle's checkpoint, on the + transaction that redacted the person's audit rows in every participant tenant and the + sentinel tenant, and then its result row + ([ADR-0108](../decisions/0108-privileged-audit-redaction.md) § 8). Every Finalize + attempt that reaches the checkpoint writes its own intent row, a repeat's included, + and unless a fault stops it a result row whose closed `outcome` says how it ended: + `finalized`, a stop at the provider, a group found pending again under the second + transaction's fences, or another call's finalization found. A Finalize refused before + the checkpoint, and a repeat of one that landed, writes only its entry row. ## Baseline Coverage (LearnStack Core Modules) @@ -700,6 +721,14 @@ the HTTP, seed, integration-delivery and job authorization sources remain unchan separate. Account history is not evidence of a login in a particular tenant. - The central MUST write and inbox/delivery completion share the business transaction. Duplicate deliveries cannot create another successful observation. +- A delivery whose affected person's User is no longer Active refuses the person + ([ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) §§ 7, + 9): the Identity fact reader reports the status from a confined definer under the + person's User fence, and the subscriber, with the evidence it alone mints, calls + `AuditStateCapture.WithholdProviderEvent`, which withdraws that invocation's one + unclaimed, still-pending observation intent. No row names a closing or closed person; + the delivery completes with its inbox row as a recorded no-op, never a failure, and a + replay runs the same rule. No other intent or operation can be withheld. - Global admission receipts are operational records, not global Audit rows. Tenant targets, delivery envelopes and Audit retain their independent replay/ retention dependencies; expiry of global receipts does not erase those links. @@ -1028,8 +1057,8 @@ observes neither a rollback nor a `42501`. - [`AuditEntry_Inherits_Entity_Not_AuditableEntity`](21-architecture-tests-catalogue.md#auditentry_inherits_entity_not_auditableentity) — the audit aggregate is append-only by inheritance. - [`AuditEntry_Is_AppendOnly`](21-architecture-tests-catalogue.md#auditentry_is_appendonly) - — no `UPDATE` or `DELETE` targets `audit_log` outside the three named sites, and - `IAuditStore` exposes no update method. + — no `UPDATE` or `DELETE` targets `audit_log` outside its one named site, the + redaction executor, and `IAuditStore` exposes no update method. - [`OperationType_Enum_Matches_Catalog`](21-architecture-tests-catalogue.md#operationtype_enum_matches_catalog) — the enum and § Operation Types carry the same seven members. - [`Every_Shipped_Request_Is_Registered`](21-architecture-tests-catalogue.md#every_shipped_request_is_registered) diff --git a/docs/standards/19-permissions.md b/docs/standards/19-permissions.md index 1268a56bd..dbea49aea 100644 --- a/docs/standards/19-permissions.md +++ b/docs/standards/19-permissions.md @@ -92,7 +92,7 @@ nonempty foundation registry. | Scope | Examples | Granted to | |-------|----------|------------| -| **Platform** | `platform.killswitch.write`, `platform.tenant.write`, `platform.tenant_bootstrap.write`, `platform.identity_authority.admin`, `platform.delivery.read`, `platform.delivery.write`, `platform.federation.read` and `platform.federation.admin` (registered); the rest of the [ADR-0101 § 5](../decisions/0101-platform-operator-authority.md) catalogue joins with the step that ships the operation using it, never ahead of it | Only platform admins / Hub operators; never assignable to a tenant role. | +| **Platform** | `platform.killswitch.write`, `platform.tenant.write`, `platform.tenant_bootstrap.write`, `platform.identity_authority.admin`, `platform.delivery.read`, `platform.delivery.write`, `platform.federation.read`, `platform.federation.admin`, `platform.data_request.read` and `platform.data_request.write` (registered); the rest of the [ADR-0101 § 5](../decisions/0101-platform-operator-authority.md) catalogue joins with the step that ships the operation using it, never ahead of it | Only platform admins / Hub operators; never assignable to a tenant role. | | **Tenant** | `education.course.write`, `enrollment.course_access.read`, `tenancy.organization.write`, `customization.content_type.write` | Tenant roles; permission check requires a `Membership` in the target tenant. | | **Organization** | `education.course.write` (org-scoped role), `enrollment.enrollment.write` (org-scoped role) | Organization-capability templates assigned to an eligible Membership for the resource's exact organization; Tenant grants are separately evaluated. | @@ -111,6 +111,8 @@ not change when it grows ([ADR-0101](../decisions/0101-platform-operator-authori | `platform.delivery.write` | `platform.delivery.replay`, `platform.delivery.reset` (the two fenced transitions, on the dispatcher's outbox role) | P03-9 Step 4 | | `platform.federation.read` | `platform.federation.report` (the report of orphaned, unreadable and nonconforming identity-provider brokers, in the platform scope) | P03-9 Step 5 | | `platform.federation.admin` | `platform.federation.remove`, `platform.federation.disable` (the two provider changes, each with an intent and a completion row) | P03-9 Step 5 | +| `platform.data_request.read` | `platform.data_request.inspect` (the metadata-only inspection of data requests awaiting an operator step, overdue, stuck, and of unpurged expired export artifacts, in the platform scope) | P03-10 Step 2 | +| `platform.data_request.write` | `audit.redaction.apply` (the completion of an erasure's privileged step: the audit redaction, the request's completion and the result row in one platform transaction, [ADR-0108](../decisions/0108-privileged-audit-redaction.md)); `platform.closure.begin` and `platform.closure.finalize` (a global account closure's Begin, and its Finalize, whose intent row `platform.closure.finalize_attempt` commits with the audit redaction before the provider account is removed, [ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) § 7); `identity.data_request.fan_out_closure` (a closure's per-group pipeline act, one admission per participant group, the one operator act announced for a group's organization, [ADR-0102](../decisions/0102-production-tenant-onboarding.md) Amendment 2) | P03-10 Steps 2 and 3 | The five onboarding acts of [ADR-0102](../decisions/0102-production-tenant-onboarding.md) run under the @@ -659,6 +661,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/20-infrastructure-stack.md b/docs/standards/20-infrastructure-stack.md index 190e48054..128a061c5 100644 --- a/docs/standards/20-infrastructure-stack.md +++ b/docs/standards/20-infrastructure-stack.md @@ -499,6 +499,37 @@ the admitted calls, profile and egress rules; the [realm runbook](../../infra/keycloak/README.md#federation-administration-client) owns the client, the realm invariants and recovery. +### Confined account-removal adapter + +**Derives from:** [ADR-0107 § 7](../decisions/0107-data-request-fulfillment-and-account-closure.md). + +`IIdentityProviderAccountRemoval` has one deleting method and a pure preflight check +(`CanRemove`, which Begin asks before it moves anyone), deletes one person's +identity-provider account, and has one caller of the deletion: the closure's Finalize, whose one call of the method an +architecture rule pins. Its default, +`RefusingIdentityProviderAccountRemoval`, refuses every call without a network effect; +the internal `KeycloakAccountRemoval` in +`LearnStack.Infrastructure.Identity.AccountRemoval` replaces it at the API composition +root only when the `learnstack-account-removal` secret (`AccountRemoval:ClientSecret`) +is configured. The client holds `manage-users`, which can also create and update users +and reset credentials in the shared realm, so the adapter builds two routes (the token +endpoint and `users/{id}` for a canonical UUID), sends two verbs (the token POST and the +deletion DELETE), and keeps the subject and the secret out of every log, audit row and +exception message. A refusal logs one closed reason code at Warning (event 7125) and +nothing else of the call; the [runbook](../runbooks/account-removal-client.md) lists the +codes. A `404` is absence only when it carries the provider's own JSON type, so a hop +in front of the provider cannot make a closure finish. Its resilience is +`IProviderResilience` from `Resilience:accountRemoval`: +no retry, because the closure's Finalize is the repeatable retry and a repeat inside +the pipeline would hide a lost answer; the timeout is 5 s and the adapter's own +cancellation sits one second later, so that the breaker records the timeout; the +circuit breaker is on within the federation adapter's ranges and the bulkhead is +exactly 1 without a queue. These values are fixed: the composition root refuses any +other value at startup. The [provider specification](../modules/identity/providers.md#account-removal-adapter) +owns the call, answer and token rules, and the +[runbook](../runbooks/account-removal-client.md) owns the client, its blast radius, +rotation and leak response. + ## APISIX Gateway - APISIX runs in **standalone mode** (YAML hot-reload, no etcd) per ADR-0015. diff --git a/docs/standards/21-architecture-tests-catalogue.md b/docs/standards/21-architecture-tests-catalogue.md index f42b9b1aa..8c9ef554f 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 +**424 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 +**309 rules in this catalogue are Implemented, and 190 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. @@ -2734,6 +2734,63 @@ Implemented requires nonempty production subjects and dirty/clean controls. command-path measurement. Current qualification/review state lives in the [phase Status block](../roadmap/phase-03-identity-admin.md). - **Phase:** P03-1 Step 4. +- **Note:** the global account closure's acquirer on the platform connection is not + this census's subject; it has its own leg, + [the closure fences rule](#the_closure_fences_are_taken_by_one_platform_acquirer_user_first_then_each_tenant_ascending_for_the_transaction). + +#### `The_Closure_Fences_Are_Taken_By_One_Platform_Acquirer_User_First_Then_Each_Tenant_Ascending_For_The_Transaction` + +- **Asserts:** in the production IL, the methods that derive both a User and a Tenant + identity lock key are exactly `IdentityMutationLocks.AcquireAsync` and + `PlatformIdentityFences.AcquireCoreAsync`, the one body of the acquirer's two forms; + in the production source, the one file that names the platform scope's handle and + derives an identity lock key is the closure's acquirer; and that acquirer, read + without comments, asks the transaction's isolation once and admits only + `read committed`, bounds the transaction's waits once with a transaction-local + `lock_timeout`, takes only exclusive transaction-scoped keys, and takes in order the + isolation question, the bound, the subject's one User key, the participant read under + it, the refusal of every tenant key for the User-only form and past the closure's + bounds, the ascending tenant order and the tenant keys. +- **Why it matters:** the closure spans every tenant of the person on a connection that + announces nothing, so `IIdentityMutationLocks` cannot fence it, and the census of that + port never sees its acquirer. A second platform acquirer, an owner that takes a key + itself, a tenant key before the User key, a participant read before the User key or in + a snapshot taken before it, tenant keys for a person past the bounds, a shared or + session-level key, or an unbounded wait would break the canonical order or the + closure's witness. +- **Source:** + [ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) § 7; + [Database Standards § The closure's fences](05-database.md#the-closures-fences). +- **Type:** xUnit — IL caller census, source scan, and eleven planted departures + (`The_Acquirer_Census_Finds_A_Planted_Departure`); the behaviour is proven on + PostgreSQL by `AccountClosureBeginTests` (the keys observed in `pg_locks` while a + Begin is held, the bounded wait, and admissions that race a Begin). **Kind:** + structural and behavioural. +- **Status:** **Implemented** (`IdentityPlatformFenceConventionTests`, P03-10 Step 3). +- **Phase:** P03-10. + +#### `The_Closure_Finalize_Takes_Its_Fences_Through_The_Acquirer_Once_In_Each_Transaction` + +- **Asserts:** the closure's Finalize part of `AccountClosureOperatorOperations`, read + without comments, calls the acquirer exactly twice, `AcquireUserAsync` once and + `AcquireAsync` once, names no advisory lock and derives no lock key, and in order + takes the User fence alone, redacts, writes its intent checkpoint, calls the + provider, takes every fence and only then moves the User to Closed. +- **Why it matters:** the first transaction moves no User and no request, so the User + key alone keeps its participant set fixed and no participant tenant's identity writes + wait for its redaction; its key ends at the checkpoint's commit, so a Finalize that + did not take every key afterwards would move the User to Closed and complete the + requests with no fence held; a Finalize that took them by hand would escape the + acquirer's census and its bounded wait. +- **Source:** + [ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) § 7; + [Database Standards § The closure's fences](05-database.md#the-closures-fences). +- **Type:** xUnit — source scan with five planted departures + (`The_Finalize_Census_Finds_A_Planted_Departure`); the behaviour is proven on + PostgreSQL by `AccountClosureFinalizeTests`, whose second transaction the `users` + trigger exception refuses without its own keys. **Kind:** structural. +- **Status:** **Implemented** (`IdentityPlatformFenceConventionTests`, P03-10 Step 3). +- **Phase:** P03-10. #### `Identity_Seed_Uses_Finite_Adopted_Manifests` @@ -3530,17 +3587,17 @@ which decides identity, multiplicity, capture and classification; the reverse, which also carries the anti-rot check and a guard against sweeping no rows at all. - **Off the request path.** Some audited operations are not MediatR requests at all. - Nine rows carry `(off-path)`: Tenancy's `platform.admin_scope.enter`, + Their rows carry `(off-path)`, among them Tenancy's `platform.admin_scope.enter`, `platform.outbox.dead_letter`, `platform.delivery.dead_letter`, - `tenancy.killswitch.toggle`, `tenancy.entitlement.refresh`, - `tenancy.tenant_assertion.reject` and `tenancy.tenant_assertion.anonymous_burst` — - snake_case within each segment since + `platform.data_request.inspect`, `tenancy.killswitch.toggle`, + `tenancy.entitlement.refresh`, `tenancy.tenant_assertion.reject` and + `tenancy.tenant_assertion.anonymous_burst` — snake_case within each segment since [ADR-0036 Amendment 7](../decisions/0036-tenant-resolution-trusted-inputs.md), so that one parser reads every audit slug and every permission key — and Audit's `audit.redaction.apply` and `audit.purge.apply`. They sit outside the request-type join - in both directions and register by slug: the four whose writer ships through - `DeclareOffPath` today, the other five — which also carry `(planned)` — when their - writer lands. ADR-0046 assigns the producer terminal writer to P02b-2 and the + in both directions and register by slug: a row whose writer ships registers through + `DeclareOffPath`, and one that also carries `(planned)` registers when its writer + lands. ADR-0046 assigns the producer terminal writer to P02b-2 and the subscriber terminal writer to P02b-3; acceptance alone registers neither slug. Stated as one unconditional join, the rule is red on its first run: the two shipped @@ -3711,23 +3768,24 @@ which decides identity, multiplicity, capture and classification; #### `Modules_Do_Not_Write_AuditLog_Directly` - **Asserts:** no module assembly **other than `LearnStack.Modules.Audit.*`** names the - `audit_log` table or the `AuditEntry` type, with one further exclusion — a module's - registered `IUserReferenceLocator`, whose column-restricted redaction `UPDATE`s are - enumerated by [`AuditEntry_Is_AppendOnly`](#auditentry_is_appendonly). `IAuditStore` — - implemented by `PostgresAuditStore` in `LearnStack.Infrastructure.Audit` — is the only - path by which a module writes an audit row of its own. Inside the Audit module, direct - `audit_log` SQL is confined to `LearnStack.Modules.Audit.Infrastructure` and bounded by - that same closed list. -- **Why the exclusions are named.** `AuditEntry`, `AuditConfig` and `AuditDbContext` live - in the Audit module ([ADR-0044 § 11](../decisions/0044-audit-write-path.md)), so a rule - reading "no module assembly, outside `LearnStack.Infrastructure.Audit`" forbade the - assembly the corpus puts the aggregate in — and contradicted the entry below, - [`AuditEntry_Is_AppendOnly`](#auditentry_is_appendonly), which names the sites where a - mutating statement may appear. The locators are the second exclusion and the one the - Audit-module wording alone would miss: each lives in the module whose snapshots carry - the user reference, so a rule bounded by `LearnStack.Modules.Audit.*` would fail on the - first locator [Phase 03](../roadmap/phase-03-identity-admin.md) lands. Naming both makes - the pair say one thing; widening the list past them requires an ADR. + `audit_log` table or the `AuditEntry` type. A module's registered + `IUserReferenceLocator` is no exclusion: it only declares where its references live + and never names the table, and the one redaction executor sits in + `LearnStack.Infrastructure.Audit`, outside every module, named by + [`AuditEntry_Is_AppendOnly`](#auditentry_is_appendonly) + ([ADR-0108 § 2, § 7](../decisions/0108-privileged-audit-redaction.md)). `IAuditStore` + — implemented by `PostgresAuditStore` in `LearnStack.Infrastructure.Audit` — is the + only path by which a module writes an audit row of its own. Inside the Audit module, + direct `audit_log` SQL is confined to `LearnStack.Modules.Audit.Infrastructure`. +- **Why the exclusion is named.** `AuditEntry`, `AuditConfig` and `AuditDbContext` live + in the Audit module ([ADR-0044 § 11](../decisions/0044-audit-write-path.md)), so a + rule reading "no module assembly, outside `LearnStack.Infrastructure.Audit`" forbade + the assembly the corpus puts the aggregate in — and contradicted the entry below, + [`AuditEntry_Is_AppendOnly`](#auditentry_is_appendonly), which names the site where a + mutating statement may appear. The locators once stood here as a second exclusion, + because the corpus had each module redact its own snapshots; ADR-0108 § 7 has them + declare paths that the Audit-owned executor applies, so no module but Audit has a + reason to name the table. Widening the exclusion requires an ADR. - **Out of scope:** `AuditEntryId` and everything in `LearnStack.SharedKernel.Audit` — the ports (`IAuditStore`, `IAuditStateCapture`, `AuditEntryDraft`, `AuditIntent`) and the value types those ports carry (`OperationType`, `OperationClass`, `AuditOutcome`, @@ -3764,18 +3822,21 @@ which decides identity, multiplicity, capture and classification; #### `AuditEntry_Is_AppendOnly` - **Asserts:** no `UPDATE` or `DELETE` statement targets `audit_log` anywhere in the - codebase or in any migration **except** at three named sites: the GDPR redaction - handler and the retention purge job, both in `LearnStack.Modules.Audit.Infrastructure`, - and a module's registered `IUserReferenceLocator`, which redacts the payload columns of - its own module's snapshots and therefore lives in that module rather than in the Audit - one ([31-audit-subsystem.md § 10](../architecture/31-audit-subsystem.md)). Every such - site must be inside an `IPlatformAdminScope` block. `IAuditStore` is asserted to expose - no update method at all. + codebase or in any migration **except** at one named site: the redaction executor, + `LearnStack.Infrastructure.Audit/AuditRedactionExecutor.cs`, which the platform scope + reaches through `IAuditRedactor` for the act it admitted and which updates the six + granted columns and never deletes + ([ADR-0108 § 2](../decisions/0108-privileged-audit-redaction.md)). Phase 11's + retention purge adds its own path when it lands. Each sanctioned site must exist and + carry the `UPDATE` it is sanctioned for, and none may carry a `DELETE`. `IAuditStore` + is asserted to expose no update method at all. - **Why the exception list is closed and named:** the earlier phrasing ("anywhere in the codebase") contradicted paths the corpus ships by design and would have failed on its - first green run. Naming the three sites keeps the rule enforceable and gives - [`Modules_Do_Not_Write_AuditLog_Directly`](#modules_do_not_write_auditlog_directly) the - same sites to exclude; widening the list requires an ADR. The database-level guard is + first green run. The list first named three sites (a redaction handler, each module's + `IUserReferenceLocator`, the purge job); ADR-0108 replaced the first two with one + Audit-owned executor that applies the locators' declarations. Naming the site keeps + the rule enforceable and makes "who can redact" a one-line census; widening the list + requires an ADR. The database-level guard is [`AuditLog_Update_Is_Column_Restricted`](#auditlog_update_is_column_restricted), which is what actually constrains *which columns* may change. - **Source:** ADR-0033 (carried from ADR-0016); @@ -3794,43 +3855,90 @@ which decides identity, multiplicity, capture and classification; operator result seam of ADR-0101 in P03-9 Step 1, the two controlled-rebind seams of ADR-0104 in P03-9 Step 3, the operator recovery seam of ADR-0103 in P03-9 Step 4 and the platform scope's intent seam of ADR-0044 Amendment 18 in P03-9 - Step 5. None - of the three sanctioned redaction sites exists yet — they land in Phase 03 and Phase - 11 — so the exemption set ships with the rule **empty**, as exact paths: the first - site to land adds its own path, so it is exempted by name rather than the pattern - widened. (A substring predicate stood there first, and exempted any Audit-module file - whose path contained "Redaction".) Since the fifth review of Packet 9 the sweep also - asserts its premise — it must have read `PostgresAuditStore`'s own `INSERT INTO - audit_log` — because with no offender anywhere, a sweep that read nothing passed as - well. + Step 5. The exemption set holds exact paths, so a site is exempted by name rather than + the pattern widened (a substring predicate stood there first, and exempted any + Audit-module file whose path contained "Redaction"); it shipped empty and holds the + redaction executor since P03-10 Step 2. The sweep also asserts that each listed path + exists and carries an `UPDATE` of the log, so an entry a rename leaves behind cannot + later exempt another file, and refuses a `DELETE` at a redaction site; its companion + feeds that pattern the shapes it must and must not catch. Since the fifth review of + Packet 9 the sweep also asserts its premise — it must have read `PostgresAuditStore`'s + own `INSERT INTO audit_log` — because with no offender anywhere, a sweep that read + nothing passed as well. - **Phase:** 02a (Packet 9). #### `Every_PII_Module_RegistersUserReferenceLocator` -- **Asserts:** every module whose audit payloads carry a user reference registers an - `IUserReferenceLocator` implementation. A module that stores such a reference and ships - no locator leaves rows a GDPR erasure cannot reach — the redaction handler redacts the - actor columns centrally and delegates the payload columns to the module that knows - which JSON paths in its own snapshots name a user - ([31-audit-subsystem.md § 10](../architecture/31-audit-subsystem.md)). -- **Registered here, asserted in Phase 03.** The - [packet plan](../roadmap/phase-03-identity-admin.md#inherited-architecture-obligations) - assigns the applicable locator census and privileged redaction handler to - P03-10. P03-1's User foundation supplies their identity prerequisite; it does - not itself deliver the erasure workflow. This refines the phase-level timing in - [ADR-0044 § What we explicitly punted on](../decisions/0044-audit-write-path.md), - without granting a redaction writer. Until that implementation there is no - locator population to count. Reserving the - name now is what [§ How to add an entry](#how-to-add-an-entry) prescribes for a rule - that is agreed and not yet written: the row carries **Registered** and the phase that - owes the code, and the alternative — a rule that lives only in an architecture - section's prose — is how a second spelling starts. -- **Source:** [31-audit-subsystem.md § 10](../architecture/31-audit-subsystem.md); - [ADR-0044 § What we explicitly punted on](../decisions/0044-audit-write-path.md). -- **Type:** xUnit + reflection over the registered locators, cross-checked against the - modules whose audit payloads carry a user reference. **Kind:** structural. -- **Status:** **Registered.** -- **Phase:** 03 — the phase that lands the interface and the handler that drives it. +- **Asserts:** every person reference the census can see in an audited entity's audit + snapshot is declared by its own module's registered `IUserReferenceLocator`, as + redactable or as an explicit retained reference, and every module that has one + registers exactly one locator from inside its own boundary + ([ADR-0107 § 1](../decisions/0107-data-request-fulfillment-and-account-closure.md), + [ADR-0108 § 7](../decisions/0108-privileged-audit-redaction.md)). The audited entities + are the declared types of the merged audit catalogue; their references are read from + each module's mapped model by CLR type (`UserId`, Identity's `MembershipId`) and, for + a reference stored as a plain `Guid` such as the consent's `[PiiSensitive]` + Membership, by a name ending in `UserId` or `MembershipId`. Every other plain `Guid` + of an audited entity or of what it contains fails as an unclassified identifier unless + it is that entity's or member's own single-column key or is on the census's explicit + allowance list of non-person identifiers, each entry with its reason (one today, the + consent's definition); every strongly typed identifier type other than the two person + kinds fails the same way unless its type is on a second allowance list (fourteen + today: the tenant, organization, role and the other identifiers the models hold, each + with its reason); an allowance no model holds fails as stale. Contained collections + are walked by the capture's own containment rule, without the foreign key to the + owner, so a member's reference is the path `Navigation/*/Property`. A person reference + fails, declared or not, where no declaration reaches it: in a member's own key, which + is a JSON object key and a `changes` path segment; in a part of an entity's composite + key, which the capture joins into `entity_id` and every `changes` path; and in a + collection of identifiers (an array or list of `UserId`, `MembershipId` or `Guid`, a + `uuid[]` included) unless it is a mapped `jsonb` array an `Elements` declaration + covers. A declaration must match a reference of the same kind (an `Elements` path + names a mapped `jsonb` property instead, because a type census cannot see inside one), + a retained reference must be the entity's whole single-column key (never a part of a + composite one), and a reference the closed grammar cannot express fails until the + grammar grows. A person reference held in a `string` or inside a `jsonb` document + other than a declared `Elements` path is invisible to the census. +- **Planted violations:** each module's locator removed in turn; a synthetic module + whose audited entities hold a typed, an untyped, a contained and an unexpressible + reference, an unclassified plain `Guid`, a collection keyed by a person, a composite + key holding a person, a `uuid[]` and a `jsonb` collection of identifiers and an + identifier type no allowance names, with no locator; the same module with a wrong + kind, a stale path, another module's entity, the declared person part of the composite + key (still refused), the declared `jsonb` collection (accepted) and a retained + reference that is not the entity's key; and a second locator in one module. Both + allowance lists are checked against the real models, so removing an entry fails the + census. +- **Canary coverage:** `AuditRedactionCanaryTests` generates, for every declaration of + every registered locator, a row in the capture's shape holding the subject's + identifier beside another person's at the declared path, runs the executor as + `learnstack_platform` and asserts exactly the subject's is redacted; its census fact + fails when a module with a locator has no canary run, and a shape its generator cannot + build fails the run. A real-capture case drives the interceptor for each shape. +- **Source:** [ADR-0108 § 7](../decisions/0108-privileged-audit-redaction.md); + [ADR-0107 § 1](../decisions/0107-data-request-fulfillment-and-account-closure.md); + [31-audit-subsystem.md § 10](../architecture/31-audit-subsystem.md). +- **Type:** model and composition-root census with planted violations, backed by the + integration canaries. **Kind:** both. +- **Status:** **Implemented** (`UserReferenceLocatorCensusTests`, P03-10 Step 2). +- **Test owners:** + [UserReferenceLocatorCensusTests.cs](../../backend/tests/LearnStack.Tests.Architecture/UserReferenceLocatorCensusTests.cs), + [AuditRedactionCanaryTests.cs](../../backend/tests/LearnStack.Tests.Integration/Database/AuditRedactionCanaryTests.cs). +- **Phase:** 03 (P03-10). + +#### `No_Module_References_Another_Modules_User_Reference_Locator` + +- **Asserts:** no module assembly references another module's locator assembly, so the + locator registrations stay outside the four cross-module mechanisms of + [ADR-0010](../decisions/0010-cross-module-communication.md), as the participants do. A + planted reference from one module to another's locator assembly is named. +- **Source:** [ADR-0108 § 7](../decisions/0108-privileged-audit-redaction.md); + [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** (`UserReferenceLocatorCensusTests`). +- **Test owners:** + [UserReferenceLocatorCensusTests.cs](../../backend/tests/LearnStack.Tests.Architecture/UserReferenceLocatorCensusTests.cs). +- **Phase:** 03 (P03-10). #### `OperationType_Enum_Matches_Catalog` @@ -5531,12 +5639,17 @@ 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 96 MVC + actions and 91 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, 37 protected keyed writes, native + session-scope admission, the eleven ADR-0099 federation actions, which reach + their requests only through `FederationOperationRunner`, the fifteen live + ADR-0106/ADR-0107 data-request actions (nine of them keyed, the person's account + closure filing among them; the ticket mint and the chunk read each sit on a + controller of their own, unkeyed), and the nine ADR-0106 § 9 retained-entry actions + on one controller (five 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 @@ -5819,8 +5932,10 @@ structural test proves — and what it does not. The EF leg bans `Organizations.Find` and `FindAsync`, which cannot express that composite key. The validator's tenant announcement and composite predicate are checked separately. -- **SQL census:** eight direct runtime SQL subjects include the validator, job - lifecycle readers, identity/self-discovery readers and the awaited +- **SQL census:** nine direct runtime SQL subjects include the validator, job + lifecycle readers, identity/self-discovery readers, the identity lifecycle reader's + platform form (many scopes in one statement on an entered platform scope's handle, + bound to its one executed call) and the awaited `OrganizationWriteStore.FindForUpdateAsync` composite-key lock followed by tenant-bound EF materialization. ADR-0047's bounded lifecycle inventory and bounds are the named enumeration exception. Two further composed page owners @@ -6062,13 +6177,60 @@ structural test proves — and what it does not. - **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 5). - **Phase:** P03-9. +#### `Only_The_Data_Request_Routes_And_Their_Owner_Name_The_Data_Request_Operator_Port_And_Only_It_Redacts` + +- **Asserts:** the files, by their path under `backend/src`, that name + `DataRequestOperatorOperations` in code (the port's name contains it, so the owner's + class is found too) are exactly the port, its one owner, the persistence composition + and the data-request routes; and the files that name the scope handle's + `RedactAuditAsync` in code are exactly the handle's interface, the scope, that owner + and the closure owner's Finalize part. Adding a caller of either is a deliberate edit + here, with its denied proof. +- **Why it matters:** the inspection reads data requests across every tenant, and the + completion is the one way any code reaches the audit log's redactable columns. The + scope also refuses the redaction at run time to every admitted operation but the + erasure completion and the closure's Finalize, and each of those two the other's + plans; this rule keeps the set of files that could ask for it closed, so a second + caller cannot appear without review. +- **Source:** + [ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) § 8; + [ADR-0108](../decisions/0108-privileged-audit-redaction.md) § 2. +- **Type:** xUnit + source scan, with a planted holder of the port, of the concrete + owner and of a redaction call, and a mention in a comment that is not counted + (`The_Data_Request_Port_Census_Finds_A_Planted_Holder_Of_The_Port_The_Owner_Or_The_Redaction`). + **Kind:** structural. +- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-10 Step 2). +- **Phase:** P03-10. + +#### `Only_The_Closure_Route_And_Its_Owner_Name_The_Closure_Operator_Port` + +- **Asserts:** the files, by their path under `backend/src`, that name + `AccountClosureOperatorOperations` in code (the port's name contains it, so the + owner's class is found too) are exactly the port, the owner's three parts (its + constructor, Begin and Finalize), the persistence composition and the closure routes' + file. Adding a caller is a deliberate edit here, with its denied proof. +- **Why it matters:** a Begin makes a person's account stop working in every tenant and + cannot be undone, and a Finalize deletes the account at the identity provider; the + operator routes, after the gate, are the one way to either. +- **Source:** + [ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) §§ 7 + and 8. +- **Type:** xUnit + source scan, with a planted holder of the port and of the concrete + owner, and a mention in a comment that is not counted. **Kind:** structural. +- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-10 Step 3). +- **Phase:** P03-10. + #### `Only_The_Operator_Services_Hold_The_Platform_Scope` - **Asserts:** the files, by their path under `backend/src`, that name - `IPlatformAdminScope` are exactly the interface, the scope, the persistence - composition and the operator services that perform an admitted act (today the - killswitch toggle, the delivery inspection and the federation owner). Adding a - service is a deliberate edit here, with its denied proof. + `IPlatformAdminScope` (the handle's name contains it) are exactly the interface, the + scope, the persistence composition and the operator services that perform an admitted + act (today the killswitch toggle, the delivery inspection, the federation owner, the + data-request owner and the account-closure owner with its Begin and Finalize parts), + and the code + that works on a handle such an owner entered and can enter none: the closure's fence + acquirer and Tenancy's lifecycle port and reader. Adding a file is a deliberate edit + here, with its denied proof. - **Why it matters:** a request handler holding the scope would enter a cross-tenant scope from a tenant request path. - **Source:** [ADR-0101](../decisions/0101-platform-operator-authority.md) § 8. @@ -6080,15 +6242,20 @@ structural test proves — and what it does not. - **Asserts:** the files, by their path under `backend/src`, that name `PlatformOperatorActExecutor` in code, comments stripped, are exactly the executor, - the registration beside the source it enters and the onboarding routes. A second - caller is a second route to an act; adding one is a deliberate edit here, with its - denied proof. + the registration beside the source it enters, the onboarding routes and the closure's + fan-out (`ClosureFanOut`), which runs one admitted `fan_out_closure` act per + participant group for Begin's owner. A second caller is a second route to an act; + adding one is a deliberate edit here, with its denied proof; the fan-out's is + `ClosureFanOutTests`' gate refusal, under which no group starts. - **Why it matters:** the executor installs a tenant context from an admission, so what may call it is what may run an operator act. The admission is the barrier, and this keeps the set of places that can spend one small and visible. -- **Source:** [ADR-0102](../decisions/0102-production-tenant-onboarding.md) § 1. +- **Source:** [ADR-0102](../decisions/0102-production-tenant-onboarding.md) § 1 and + Amendment 2, + [ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) § 7. - **Type:** xUnit + source scan. **Kind:** structural. -- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 2). +- **Status:** **Implemented** (`PlatformAdminScopeConventionTests`, P03-9 Step 2; the + fan-out joined in P03-10 Step 3). - **Phase:** P03-9. #### `Only_The_Operator_Administrator_Core_Resolves_An_Operator_Subject` @@ -6694,12 +6861,18 @@ the phase Status block owns packet state and qualification. instrumentation entries. Native preparation publishes a complete immutable page snapshot before rendering; the passive RSC facade exposes only that snapshot and its liveness assertion, never a credential, API operation or - preparation capability. The exact seven protected page views and their shared - render helpers have source-census and AST dirty controls against additional - asynchronous work, IO and framework background work, including transitive - aliases. Entry, member-list and current-scope continuations conceal upstream - cursor material and authenticate their distinct purposes. -- **Source:** ADR-0070/0071/0078/0079; Security 11 § Tenant BFF sessions and native entry. + preparation capability. The exact protected page views, which the tests below pin + and this entry does not count, and their shared render helpers have source-census + and AST dirty controls against additional asynchronous work, IO and framework + background work, including transitive aliases. Entry, member-list, + current-scope and data-request continuations conceal upstream cursor material and + authenticate their distinct purposes. The data-request download relay keeps its + export ticket inside the relay, never in a URL, header, page or log; answers one + attachment only after the first chunk proves the bundle's geometry, or a refusal + before any byte; keeps one chunk in flight, zeroes each decoded buffer, and + destroys the connection on any later failure, so a short body never completes. +- **Source:** ADR-0070/0071/0078/0079; ADR-0107 § 4; Security 11 § Tenant BFF sessions + and native entry and § Retained consent-subject admission. - **Type:** frontend source/production canaries. **Kind:** structural. - **Test owner:** `frontend/apps/web/src/test/bff-boundaries.test.ts` and `src/test/public-boundaries.test.ts`, using the production graph and AST @@ -6708,10 +6881,13 @@ the phase Status block owns packet state and qualification. `src/server/auth/store-page-preload.test.ts`. Independent development canaries live in `src/test/bff-development-diagnostics.test.ts` and `src/test/bff-development-diagnostics-counter.test.ts`; their test-owned process - controls live in `src/test/bff-proof-lifeline.test.ts`. + controls live in `src/test/bff-proof-lifeline.test.ts`. The download relay's + controls live in `src/server/auth/data-export-download.test.ts` and + `src/server/auth/native-data-request-http.test.ts`. - **Status:** **Implemented** — frontend boundary, native protocol/canary and fixture-output controls named above. -- **Phase:** P02b-7 Steps 1/3–5; P03-3 Steps 8–9 extend native entry and prepared views. +- **Phase:** P02b-7 Steps 1/3–5; P03-3 Steps 8–9 extend native entry and prepared views; + P03-10 Step 4 adds the person's data-request document and its download relay. #### `Bff_Session_Refresh_And_Revocation_Have_One_Owner` @@ -6905,9 +7081,13 @@ the phase Status block owns packet state and qualification. Role-read capability causes zero Role API calls. A legitimate missing own profile on a derived branch uses the site fallback. Failed AccountSite authority publishes only public failure data, without cached private fields or CSRF. - The exact twelve HTTP entries include seven protected views; the twelve - POST actions remain closed. Ordinary passive documents still preload without - idle/refresh writes, while HEAD and speculative prefetch avoid private preload. + The exact HTTP entry set, the protected views and the native documents among it, + and the closed POST set of Frontend Architecture § Native Entry and Administration + remain closed; nothing here counts them, the tests below pin them. Ordinary passive + documents still preload without idle/refresh writes, while HEAD and speculative + prefetch avoid private preload. Every data-request refusal reason the API documents + or emits maps to a closed localized sentence, on the person's document and on the + administrator's pages. - **Source:** ADR-0070/0078/0079; ADR-0054 dated auth extension; Security 11 § CSRF. - **Type:** native listener and actual Next route controls. **Kind:** behavioural. - **Test owner:** `frontend/apps/web/src/test/bff-auth-admission.test.ts` and @@ -6922,9 +7102,14 @@ the phase Status block owns packet state and qualification. `src/components/auth/admin-pages.test.tsx` covers explicit replacement of an unavailable stored preference through the existing native field values; the no-script browser journey exercises that required choice and verifies its POST. + The data-request forms and refusal completeness use + `src/server/auth/native-data-request-http.test.ts`, + `src/server/auth/data-request-html.test.ts` (the person) and + `src/server/auth/data-request-administration.test.ts` (the administrator). - **Status:** **Implemented** — native input/route controls above and the actual browser form/Origin and no-network startup cases in `TenantBffSessionTests`. -- **Phase:** P02b-7 Steps 3–5; P03-3 Steps 8–9 extend native forms and finite page preparation. +- **Phase:** P02b-7 Steps 3–5; P03-3 Steps 8–9 extend native forms and finite page + preparation; P03-10 Step 4 adds the data-request forms and documents. #### `Bff_Host_Cookies_And_History_Are_Isolated` @@ -6935,7 +7120,7 @@ the phase Status block owns packet state and qualification. stored provider events. Real paginated entry JSON/HTML, stock-browser next/Back URLs/history and second-page selection keep subject/authority material private; the original disclosure has a real old-source negative control. Stopped-provider - public rendering remains independent. The seven prepared protected views retain + public rendering remains independent. The prepared protected views retain native forms when JavaScript is disabled. Actual stock-browser page checks require ready views and specific visible contents; an unavailable view retaining the wrapper/h1 fails the same guard. No-script profile save/sign-out runs on both @@ -6955,10 +7140,16 @@ the phase Status block owns packet state and qualification. and `src/components/auth/session.test.tsx` cover fixed GET recovery, native forms and session/unsaved-edit behavior; `scripts/verify-bff-protocol.mjs` exercises the actual Next prepared views and `verify-bff-browser.mjs` the no-script flow. + The data-request document's guard, which restores the bare page or one retained + group's page and never a result, is covered by + `src/server/auth/data-request-html.test.ts`, + `src/server/auth/native-data-request-http.test.ts` and the observation of + `scripts/test-data-request-proof-view.mjs`. - **Status:** **Implemented** — `TenantBffSessionTests`, its real-chain/browser scripts and the stopped-provider public-demo lifecycle. - **Phase:** P02b-7 Step 5; P03-3 Step 9 extends selected views, no-script and history - controls. Phase 06 retains full browser OIDC end-to-end expansion. The Phase 03 + controls; P03-10 Step 4 adds the data-request document's guard. Phase 06 retains + full browser OIDC end-to-end expansion. The Phase 03 Status block owns current P03-3 qualification and review state. ## P02b-4 background-job obligations @@ -7677,7 +7868,11 @@ The [Phase 03 Status](../roadmap/phase-03-identity-admin.md) owns packet/proof s stable EventId through ordinary outbox/inbox and central typed Audit evidence. SystemActor differs from the affected account; provider time/result does not establish a tenant login. Duplicate/unknown commit, expired claim, closure, - overflow and Audit failure cannot duplicate, forge or silently lose success. + overflow and Audit failure cannot duplicate, forge or silently lose success. The + subscriber is the one caller of `AttachProviderEvent` and of `WithholdProviderEvent`, + which withdraws the observation of a person whose User is no longer Active + ([ADR-0107](../decisions/0107-data-request-fulfillment-and-account-closure.md) + §§ 7, 9). - **Source:** [ADR-0097](../decisions/0097-retained-provider-events-and-tenant-audit-mirror.md), [Database](05-database.md#provider-event-intake-storage). - **Type:** real app/ingress-role isolation, concurrency, transport, Audit and @@ -7902,9 +8097,9 @@ sign-in read). The `NetworkStream`, `ClientWebSocket`, `WebRequest`, `HttpWebRequest`, `WebClient`, `IHttpClientFactory`, `AddHttpClient` or a `Dns.` call) or the MailKit SMTP client (`SmtpClient`, the `MailKit` namespace) is on a named allow-list, each entry with its - reason: `FederationEgressFetcher`, the only fetcher of a tenant-supplied URL; four + reason: `FederationEgressFetcher`, the only fetcher of a tenant-supplied URL; five clients of a fixed, composition-configured tenant-realm origin - (`KeycloakFederationProvider`, `KeycloakIdentityEventProvider`, + (`KeycloakFederationProvider`, `KeycloakAccountRemoval`, `KeycloakIdentityEventProvider`, `TenantAuthenticationBackchannel`, `CurrentInvitationRecipientBackchannel`); and `SmtpEmailProvider`, the operator-configured SMTP host for invitation mail. An entry whose file no longer holds a transport fails as stale. Instrumentation, exception and @@ -7925,6 +8120,100 @@ sign-in read). The - **Test owner:** [FederationAdapterConventionTests.cs](../../backend/tests/LearnStack.Tests.Architecture/FederationAdapterConventionTests.cs). - **Phase:** 03 (P03-8 Step 3; widened to every production source in review round 1). +#### `Account_Removal_Client_Is_Held_Only_By_The_Adapter` + +- **Asserts:** the literal client identifier `learnstack-account-removal` appears in + production source only in `KeycloakAccountRemovalRoutes`, and the secret key + `AccountRemoval:ClientSecret` only in `KeycloakAccountRemoval`; every other caller + reaches the adapter through `AccountRemovalAdapterFactory`, so no other code holds the + `manage-users` client or its credential. Comments are set aside; a planted holder in + the API, the Identity Application and the federation adapter's directory is refused + and a prose-only mention is not. +- **Source:** [ADR-0107 § 7](../decisions/0107-data-request-fulfillment-and-account-closure.md#7-global-account-closure) + ("one new realm client with `manage-users`, its secret in `ISecretProvider`"). +- **Type:** source scan with planted holders. **Kind:** structural. +- **Status:** **Implemented** (`AccountRemovalAdapterConventionTests`). +- **Test owner:** [AccountRemovalAdapterConventionTests.cs](../../backend/tests/LearnStack.Tests.Architecture/AccountRemovalAdapterConventionTests.cs). +- **Phase:** 03 (P03-10 Step 3). + +#### `Account_Removal_Adapter_Admits_Only_The_Token_And_User_Routes` + +- **Asserts:** `KeycloakAccountRemovalRoutes` builds exactly two routes, the token + endpoint and `users/{id}`; no string literal in the adapter namespace names another + Admin, user, client, role, group, session, credential or flow path (the one admitted + literal is the `roles` token claim the adapter narrows), and no file but the routes and + the options builds or extends a URI. Planted routes in the directory, a planted URI + builder and a clean control are checked. The unit tests + `KeycloakAccountRemovalTests` check the same set behaviourally against a scripted + provider. +- **Source:** [ADR-0107 § 7](../decisions/0107-data-request-fulfillment-and-account-closure.md#7-global-account-closure). +- **Type:** reflection plus source scan, with planted routes. **Kind:** structural. +- **Status:** **Implemented** (`AccountRemovalAdapterConventionTests`). +- **Test owner:** [AccountRemovalAdapterConventionTests.cs](../../backend/tests/LearnStack.Tests.Architecture/AccountRemovalAdapterConventionTests.cs); + [KeycloakAccountRemovalTests.cs](../../backend/tests/LearnStack.Tests.Unit/Infrastructure/Identity/KeycloakAccountRemovalTests.cs). +- **Phase:** 03 (P03-10 Step 3). + +#### `Account_Removal_Adapter_Sends_Only_The_Token_Post_And_The_User_Delete` + +- **Asserts:** no file of the adapter namespace names an `HttpMethod` other than POST + and DELETE, constructs an `HttpMethod`, or calls a verb-named `HttpClient` helper, and + the adapter file names both admitted verbs. The client's role can also create and + update users, so a PUT, a GET or a POST to `users` is not a call this class may + contain. +- **Source:** [ADR-0107 § 7](../decisions/0107-data-request-fulfillment-and-account-closure.md#7-global-account-closure). +- **Type:** source scan with planted verbs and a clean control. **Kind:** structural. +- **Status:** **Implemented** (`AccountRemovalAdapterConventionTests`). +- **Test owner:** [AccountRemovalAdapterConventionTests.cs](../../backend/tests/LearnStack.Tests.Architecture/AccountRemovalAdapterConventionTests.cs). +- **Phase:** 03 (P03-10 Step 3). + +#### `Account_Removal_Adapter_Does_Not_Read_DeploymentMode` + +- **Asserts:** no source in `LearnStack.Infrastructure.Identity.AccountRemoval` names + `DeploymentMode`, and no field or constructor parameter of its types has that type; + the composition root alone selects the adapter and the Development loopback rule. +- **Source:** [ADR-0107 § 7](../decisions/0107-data-request-fulfillment-and-account-closure.md#7-global-account-closure), + [ADR-0020](../decisions/0020-triple-deployment-hybrid-license.md). +- **Type:** source scan and reflection, with a planted read. **Kind:** structural. +- **Status:** **Implemented** (`AccountRemovalAdapterConventionTests`). +- **Test owner:** [AccountRemovalAdapterConventionTests.cs](../../backend/tests/LearnStack.Tests.Architecture/AccountRemovalAdapterConventionTests.cs). +- **Phase:** 03 (P03-10 Step 3). + +#### `Account_Removal_Port_Has_One_Method_And_A_Closed_Set_Of_Holders` + +- **Asserts:** `IIdentityProviderAccountRemoval` declares exactly one deleting method, + `RemoveAsync`, beside one synchronous local preflight, `CanRemove`, which returns a + `bool` and so cannot reach the provider, and no property; production source names the + port, its refusing default, the adapter or its factory only in the declaration, the + default, the adapter, the factory, the API composition, the Identity foundation + registration and the closure owner's constructor file, whose Finalize is the one + caller of the deletion the ADR admits; the Finalize part calls the port through the + owner's field and names no port type. +- **Source:** [ADR-0107 § 7](../decisions/0107-data-request-fulfillment-and-account-closure.md#7-global-account-closure) + ("exactly one method" and a single caller for a `manage-users` credential). +- **Type:** reflection plus source scan with planted holders. **Kind:** structural. +- **Status:** **Implemented** (`AccountRemovalAdapterConventionTests`). +- **Test owner:** [AccountRemovalAdapterConventionTests.cs](../../backend/tests/LearnStack.Tests.Architecture/AccountRemovalAdapterConventionTests.cs). +- **Phase:** 03 (P03-10 Step 3). + +#### `Account_Removal_Port_Is_Called_Only_From_The_Closure_Finalize` + +- **Asserts:** the identifier `accountRemoval`, the closure owner's captured port, + appears in production source only in the owner's partial files (the constructor, + Begin and Finalize parts), only as the receiver of a call or in the constructor's + parameter declaration (never aliased, passed on or captured), and + `accountRemoval.RemoveAsync(` is called exactly once, in the Finalize part. The + port-holder rule above confines the files that name a port type; this one covers the + files that reach the port without naming one, which a second call in Begin would + otherwise pass. Comments and literals are set aside; planted calls in Begin, a second + and a missing call in Finalize, an alias, an argument, a capture, a method group and + a foreign file are refused, and a prose-only mention is not. +- **Source:** [ADR-0107 § 7](../decisions/0107-data-request-fulfillment-and-account-closure.md#7-global-account-closure) + (a single caller for a `manage-users` credential). +- **Type:** source scan, planted departures and a clean control. **Kind:** structural. +- **Status:** **Implemented** (`AccountRemovalAdapterConventionTests`). +- **Test owner:** [AccountRemovalAdapterConventionTests.cs](../../backend/tests/LearnStack.Tests.Architecture/AccountRemovalAdapterConventionTests.cs). +- **Phase:** 03 (P03-10 Step 3, review round 1). + #### `Federation_Host_Alias_Setter_Is_Read_Only_And_Host_Only` - **Asserts:** `FederationHostAliasReader`, the native self read's host-alias setter, @@ -7973,3 +8262,110 @@ 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. The native + retained-entry operations (P03-10 Step 1, unit 4b; the closure filing, Step 3) close + the chain: exactly nine selector-free operations and the receipt read of their five + 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; 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), + [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). + +#### `Erasure_Operations_Run_Only_Under_The_Erasure_Witness` + +- **Asserts:** the erasure operations of `Membership` (`RemoveAssignmentsForErasure`, + `ClearProfileForErasure`, `RevokeForErasure`) and `Invitation` (`RevokeForErasure`) + take a `DataErasureWitness`, which is sealed and privately constructed, captured only + from a fulfilling erasure request, and minted only by `DataErasureService`'s one + nested source; each operation has the erasure service as its one caller. A planted + extra minter and a planted extra caller are each named. The database side is the + contextual guard's one exception: a clearing UPDATE of a Revoked Membership's profile + passes only with the person's User fence and the tenant key held exclusively and the + person's erasure of that group `fulfilling` and naming that Membership in its frozen + snapshot, and each condition removed alone is refused as the application role. +- **Source:** + [ADR-0107 § 5](../decisions/0107-data-request-fulfillment-and-account-closure.md). +- **Type:** compiled minter and caller censuses with planted probes; real app-role + PostgreSQL refusals of each witness condition; domain and job behaviour end to end. + **Kind:** both. +- **Status:** **Implemented** (`DataErasureWitnessConventionTests`); companion owners + below. +- **Test owners:** + [DataErasureWitnessConventionTests.cs](../../backend/tests/LearnStack.Tests.Architecture/DataErasureWitnessConventionTests.cs), + [DataErasureGuardTests.cs](../../backend/tests/LearnStack.Tests.Integration/Database/DataErasureGuardTests.cs), + [DataErasureDomainTests.cs](../../backend/tests/LearnStack.Tests.Unit/Identity/DataErasureDomainTests.cs), + [DataErasureExecutionTests.cs](../../backend/tests/LearnStack.Tests.Integration/Database/DataErasureExecutionTests.cs). +- **Phase:** 03 (P03-10, tenant erasure). + +#### `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/scripts/bff-proof-host.mjs b/frontend/apps/web/scripts/bff-proof-host.mjs index 4b1cae08c..03c49dc1a 100644 --- a/frontend/apps/web/scripts/bff-proof-host.mjs +++ b/frontend/apps/web/scripts/bff-proof-host.mjs @@ -591,6 +591,10 @@ export async function prepareBffProof({ 'native-invitation-client', 'native-invitation-http', 'native-consent-http', + 'native-data-request-http', + 'data-request-copy', + 'data-request-html', + 'data-export-download', 'native-federation-client', 'consent-response-contract', 'custom-field-forms', @@ -622,6 +626,7 @@ export async function prepareBffProof({ join(directory, 'invitation.json'), ); cpSync(join(source, 'src/i18n/messages', locale, 'auth.json'), join(directory, 'auth.json')); + cpSync(join(source, 'src/i18n/messages', locale, 'data.json'), join(directory, 'data.json')); } if (mutation === 'activity') { const path = join(app, 'src/server/auth/request-runtime.ts'); diff --git a/frontend/apps/web/scripts/data-request-proof-view.d.mts b/frontend/apps/web/scripts/data-request-proof-view.d.mts new file mode 100644 index 000000000..8d5dfc65f --- /dev/null +++ b/frontend/apps/web/scripts/data-request-proof-view.d.mts @@ -0,0 +1,10 @@ +export type DataRequestProofView = Readonly<{ + kind: 'data_request_document'; + view: string | null; + filingForms: number; + actionForms: number; + downloadForms: number; + confirmationProtected: boolean; + historyProtected: boolean; +}>; +export function dataRequestProofView(html: string, policy?: string): DataRequestProofView; diff --git a/frontend/apps/web/scripts/data-request-proof-view.mjs b/frontend/apps/web/scripts/data-request-proof-view.mjs new file mode 100644 index 000000000..fb2fb3568 --- /dev/null +++ b/frontend/apps/web/scripts/data-request-proof-view.mjs @@ -0,0 +1,109 @@ +import assert from 'node:assert/strict'; + +const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; +const views = new Set([ + 'signin', + 'error', + 'session', + 'session_erasure', + 'session_closure', + 'entry_scopes', + 'entry', + 'entry_erasure', + 'entry_closure', +]); +const keyed = new Set(['export', 'erasure', 'closure', 'cancel', 'revoke']); +const targeted = new Set(['cancel', 'revoke', 'download']); + +/** Tiny observations of actual native HTML; no proof, key, identifier or page text leaves this projection. */ +export function dataRequestProofView(html, policy) { + assert.ok(typeof html === 'string' && Buffer.byteLength(html) <= 256 * 1024); + assert.ok(policy === undefined || (typeof policy === 'string' && policy.length <= 4096)); + const view = /]*\bdata-data-request-view="([a-z_]+)"/.exec(html)?.[1] ?? null; + assert.ok(view === null || views.has(view)); + let filingForms = 0; + let actionForms = 0; + let downloadForms = 0; + let confirmationProtected = true; + for (const form of html.matchAll(/]*)>([\s\S]*?)<\/form>/g)) { + const action = /\baction="([^"]+)"/.exec(form[1])?.[1]; + const match = /^\/api\/(?:account|auth\/entry)\/data-requests(?:\/([a-z]+))?$/.exec( + action ?? '', + ); + if (!match) continue; + assert.match(form[1], /\bmethod="post"/); + const field = (name) => [ + ...form[2].matchAll(new RegExp('\\bname="' + name + '" value="([^"]*)"', 'g')), + ]; + const name = match[1] ?? 'view'; + const entry = action.startsWith('/api/auth/entry/'); + assert.equal(field('csrfToken').length, 1); + assert.match(field('csrfToken')[0][1], /^[A-Za-z0-9_-]{43}$/); + assert.equal(field('idempotencyKey').length, keyed.has(name) ? 1 : 0); + if (keyed.has(name)) assert.match(field('idempotencyKey')[0][1], /^[A-Za-z0-9_-]{43}$/); + assert.equal(field('requestId').length, targeted.has(name) ? 1 : 0); + if (targeted.has(name)) assert.match(field('requestId')[0][1], uuid); + assert.equal(field('group').length, entry ? 1 : 0); + if (entry) assert.ok(field('group')[0][1] === 'tenant' || uuid.test(field('group')[0][1])); + if (name === 'cancel' || name === 'revoke') + assert.match(field('version')[0][1], /^(0|[1-9][0-9]{0,18})$/); + if (name === 'erasure' || name === 'closure') { + const boxes = [...form[2].matchAll(/]*)>/g)]; + const expected = + name === 'erasure' ? ['confirm:erase'] : ['confirm:close', 'acknowledge:no_status']; + confirmationProtected &&= + /
[^<]+<\/legend>/.test(form[2]) && + boxes.length === expected.length && + boxes.every( + (box, index) => + / required\b/.test(box[1]) && + box[1].includes( + 'name="' + + expected[index].split(':')[0] + + '" value="' + + expected[index].split(':')[1] + + '"', + ), + ); + } + if (name === 'download') assert.ok(++downloadForms <= 20); + else if (keyed.has(name) && name !== 'cancel' && name !== 'revoke') + assert.ok(++filingForms <= 3); + else assert.ok(++actionForms <= 40); + } + const scripts = [...html.matchAll(/]*)>([\s\S]*?)<\/script>/g)]; + const nonce = + scripts.length === 1 ? /\bnonce="([A-Za-z0-9+/]{22}==)"/.exec(scripts[0][1])?.[1] : undefined; + const script = scripts[0]?.[2] ?? ''; + const scriptPolicy = /(?:^|;)\s*script-src\s+([^;]+)/.exec(policy ?? '')?.[1]?.trim(); + // The one fixed destination: the bare page, or a retained group's page on exactly a retained group's view. No + // result, step or cursor is restored, and every restoration goes to the address the page recorded. + const destination = /history\.replaceState\(null,'','([^']*)'\)/.exec(script)?.[1]; + const group = /^\/account\/data(?:\?group=(.+))?$/.exec(destination ?? ''); + const grouped = ['entry', 'entry_erasure', 'entry_closure'].includes(view ?? ''); + const historyProtected = + nonce !== undefined && + scriptPolicy === "'nonce-" + nonce + "'" && + html.indexOf('') && + group !== null && + (group[1] === undefined + ? !grouped + : grouped && (group[1] === 'tenant' || uuid.test(group[1]))) && + script.includes("addEventListener('pagehide'") && + script.includes("addEventListener('pageshow'") && + script.includes('e.persisted||leaving') && + script.includes("document.documentElement.style.visibility='hidden'") && + script.includes("location.replace('" + destination + "')") && + script.split('location.replace(').length === + script.split("location.replace('" + destination + "')").length && + !script.includes('location.reload'); + return Object.freeze({ + kind: 'data_request_document', + view, + filingForms, + actionForms, + downloadForms, + confirmationProtected, + historyProtected, + }); +} diff --git a/frontend/apps/web/scripts/framework-proof-admission-source.mjs b/frontend/apps/web/scripts/framework-proof-admission-source.mjs index d3fb0f814..c67d168de 100644 --- a/frontend/apps/web/scripts/framework-proof-admission-source.mjs +++ b/frontend/apps/web/scripts/framework-proof-admission-source.mjs @@ -76,9 +76,11 @@ export function instrumentCopiedAdmissionRuntime(sourceText) { ? bffRequests.run(binding, request, response, () => nativeConsentTarget(binding.target) ? consentHandler(binding, request, response) - : nativeInvitationTarget(binding.target) - ? invitationHandler(binding, request, response) - : handle(request, response), + : nativeDataRequestTarget(binding.target) + ? dataRequestHandler(binding, request, response) + : nativeInvitationTarget(binding.target) + ? invitationHandler(binding, request, response) + : handle(request, response), ) : handle(request, response), ), @@ -92,9 +94,11 @@ export function instrumentCopiedAdmissionRuntime(sourceText) { ? bffRequests.run(binding, request, response, () => nativeConsentTarget(binding.target) ? consentHandler(binding, request, response) - : nativeInvitationTarget(binding.target) - ? invitationHandler(binding, request, response) - : handle(request, response)) + : nativeDataRequestTarget(binding.target) + ? dataRequestHandler(binding, request, response) + : nativeInvitationTarget(binding.target) + ? invitationHandler(binding, request, response) + : handle(request, response)) : handle(request, response); }))`, ); diff --git a/frontend/apps/web/scripts/framework-proof-relay.mjs b/frontend/apps/web/scripts/framework-proof-relay.mjs index 5f09c59af..fd6a4e47c 100644 --- a/frontend/apps/web/scripts/framework-proof-relay.mjs +++ b/frontend/apps/web/scripts/framework-proof-relay.mjs @@ -81,6 +81,31 @@ export const NATIVE_OPERATION_KINDS = Object.freeze([ 'enableFederation', 'deleteFederation', 'resumeFederationOperation', + // ADR-0106 § 9: the person's own data requests in the session group, then the retained-entry set. + 'listOwnDataRequests', + 'createOwnDataExport', + 'createOwnDataErasure', + 'createOwnAccountClosure', + 'cancelOwnDataRequest', + 'revokeOwnDataExport', + 'mintOwnDataExportTicket', + 'readOwnDataExportChunk', + 'listRetainedDataRequestScopes', + 'listRetainedDataRequests', + 'createRetainedDataExport', + 'createRetainedDataErasure', + 'createRetainedAccountClosure', + 'cancelRetainedDataRequest', + 'revokeRetainedDataExport', + 'mintRetainedDataExportTicket', + 'readRetainedDataExportChunk', + // ADR-0106 §§ 3, 13: an administrator's requests in the session group; no ticket or chunk kind. + 'listDataRequests', + 'getDataRequest', + 'createDataExportForSubject', + 'createDataErasureForSubject', + 'cancelDataRequest', + 'revokeDataExport', ]); const OPERATION_SET = new Set(NATIVE_OPERATION_KINDS); diff --git a/frontend/apps/web/scripts/public-server-runtime.mjs b/frontend/apps/web/scripts/public-server-runtime.mjs index 2a41b0059..7ac3382d6 100644 --- a/frontend/apps/web/scripts/public-server-runtime.mjs +++ b/frontend/apps/web/scripts/public-server-runtime.mjs @@ -15,6 +15,8 @@ export async function startPublicRuntime(control) { let nativeInvitationTarget; let consentHandler; let nativeConsentTarget; + let dataRequestHandler; + let nativeDataRequestTarget; let upgradeSink; let app; let server; @@ -211,7 +213,11 @@ export async function startPublicRuntime(control) { { createTenantProvider }, { createAccountSiteCaller }, { createNativeSessionApi }, - { createNativeAdministrationCaller, createNativeRetainedConsentCaller }, + { + createNativeAdministrationCaller, + createNativeRetainedConsentCaller, + createNativeRetainedDataRequestCaller, + }, { installBffSessionRuntime }, { installBffRequestRuntime }, { createNativeInvitationApi }, @@ -223,6 +229,9 @@ export async function startPublicRuntime(control) { { default: authEn }, { default: authTr }, { createNativeFederationTestApi, createPublicSignInReader }, + { createNativeDataRequestHandler, nativeDataRequestTarget: dataRequestTarget }, + { default: dataEn }, + { default: dataTr }, ] = await Promise.all([ ownSetup(import('../.server/auth/provider-core.js')), ownSetup(import('../.server/auth/account-client.js')), @@ -239,6 +248,9 @@ export async function startPublicRuntime(control) { ownSetup(import('../src/i18n/messages/en/auth.json', { with: { type: 'json' } })), ownSetup(import('../src/i18n/messages/tr/auth.json', { with: { type: 'json' } })), ownSetup(import('../.server/auth/native-federation-client.js')), + ownSetup(import('../.server/auth/native-data-request-http.js')), + ownSetup(import('../src/i18n/messages/en/data.json', { with: { type: 'json' } })), + ownSetup(import('../src/i18n/messages/tr/data.json', { with: { type: 'json' } })), ]); assertStarting(); const nativeConfiguration = { @@ -264,6 +276,10 @@ export async function startPublicRuntime(control) { native, administration, retainedConsent: createNativeRetainedConsentCaller(nativeConfiguration, globalThis.fetch), + retainedDataRequest: createNativeRetainedDataRequestCaller( + nativeConfiguration, + globalThis.fetch, + ), invitations: createNativeInvitationApi(nativeConfiguration, globalThis.fetch), // ADR-0099: the server-side sign-in option read and the BFF-only federation test owner. publicSignIn: createPublicSignInReader(configuration, globalThis.fetch), @@ -295,6 +311,12 @@ export async function startPublicRuntime(control) { } nativeInvitationTarget = invitationTarget; nativeConsentTarget = consentTarget; + nativeDataRequestTarget = dataRequestTarget; + dataRequestHandler = createNativeDataRequestHandler({ + catalogues: { en: dataEn, tr: dataTr }, + store: bffSessions.store, + responseLease: bffRequests.nativeDataRequestResponse, + }); consentHandler = createNativeConsentHandler({ catalogues: { en: authEn.consents, tr: authTr.consents }, store: bffSessions.store, @@ -360,9 +382,11 @@ export async function startPublicRuntime(control) { ? bffRequests.run(binding, request, response, () => nativeConsentTarget(binding.target) ? consentHandler(binding, request, response) - : nativeInvitationTarget(binding.target) - ? invitationHandler(binding, request, response) - : handle(request, response), + : nativeDataRequestTarget(binding.target) + ? dataRequestHandler(binding, request, response) + : nativeInvitationTarget(binding.target) + ? invitationHandler(binding, request, response) + : handle(request, response), ) : handle(request, response), ), diff --git a/frontend/apps/web/scripts/test-data-request-proof-view.mjs b/frontend/apps/web/scripts/test-data-request-proof-view.mjs new file mode 100644 index 000000000..38426abbc --- /dev/null +++ b/frontend/apps/web/scripts/test-data-request-proof-view.mjs @@ -0,0 +1,162 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { dataRequestProofView } from './data-request-proof-view.mjs'; +const id = '019a154b-0000-7000-8000-000000000041'; +const nonce = 'A'.repeat(22) + '=='; +const proof = 'P'.repeat(43); +const key = 'K'.repeat(43); +const policy = "default-src 'none'; script-src 'nonce-" + nonce + "'; form-action 'self'"; +// Independent proof subject. This contains only the security-bearing pieces the observation checks. +const guard = (destination = '/account/data') => + "history.replaceState(null,'','" + + destination + + "');addEventListener('pagehide',()=>{document.documentElement.style.visibility='hidden'});addEventListener('pageshow',e=>{if(e.persisted||leaving)location.replace('" + + destination + + "')})"; +const hidden = (name, value) => ''; +const filing = + '
' + + hidden('csrfToken', proof) + + hidden('idempotencyKey', key) + + ''; +const cancel = + '
' + + hidden('csrfToken', proof) + + hidden('idempotencyKey', key) + + hidden('requestId', id) + + hidden('version', '3') + + ''; +const download = + '
' + + hidden('csrfToken', proof) + + hidden('requestId', id) + + ''; +const erasure = + '
' + + hidden('csrfToken', proof) + + hidden('idempotencyKey', key) + + '
Confirm
'; +const page = (body, view = 'session', destination = undefined) => + '
' + + body + + '

private-request-canary

'; +test('actual form, confirmation and nonce observations remain closed and payload-free', () => { + const value = dataRequestProofView(page(filing + cancel + download), policy); + assert.deepEqual(value, { + kind: 'data_request_document', + view: 'session', + filingForms: 1, + actionForms: 1, + downloadForms: 1, + confirmationProtected: true, + historyProtected: true, + }); + for (const privateValue of [id, proof, key, 'private-request-canary', nonce]) + assert.ok(!JSON.stringify(value).includes(privateValue)); + assert.equal(Object.isFrozen(value), true); + const confirmation = dataRequestProofView(page(erasure, 'session_erasure'), policy); + assert.equal(confirmation.view, 'session_erasure'); + assert.equal(confirmation.confirmationProtected, true); + // A retained group's view restores exactly that group's fixed page; the chooser restores the bare page. + for (const group of ['tenant', id]) + assert.equal( + dataRequestProofView(page('', 'entry_closure', '/account/data?group=' + group), policy) + .historyProtected, + true, + ); + assert.equal(dataRequestProofView(page('', 'entry_scopes'), policy).historyProtected, true); +}); +test('anonymous 200 HTML cannot masquerade as a credentialed request page', () => { + assert.deepEqual( + dataRequestProofView('Sign in'), + { + kind: 'data_request_document', + view: null, + filingForms: 0, + actionForms: 0, + downloadForms: 0, + confirmationProtected: true, + historyProtected: false, + }, + ); +}); +test('wrong nonce, unrestricted script policy, removed veil, POST reload and an unchecked confirmation are visible', () => { + const html = page(filing); + assert.equal( + dataRequestProofView(html, policy.replace(nonce, 'B'.repeat(22) + '==')).historyProtected, + false, + ); + assert.equal( + dataRequestProofView(html, policy.replace("'nonce-" + nonce + "'", "'unsafe-inline'")) + .historyProtected, + false, + ); + assert.equal( + dataRequestProofView( + html.replace("document.documentElement.style.visibility='hidden'", ''), + policy, + ).historyProtected, + false, + ); + assert.equal( + dataRequestProofView( + html.replace("location.replace('/account/data')", 'location.reload()'), + policy, + ).historyProtected, + false, + ); + for (const [view, destination] of [ + ['session', '/account/data?group=tenant'], + ['entry', '/account/data'], + ['entry', '/account/data?group=tenant&result=export'], + ['entry', '/account/data?group=not-a-group'], + ['entry_scopes', '/account/data?group=tenant'], + ]) + assert.equal(dataRequestProofView(page('', view, destination), policy).historyProtected, false); + assert.equal( + dataRequestProofView( + page('', 'entry', '/account/data?group=tenant').replace( + "location.replace('/account/data?group=tenant')", + "location.replace('/account/data')", + ), + policy, + ).historyProtected, + false, + ); + assert.equal( + dataRequestProofView(page(erasure.replace(' required ', ' ')), policy).confirmationProtected, + false, + ); + assert.equal( + dataRequestProofView( + page(erasure.replace('
Confirm', '
')), + policy, + ).confirmationProtected, + false, + ); +}); +test('the observation refuses duplicate proofs, missing keys, foreign targets, extra rows and oversized HTML', () => { + assert.throws(() => + dataRequestProofView( + page(filing.replace('', hidden('csrfToken', proof) + '')), + policy, + ), + ); + assert.throws(() => + dataRequestProofView(page(cancel.replace(hidden('idempotencyKey', key), '')), policy), + ); + assert.throws(() => dataRequestProofView(page(cancel.replace(id, 'not-a-request')), policy)); + assert.throws(() => + dataRequestProofView(page(filing.replace('/api/account/', '/api/auth/entry/')), policy), + ); + assert.throws(() => dataRequestProofView(page(filing.repeat(4)), policy)); + assert.throws(() => dataRequestProofView(page(filing, 'studio'), policy)); + assert.throws(() => dataRequestProofView('x'.repeat(256 * 1024 + 1), policy)); +}); diff --git a/frontend/apps/web/src/app/(studio)/studio/data-requests/[requestId]/page.tsx b/frontend/apps/web/src/app/(studio)/studio/data-requests/[requestId]/page.tsx new file mode 100644 index 000000000..51ddc28bf --- /dev/null +++ b/frontend/apps/web/src/app/(studio)/studio/data-requests/[requestId]/page.tsx @@ -0,0 +1,6 @@ +import { AccountPage, accountPageMetadata } from '@/components/auth/shell'; + +export const generateMetadata = () => accountPageMetadata('data_request'); +export default function DataRequestPage() { + return ; +} diff --git a/frontend/apps/web/src/app/(studio)/studio/data-requests/erasure/page.tsx b/frontend/apps/web/src/app/(studio)/studio/data-requests/erasure/page.tsx new file mode 100644 index 000000000..c0d264e89 --- /dev/null +++ b/frontend/apps/web/src/app/(studio)/studio/data-requests/erasure/page.tsx @@ -0,0 +1,6 @@ +import { AccountPage, accountPageMetadata } from '@/components/auth/shell'; + +export const generateMetadata = () => accountPageMetadata('data_request_erasure'); +export default function DataRequestErasurePage() { + return ; +} diff --git a/frontend/apps/web/src/app/(studio)/studio/data-requests/page.tsx b/frontend/apps/web/src/app/(studio)/studio/data-requests/page.tsx new file mode 100644 index 000000000..8e80a1788 --- /dev/null +++ b/frontend/apps/web/src/app/(studio)/studio/data-requests/page.tsx @@ -0,0 +1,6 @@ +import { AccountPage, accountPageMetadata } from '@/components/auth/shell'; + +export const generateMetadata = () => accountPageMetadata('data_requests'); +export default function DataRequestsPage() { + return ; +} diff --git a/frontend/apps/web/src/app/globals.css b/frontend/apps/web/src/app/globals.css index 85fcbe8ce..42f8898c6 100644 --- a/frontend/apps/web/src/app/globals.css +++ b/frontend/apps/web/src/app/globals.css @@ -304,3 +304,76 @@ padding: 0; border: 0; } + +/* ADR-0106 data-request administration: 44 px targets, status glyphs and a 320 px reflow. + A link's content is one element: text beside an element in a flex container loses its space. */ +.auth-data-requests button, +.auth-data-requests :is(p, nav, dd, h3, li) > a { + display: inline-flex; + align-items: center; + min-block-size: 44px; +} +/* A summary keeps display: list-item, which alone draws its open/closed marker. */ +.auth-data-requests summary { + display: list-item; + min-block-size: 44px; + padding-block: 0.5rem; + align-content: center; +} +.auth-data-request-status { + display: flex; + gap: 0.5rem; + align-items: center; + font-weight: 600; +} +.auth-data-request-status svg { + flex: none; + inline-size: 1.25rem; + block-size: 1.25rem; +} +.auth-data-request-facts { + display: grid; + grid-template-columns: minmax(0, max-content) minmax(0, 1fr); + gap: 0.25rem 1rem; +} +.auth-data-request-facts dd { + margin: 0; +} +.auth-data-request-confirm { + border: 2px solid currentColor; + padding: 0.5rem 1rem; + margin-block: 1rem; +} +.auth-data-request-confirm legend { + font-weight: 600; + padding-inline: 0.25rem; +} +.auth-data-request-confirm label { + display: flex; + gap: 0.75rem; + align-items: flex-start; + min-block-size: 44px; + padding-block: 0.5rem; + cursor: pointer; +} +.auth-shell .auth-data-request-confirm input[type='checkbox'] { + flex: none; + inline-size: 1.5rem; + block-size: 1.5rem; + margin: 0.1rem 0 0; +} +@media (max-width: 30rem) { + .auth-data-request-facts { + grid-template-columns: minmax(0, 1fr); + } + .auth-data-request-facts dd { + margin-block-end: 0.5rem; + } +} +@media (prefers-reduced-motion: reduce) { + .auth-data-requests * { + animation: none !important; + transition: none !important; + scroll-behavior: auto !important; + } +} diff --git a/frontend/apps/web/src/components/auth/admin-data-request-labels.ts b/frontend/apps/web/src/components/auth/admin-data-request-labels.ts new file mode 100644 index 000000000..431fd74ce --- /dev/null +++ b/frontend/apps/web/src/components/auth/admin-data-request-labels.ts @@ -0,0 +1,296 @@ +import type { AdminCopy, DataRequestUiCopy } from '@/i18n/administration-catalogues'; +import type { + DataRequestAdministrationRefusal, + DataRequestAdministrationResult, + PageDataRequest, +} from '@/server/auth/page-contract'; + +/** + * ADR-0106 §§ 6–8, 11 for the administrator's pages and recovery document. Every sentence is a literal catalogue + * key, so the catalogue census reads it; the person's own catalogue (`dataRequest`) is used only where its wording is + * exactly right for an administrator too, and `admin` holds the administrator's wording everywhere else. + */ +export type DataRequestState = PageDataRequest['status'] | 'due'; +type Request = Pick< + PageDataRequest, + 'kind' | 'origin' | 'status' | 'executeAt' | 'requestedByYou' | 'artifact' +>; + +/** An erasure past its window but not yet run reads "starting soon", exactly as on the person's own page. */ +export function dataRequestDisplayState( + item: Pick, + preparedAt: string, +): DataRequestState { + return item.kind === 'erasure' && + item.status === 'scheduled' && + item.executeAt !== null && + Date.parse(preparedAt) >= Date.parse(item.executeAt) + ? 'due' + : item.status; +} +/** Only the administrator who filed a request may act on it (the API answers 404 to anyone else). */ +const filedByCaller = (item: Request) => item.origin === 'administrator' && item.requestedByYou; +/** ADR-0106 § 11: an export until it starts, an erasure until its window ends. */ +export function administratorMayCancel(item: Request, preparedAt: string): boolean { + if (!filedByCaller(item)) return false; + if (item.kind === 'export') return item.status === 'requested'; + return item.kind === 'erasure' && dataRequestDisplayState(item, preparedAt) === 'scheduled'; +} +/** ADR-0107 § 4: "the requesting administrator may revoke an unexpired artifact". */ +export function administratorMayRevoke(item: Request): boolean { + return filedByCaller(item) && item.kind === 'export' && item.artifact?.readable === true; +} +export function dataRequestKindLabel( + kind: PageDataRequest['kind'], + admin: AdminCopy, + dataRequest: DataRequestUiCopy, +): string { + switch (kind) { + case 'export': + return admin('data_requests.kind.export'); + case 'erasure': + return admin('data_requests.kind.erasure'); + case 'closure': + // The API never shows an administrator a closure; the type admits it, so its neutral name is kept. + return dataRequest('kind.closure'); + } +} +export function dataRequestStatusLabel(state: DataRequestState, dataRequest: DataRequestUiCopy) { + switch (state) { + case 'requested': + return dataRequest('status.requested'); + case 'scheduled': + return dataRequest('status.scheduled'); + case 'due': + return dataRequest('status.due'); + case 'fulfilling': + return dataRequest('status.fulfilling'); + case 'awaiting_privileged_step': + return dataRequest('status.awaiting_privileged_step'); + case 'completed': + return dataRequest('status.completed'); + case 'blocked': + return dataRequest('status.blocked'); + case 'failed': + return dataRequest('status.failed'); + case 'cancelled': + return dataRequest('status.cancelled'); + } +} +/** The presentational glyph beside a status; the status text carries the meaning. */ +export function dataRequestStateIcon( + state: DataRequestState, +): 'waiting' | 'working' | 'person' | 'done' | 'stopped' | 'problem' { + switch (state) { + case 'completed': + return 'done'; + case 'cancelled': + return 'stopped'; + case 'blocked': + case 'failed': + return 'problem'; + case 'awaiting_privileged_step': + return 'person'; + case 'fulfilling': + case 'due': + return 'working'; + case 'requested': + case 'scheduled': + return 'waiting'; + } +} +export function dataRequestFiledBy(item: Request, admin: AdminCopy): string { + switch (item.origin) { + case 'self': + return admin('data_requests.filed.person'); + case 'closure_fanout': + return admin('data_requests.filed.closure'); + case 'administrator': + return item.requestedByYou + ? admin('data_requests.filed.you') + : admin('data_requests.filed.other'); + } +} +/** The next step a reader of this request can expect, in the administrator's terms. */ +export function dataRequestNextStep( + item: Request, + state: DataRequestState, + admin: AdminCopy, + dataRequest: DataRequestUiCopy, +): string { + if (item.status === 'cancelled') return dataRequest('next.cancelled'); + if (item.status === 'failed') return dataRequest('next.failed'); + if (item.status === 'blocked') return dataRequest('next.blocked'); + if (item.kind === 'export') + return item.status === 'completed' + ? item.artifact?.readable + ? admin('data_requests.next.export_ready') + : admin('data_requests.next.export_gone') + : admin('data_requests.next.export_requested'); + if (item.kind === 'closure') return dataRequestStatusLabel(state, dataRequest); + if (state === 'due') return dataRequest('next.erasure_due'); + switch (item.status) { + case 'scheduled': + // A fan-out erasure is never scheduled; only the person cancels what they filed themselves. + return item.origin === 'self' + ? admin('data_requests.next.erasure_scheduled_self') + : admin('data_requests.next.erasure_scheduled'); + case 'fulfilling': + return admin('data_requests.next.erasure_fulfilling'); + case 'awaiting_privileged_step': + return admin('data_requests.next.erasure_awaiting'); + default: + return dataRequest('next.erasure_completed'); + } +} +export function dataRequestLastRefusal( + code: NonNullable, + admin: AdminCopy, +): string { + switch (code) { + case 'blocked_window': + return admin('data_requests.last_refusal.blocked_window'); + case 'blocked_hold': + return admin('data_requests.last_refusal.blocked_hold'); + case 'blocked_last_administrator': + return admin('data_requests.last_refusal.blocked_last_administrator'); + } +} +export function dataRequestFailure( + reason: NonNullable, + admin: AdminCopy, + dataRequest: DataRequestUiCopy, +): string { + switch (reason) { + case 'export_too_large': + return admin('data_requests.failure.export_too_large'); + case 'execution_failed': + return dataRequest('failure.execution_failed'); + } +} +export function dataRequestRetainedLabel( + kind: PageDataRequest['retained'][number]['kind'], + admin: AdminCopy, + dataRequest: DataRequestUiCopy, +): string { + switch (kind) { + case 'consent_evidence': + return admin('data_requests.retained.consent_evidence'); + case 'invitation_record': + return admin('data_requests.retained.invitation_record'); + case 'invitation_envelope': + return dataRequest('retained.kind.invitation_envelope'); + case 'audit_actor_reference': + return admin('data_requests.retained.audit_actor_reference'); + case 'audit_entity_reference': + return admin('data_requests.retained.audit_entity_reference'); + case 'audit_metadata_reference': + return admin('data_requests.retained.audit_metadata_reference'); + case 'unscoped_audit_rows': + return dataRequest('retained.kind.unscoped_audit_rows'); + case 'transport_evidence': + return dataRequest('retained.kind.transport_evidence'); + case 'execution_evidence': + return dataRequest('retained.kind.execution_evidence'); + case 'provider_event_record': + return dataRequest('retained.kind.provider_event_record'); + case 'idempotency_cache': + return dataRequest('retained.kind.idempotency_cache'); + case 'attribution_reference': + return dataRequest('retained.kind.attribution_reference'); + case 'federation_actor_reference': + return admin('data_requests.retained.federation_actor_reference'); + case 'request_receipt': + return dataRequest('retained.kind.request_receipt'); + case 'external_copy': + return dataRequest('retained.kind.external_copy'); + case 'unserved_group': + return admin('data_requests.retained.unserved_group'); + } +} +export function dataRequestCollectionLabel( + collection: string, + admin: AdminCopy, + dataRequest: DataRequestUiCopy, +): string { + return collection === 'audit.entries' + ? dataRequest('artifact.collection_audit_entries') + : collection === 'identity.invitations_issued' + ? admin('data_requests.collection_invitations_issued') + : dataRequest('artifact.collection_other'); +} +/** One sentence per closed refusal of the administrator's routes; `unknown` is a reason this release does not name. */ +export function dataRequestRefusalSentence( + refusal: DataRequestAdministrationRefusal, + admin: AdminCopy, + dataRequest: DataRequestUiCopy, +): string { + switch (refusal) { + case 'request_already_active': + return admin('data_requests.refusal.request_already_active'); + case 'blocked_hold': + return admin('data_requests.refusal.blocked_hold'); + case 'blocked_last_administrator': + return admin('data_requests.refusal.blocked_last_administrator'); + case 'subject_export_available': + return dataRequest('refusal.subject_export_available'); + case 'subject_membership_current': + // The API judges the person's current Membership of the group, which need not be the one named. + return admin('data_requests.refusal.subject_membership_current'); + case 'subject_is_requester': + return dataRequest('refusal.subject_is_requester'); + case 'subject_not_admitted': + return admin('data_requests.refusal.subject_not_admitted'); + case 'snapshot_too_large': + return admin('data_requests.refusal.snapshot_too_large'); + case 'data_export_unavailable': + return admin('data_requests.refusal.data_export_unavailable'); + case 'data_request_window_ended': + return dataRequest('refusal.data_request_window_ended'); + case 'data_request_not_cancellable': + return dataRequest('refusal.data_request_not_cancellable'); + case 'unknown': + return admin('data_requests.refusal.unknown'); + } +} +/** + * Whether a closed result the page was redirected with still describes the request as prepared: the notice and the + * title prefix are dropped once the request moved on (a reload, a restored or a shared URL keeps the query). + */ +export function dataRequestResultCurrent( + result: DataRequestAdministrationResult, + item: Pick, + preparedAt: string, +): boolean { + switch (result) { + case 'export': + return ( + item.kind === 'export' && + (item.status === 'requested' || + item.status === 'fulfilling' || + (item.status === 'completed' && item.artifact?.readable === true)) + ); + case 'erasure': + return item.kind === 'erasure' && dataRequestDisplayState(item, preparedAt) === 'scheduled'; + case 'cancelled': + return item.status === 'cancelled'; + case 'revoked': + return item.kind === 'export' && item.artifact !== null && !item.artifact.readable; + } +} +export function dataRequestResultSentence( + result: DataRequestAdministrationResult, + admin: AdminCopy, + dataRequest: DataRequestUiCopy, +): string { + switch (result) { + case 'export': + return admin('data_requests.result.export'); + case 'erasure': + return admin('data_requests.result.erasure'); + case 'cancelled': + return dataRequest('result.cancelled'); + case 'revoked': + return admin('data_requests.result.revoked'); + } +} diff --git a/frontend/apps/web/src/components/auth/admin-data-requests.test.tsx b/frontend/apps/web/src/components/auth/admin-data-requests.test.tsx new file mode 100644 index 000000000..3d3cfcab1 --- /dev/null +++ b/frontend/apps/web/src/components/auth/admin-data-requests.test.tsx @@ -0,0 +1,678 @@ +import { renderToStaticMarkup } from 'react-dom/server'; +import { describe, expect, it, vi } from 'vitest'; + +import { + administratorMayCancel, + administratorMayRevoke, + dataRequestDisplayState, + dataRequestResultCurrent, +} from './admin-data-request-labels'; +import { PreparedAccountPage, accountPageMetadata } from './shell'; +import { dataRequestCancellable, dataRequestState } from '../../server/auth/data-request-html'; +import { bffAdministrationForm } from '../../server/auth/http-forms'; +import { optionalPreparedPage } from '../../server/auth/page'; +import type { + NativePageSnapshot, + PageDataRequest, + PageView, +} from '../../server/auth/page-contract'; +import { administrationSnapshot, uiMember } from '../../test/administration-ui-fixture'; + +vi.mock('@/server/auth/page', () => ({ optionalPreparedPage: vi.fn() })); +vi.mock('@/client/bff-session', () => ({ extendBffSession: vi.fn() })); + +const requestId = '019a154b-0000-7000-8000-000000000041'; +const preparedAt = '2026-11-23T12:00:00.000Z'; +const named = { + membershipId: uiMember.membershipId, + displayName: '', + status: 'Active', + organizationScoped: false, +} as const; +const request = (value: Partial = {}): PageDataRequest => ({ + id: requestId, + kind: 'erasure', + origin: 'administrator', + status: 'scheduled', + createdAt: '2026-11-23T10:00:00.0000000+00:00', + updatedAt: null, + completedAt: null, + lastRefusal: null, + failureReason: null, + retained: [], + artifact: null, + version: '9223372036854775807', + executeAt: '2026-11-24T10:00:00.0000000+00:00', + requestedByYou: true, + membershipIds: [uiMember.membershipId], + membershipCount: 1, + // An administrator's erasure is filed only for a Revoked Membership, which is never read (ADR-0106 § 3). + subject: 'revoked', + ...value, +}); +const exported = (value: Partial = {}) => + request({ + kind: 'export', + status: 'completed', + executeAt: null, + completedAt: '2026-11-23T10:05:00.0000000+00:00', + updatedAt: '2026-11-23T10:05:00.0000000+00:00', + subject: named, + artifact: { + id: '019a154b-0000-7000-8000-000000000042', + status: 'available', + expiresAt: '2026-11-30T10:05:00.0000000+00:00', + purgedAt: null, + byteCount: 2 * 1024 * 1024, + chunkCount: 16, + truncations: [{ collection: 'audit.entries', included: 10, total: 12 }], + version: '9007199254740993', + readable: true, + }, + ...value, + }); +function documentFor(view: PageView, overrides: Partial = {}) { + const snapshot = administrationSnapshot(view, overrides); + const html = renderToStaticMarkup(); + return { snapshot, document: new DOMParser().parseFromString(html, 'text/html') }; +} +const inLocale = (locale: string): Partial => ({ + ownProfile: { displayName: null, preferredLocale: locale, version: '1' }, +}); +function forms(document: Document) { + return [...document.querySelectorAll('form')].filter((form) => + form.getAttribute('action')!.startsWith('/api/studio/data-request-'), + ); +} +function fields(form: HTMLFormElement) { + const values = new URLSearchParams(); + for (const [name, value] of new FormData(form)) values.append(name, String(value)); + return values; +} +const list = (items: PageDataRequest[], next: string | null = null): PageView => ({ + kind: 'data_requests', + items, + endCursor: next, + hasNextPage: next !== null, + preparedAt, +}); +const detail = ( + value: PageDataRequest, + result: Extract['result'] = null, +): PageView => ({ kind: 'data_request', request: value, result, preparedAt }); +// The member page exists only for an Active or Suspended Membership: the API answers 404 for a Revoked one. +const memberView = ( + status: 'Active' | 'Suspended', + dataRequests: Extract['dataRequests'], + inCurrentScope = true, +): PageView => ({ + kind: 'member', + member: { + ...uiMember, + status, + inCurrentScope, + canChangeStatus: true, + canReplaceRoles: false, + }, + roles: null, + ...(dataRequests ? { dataRequests } : {}), +}); +const erasurePage = (membershipId: string | null = uiMember.membershipId): PageView => ({ + kind: 'data_request_erasure', + membershipId, +}); + +describe('Studio data requests: the list (ADR-0106 §§ 6, 13)', () => { + it.each(['en', 'tr'])( + 'names the subject, the status and the filer without a form (%s)', + (locale) => { + const items = [ + request(), + exported({ id: '019a154b-0000-7000-8000-000000000043', requestedByYou: false }), + request({ + id: '019a154b-0000-7000-8000-000000000044', + origin: 'self', + requestedByYou: false, + subject: null, + }), + ]; + const { document } = documentFor(list(items, 'c2VhbGVk'), inLocale(locale)); + expect(document.querySelectorAll('h1')).toHaveLength(1); + expect(document.querySelector('h1')?.textContent).toBe( + locale === 'en' ? 'Data requests' : 'Veri talepleri', + ); + const headings = [...document.querySelectorAll('.auth-resource-list article h3 a')]; + expect(headings.map((link) => link.getAttribute('href'))).toEqual( + items.map((item) => '/studio/data-requests/' + item.id), + ); + expect(headings[0]!.querySelector('bdi')).toBeNull(); + expect(headings[1]!.querySelector('bdi')?.textContent).toBe(''); + expect(document.querySelector('subject')).toBeNull(); + // Each flex link holds one element, so the space before the name is never a flex item's trailing space. + for (const link of headings) { + expect(link.childNodes).toHaveLength(1); + expect((link.firstChild as Element).tagName).toBe('SPAN'); + } + if (locale === 'en') { + expect(headings.map((link) => link.textContent)).toEqual([ + 'Erasure: Revoked member', + 'Data export: ', + 'Erasure: Member name unavailable', + ]); + const filed = [...document.querySelectorAll('article dl')].map( + (facts) => facts.querySelectorAll('dd')[0]?.textContent, + ); + expect(filed).toEqual(['You', 'Another administrator', 'The person themselves']); + expect(document.body.textContent).toContain('Status: Scheduled'); + expect(document.body.textContent).toContain('Administrators cannot download it.'); + } + for (const status of document.querySelectorAll('.auth-data-request-status')) { + const icon = status.querySelector('svg')!; + expect(icon.getAttribute('aria-hidden')).toBe('true'); + expect(icon.getAttribute('focusable')).toBe('false'); + expect(status.querySelector('span')?.textContent?.length).toBeGreaterThan(5); + } + expect(document.querySelectorAll('time').length).toBeGreaterThanOrEqual(4); + expect(forms(document)).toHaveLength(0); + expect( + document.querySelector('a[href="/studio/data-requests?cursor=c2VhbGVk"]'), + ).not.toBeNull(); + expect(document.querySelector('a[href="/studio/members"]')).not.toBeNull(); + expect(document.body.textContent).not.toContain(uiMember.membershipId); + expect(document.querySelector('script')).toBeNull(); + }, + ); + + it('shows the navigation entry only with the membership capability, and an empty state', () => { + const { document, snapshot } = documentFor(list([])); + expect(document.querySelector('nav a[href="/studio/data-requests"]')?.textContent).toBe( + 'Data requests', + ); + expect(document.body.textContent).toContain('No data requests have been made in this scope.'); + const without = documentFor(list([]), { + capabilities: { ...snapshot.capabilities!, canManageMemberships: false }, + }).document; + expect( + without.querySelector('nav[aria-label="Account navigation"] a[href="/studio/data-requests"]'), + ).toBeNull(); + expect( + document.querySelector( + 'nav[aria-label="Account navigation"] a[href="/studio/data-requests"]', + ), + ).not.toBeNull(); + }); + + it('offers the first page after an invalid cursor', () => { + const { document } = documentFor(list([]), { + outcome: { kind: 'failure', reason: 'invalid_cursor', status: 400, retryAfterSeconds: null }, + }); + expect(document.querySelector('section a[href="/studio/data-requests"]')).not.toBeNull(); + }); +}); + +describe('Studio data requests: one request', () => { + it('cancels a scheduled erasure the caller filed at its version, with a fresh key', () => { + const { document, snapshot } = documentFor(detail(request())); + const [form] = forms(document); + expect(form?.getAttribute('action')).toBe('/api/studio/data-request-cancel'); + const values = fields(form!); + expect([...values.keys()]).toEqual(['csrfToken', 'version', 'idempotencyKey', 'requestId']); + expect(values.get('idempotencyKey')).toBe(snapshot.formKeys[0]); + expect(bffAdministrationForm('/api/studio/data-request-cancel', values)).toEqual({ + operation: { + kind: 'cancelDataRequest', + id: requestId, + version: '9223372036854775807', + idempotencyKey: snapshot.formKeys[0], + }, + destination: '/studio/data-requests/' + requestId, + }); + // A Revoked subject has no member page: a truthful label, and no link to a page that answers 404. + expect(document.querySelector('.auth-resource-name a, dd a')).toBeNull(); + expect(document.querySelector('.auth-resource-name')?.textContent).toBe( + 'Erasure: Revoked member', + ); + expect(document.body.textContent).toContain('Starts after'); + expect(document.body.textContent).toContain( + 'Until then the person can cancel it, and so can the administrator who asked for it.', + ); + }); + + it('links a named subject to the Membership whose read named it, and an unnamed one nowhere', () => { + const other = '019a154b-0000-7000-8000-000000000077'; + const { document } = documentFor( + detail(exported({ subject: { ...named, membershipId: other } })), + ); + const link = document.querySelector('dd a')!; + expect(link.getAttribute('href')).toBe('/studio/members/' + other); + expect(link.childNodes).toHaveLength(1); + expect(link.querySelector('span > bdi')?.textContent).toBe(''); + const unnamed = documentFor(detail(exported({ subject: null }))).document; + expect(unnamed.querySelector('dd a')).toBeNull(); + expect(unnamed.body.textContent).toContain('Member name unavailable'); + }); + + it("does not credit an administrator with a self-filed erasure's cancellation", () => { + const self = documentFor(detail(request({ origin: 'self', requestedByYou: false }))); + const text = self.document.body.textContent!; + expect(text).toContain( + 'Erasure starts after the time shown. Until then the person can cancel it.', + ); + expect(text).not.toContain('the administrator who asked for it'); + }); + + it('offers no cancellation once the window ended, nor to anyone but the administrator who filed it', () => { + const due = documentFor(detail(request({ executeAt: '2026-11-23T11:00:00.0000000+00:00' }))); + expect(forms(due.document)).toHaveLength(0); + expect(due.document.body.textContent).toContain('Status: Starting soon'); + expect(due.document.body.textContent).toContain('It can no longer be cancelled.'); + const other = documentFor(detail(request({ requestedByYou: false }))); + expect(forms(other.document)).toHaveLength(0); + expect(other.document.body.textContent).toContain( + 'Another administrator asked for this request. Only they or the person can cancel it.', + ); + const person = documentFor(detail(request({ origin: 'self', requestedByYou: true }))); + expect(forms(person.document)).toHaveLength(0); + expect(person.document.body.textContent).toContain( + 'The person asked for this request themselves. Only they can cancel it.', + ); + const fanOut = documentFor( + detail(request({ origin: 'closure_fanout', requestedByYou: false })), + ).document.querySelector('.auth-data-requests')!.textContent!; + expect(fanOut).toContain("The person's account closure"); + expect(fanOut).not.toContain('can cancel it.'); + const reader = documentFor(detail(request()), { + capabilities: { + ...administrationSnapshot(detail(request())).capabilities!, + canManageMemberships: false, + }, + }); + expect(forms(reader.document)).toHaveLength(0); + }); + + it('revokes an available export the caller filed at the artifact version inside a disclosure', () => { + const value = exported(); + const { document, snapshot } = documentFor(detail(value)); + const form = forms(document).find( + (candidate) => candidate.getAttribute('action') === '/api/studio/data-request-revoke', + )!; + expect(form.closest('details.auth-danger')).not.toBeNull(); + expect(fields(form).get('version')).toBe('9007199254740993'); + expect(fields(form).get('idempotencyKey')).toBe(snapshot.formKeys[1]); + expect( + bffAdministrationForm('/api/studio/data-request-revoke', fields(form)).operation, + ).toEqual({ + kind: 'revokeDataExport', + id: requestId, + version: '9007199254740993', + idempotencyKey: snapshot.formKeys[1], + }); + expect(document.body.textContent).toContain('Available until'); + expect(document.body.textContent).toContain('2 MB'); + expect(document.body.textContent).toContain('Activity records: 10 included, 12 in total'); + expect(document.body.textContent).toContain('Administrators cannot download it.'); + expect(document.body.textContent).toContain( + 'The person can download it on their own data page until the date shown.', + ); + for (const changed of [ + exported({ requestedByYou: false }), + exported({ origin: 'self' }), + exported({ artifact: { ...value.artifact!, readable: false, status: 'revoked' } }), + ]) + expect(forms(documentFor(detail(changed)).document)).toHaveLength(0); + }); + + it.each(['en', 'tr'] as const)( + 'announces a settled action in a status region and the document title (%s)', + async (locale) => { + const { document, snapshot } = documentFor(detail(request(), 'erasure'), inLocale(locale)); + const notice = document.querySelector('[role="status"]')!; + expect(notice.querySelector('h2')?.textContent).toBe( + locale === 'en' ? 'Your action has been recorded' : 'İşleminiz kaydedildi', + ); + expect(notice.textContent).toContain( + locale === 'en' ? 'It starts after 24 hours' : 'İşlem 24 saat sonra başlar', + ); + vi.mocked(optionalPreparedPage).mockResolvedValueOnce({ + snapshot, + assertActive: () => undefined, + } as never); + expect((await accountPageMetadata('data_request')).title).toBe( + locale === 'en' + ? 'Your action has been recorded – Data request' + : 'İşleminiz kaydedildi – Veri talebi', + ); + vi.mocked(optionalPreparedPage).mockResolvedValueOnce({ + snapshot: administrationSnapshot(detail(request()), inLocale(locale)), + assertActive: () => undefined, + } as never); + expect((await accountPageMetadata('data_request')).title).toBe( + locale === 'en' ? 'Data request' : 'Veri talebi', + ); + // The person cancelled it since: a reloaded, restored or shared URL no longer announces the filing. + const stale = administrationSnapshot( + detail( + request({ status: 'cancelled', updatedAt: '2026-11-23T11:00:00.0000000+00:00' }), + 'erasure', + ), + inLocale(locale), + ); + const html = renderToStaticMarkup( + , + ); + expect( + new DOMParser().parseFromString(html, 'text/html').querySelector('[role="status"]'), + ).toBeNull(); + vi.mocked(optionalPreparedPage).mockResolvedValueOnce({ + snapshot: stale, + assertActive: () => undefined, + } as never); + expect((await accountPageMetadata('data_request')).title).toBe( + locale === 'en' ? 'Data request' : 'Veri talebi', + ); + }, + ); + + it('keeps a result only while it describes the request as prepared', () => { + const at = preparedAt; + const cases: [Parameters[0], PageDataRequest, boolean][] = [ + ['erasure', request(), true], + ['erasure', request({ executeAt: '2026-11-23T11:00:00.0000000+00:00' }), false], + ['erasure', request({ status: 'cancelled' }), false], + ['erasure', exported({ status: 'requested', artifact: null }), false], + ['export', exported({ status: 'requested', artifact: null }), true], + ['export', exported({ status: 'fulfilling', artifact: null }), true], + ['export', exported(), true], + ['export', exported({ artifact: { ...exported().artifact!, readable: false } }), false], + ['export', exported({ status: 'failed', artifact: null }), false], + ['export', request(), false], + ['cancelled', request({ status: 'cancelled' }), true], + ['cancelled', request(), false], + ['revoked', exported({ artifact: { ...exported().artifact!, readable: false } }), true], + ['revoked', exported(), false], + ['revoked', exported({ artifact: null }), false], + ]; + for (const [result, item, expected] of cases) + expect(dataRequestResultCurrent(result, item, at), result + ' ' + item.status).toBe(expected); + }); + + it('explains what was kept, why a request stopped or failed, and every Membership it covers', () => { + const completed = request({ + status: 'completed', + completedAt: '2026-11-24T12:00:00.0000000+00:00', + updatedAt: '2026-11-24T12:00:00.0000000+00:00', + retained: [ + { kind: 'consent_evidence', count: 3 }, + { kind: 'invitation_envelope', count: 1 }, + { kind: 'unserved_group', count: 0 }, + ], + membershipIds: [uiMember.membershipId, '019a154b-0000-7000-8000-000000000099'], + membershipCount: 25, + }); + const text = documentFor(detail(completed)).document.querySelector( + '.auth-data-requests', + )!.textContent!; + expect(text).toContain('Records of consents the person gave or withdrew: 3'); + expect(text).toContain('Encrypted copies of invitation e-mails: 1'); + expect(text).toContain('Places that could not be processed and keep the person'); + expect(text).toContain('This list is not complete'); + expect(text).toContain('Membership record 2'); + expect(text).toContain('Only the first 20 records are listed.'); + // An erasure that ran leaves every record a Revoked tombstone: none has a member page. + expect( + documentFor(detail(completed)).document.querySelectorAll('li a[href^="/studio/members/"]'), + ).toHaveLength(0); + const exportRecords = documentFor( + detail(exported({ membershipIds: completed.membershipIds, membershipCount: 2 })), + ).document.querySelectorAll('li > a[href^="/studio/members/"]'); + expect([...exportRecords].map((link) => link.getAttribute('href'))).toEqual( + completed.membershipIds.map((id) => '/studio/members/' + id), + ); + for (const link of exportRecords) { + expect(link.childNodes).toHaveLength(1); + expect(link.firstElementChild?.tagName).toBe('SPAN'); + } + expect(exportRecords[1]!.textContent).toBe('Membership record 2'); + expect(text).not.toMatch(/\byou gave\b|\byour\b/i); + const blocked = documentFor( + detail( + request({ + status: 'blocked', + lastRefusal: 'blocked_last_administrator', + updatedAt: '2026-11-24T10:01:00.0000000+00:00', + }), + ), + ).document.body.textContent!; + expect(blocked).toContain("this person is the institution's only administrator"); + expect(blocked).toContain('Ended'); + const failed = documentFor( + detail( + exported({ + status: 'failed', + failureReason: 'export_too_large', + artifact: null, + completedAt: null, + }), + ), + ).document.body.textContent!; + expect(failed).toContain('Ask the platform operator about the export size limit.'); + }); +}); + +describe("Studio data requests: the member's section", () => { + const empty = { items: [], complete: true, preparedAt }; + + it('files an export for this Membership and sends erasure through the revocation', () => { + const { document, snapshot } = documentFor(memberView('Active', empty)); + const section = document.querySelector( + 'section[aria-labelledby="member-data-requests-title"]', + )!; + expect(section.querySelector('h2')?.textContent).toBe('Data requests'); + const [form, ...rest] = forms(document); + expect(rest).toHaveLength(0); + expect(form?.getAttribute('action')).toBe('/api/studio/data-request-export'); + expect(fields(form!).get('idempotencyKey')).toBe(snapshot.formKeys[32]); + expect(bffAdministrationForm('/api/studio/data-request-export', fields(form!))).toEqual({ + operation: { + kind: 'createDataExportForSubject', + membershipId: uiMember.membershipId, + idempotencyKey: snapshot.formKeys[32], + }, + destination: '/studio/members/' + uiMember.membershipId, + }); + expect(section.textContent).toContain( + 'This membership is still active or suspended. It has to end before an administrator can ask for its erasure.', + ); + expect(section.textContent).toContain( + 'The revocation is recorded as its own action, and the page where its erasure is asked for then opens.', + ); + // The erasure itself is filed on the page the revocation leads to, never here. + expect(document.querySelector('form[action="/api/studio/data-request-erasure"]')).toBeNull(); + expect(section.querySelector('details')).toBeNull(); + expect(section.textContent).toContain('No data requests about this member'); + // Every idempotency key on the member page stays distinct. + const keys = [ + ...document.querySelectorAll('input[name="idempotencyKey"]'), + ].map((input) => input.value); + expect(new Set(keys).size).toBe(keys.length); + }); + + it('withholds a filing the visible list already proves futile, and lists only this member', () => { + const active = documentFor( + memberView('Suspended', { + items: [ + exported({ status: 'requested', artifact: null, completedAt: null }), + request({ id: '019a154b-0000-7000-8000-000000000045', origin: 'self' }), + ], + complete: true, + preparedAt, + }), + ).document; + expect(forms(active)).toHaveLength(0); + expect(active.body.textContent).toContain( + 'An export for this member is already being prepared.', + ); + expect( + [ + ...active.querySelectorAll( + 'section[aria-labelledby="member-data-requests-title"] article a', + ), + ].map((link) => link.getAttribute('href')), + ).toEqual([ + '/studio/data-requests/' + requestId, + '/studio/data-requests/019a154b-0000-7000-8000-000000000045', + ]); + const available = documentFor( + memberView('Active', { items: [exported({ origin: 'self' })], complete: true, preparedAt }), + ).document; + expect(forms(available)).toHaveLength(0); + expect(available.body.textContent).toContain( + 'A copy of the data is already available to download.', + ); + }); + + it('says what it could not check, and keeps the filings', () => { + const partial = documentFor(memberView('Active', { items: [], complete: false, preparedAt })); + expect(partial.document.body.textContent).toContain('Only the 100 most recent requests'); + const unavailable = documentFor( + memberView('Active', { items: null, complete: false, preparedAt }), + ); + expect(unavailable.document.body.textContent).toContain('could not be checked just now'); + expect(unavailable.document.body.textContent).not.toContain( + 'Only the 100 most recent requests', + ); + expect(forms(unavailable.document)).toHaveLength(1); + }); + + it('sends another scope to its own access, and shows nothing without the capability', () => { + const outside = documentFor(memberView('Active', undefined, false)).document; + expect(forms(outside)).toHaveLength(0); + expect(outside.body.textContent).toContain("made in the member's own scope"); + const { snapshot } = documentFor(memberView('Active', empty)); + const without = documentFor(memberView('Active', empty), { + capabilities: { ...snapshot.capabilities!, canManageMemberships: false }, + }).document; + expect(without.querySelector('#member-data-requests-title')).toBeNull(); + }); +}); + +describe('Studio data requests: the erasure page of a Revoked Membership (ADR-0106 §§ 3, 11)', () => { + it.each(['en', 'tr'] as const)( + 'confirms the erasure explicitly, stating what goes and what stays (%s)', + (locale) => { + const { document, snapshot } = documentFor(erasurePage(), inLocale(locale)); + expect(document.querySelectorAll('h1')).toHaveLength(1); + expect(document.querySelector('h1')?.textContent).toBe( + locale === 'en' + ? "Erase a revoked member's data" + : 'Sonlandırılmış bir üyenin verilerini sil', + ); + const text = document.querySelector('.auth-data-requests')!.textContent!; + expect(text).toContain( + locale === 'en' ? 'This membership was revoked.' : 'Bu üyelik sonlandırıldı.', + ); + // Nothing about the Membership was read: no name, and no link to a member page that answers 404. + expect(document.querySelector('a[href^="/studio/members/"]')).toBeNull(); + expect(document.body.textContent).not.toContain(uiMember.membershipId); + const [form, ...rest] = forms(document); + expect(rest).toHaveLength(0); + expect(form!.getAttribute('action')).toBe('/api/studio/data-request-erasure'); + const disclosure = form!.closest('details.auth-danger')!; + expect(disclosure.querySelector('summary')?.textContent).toBe( + locale === 'en' ? 'Review the erasure' : 'Silme işlemini gözden geçir', + ); + expect(disclosure.querySelectorAll('h2')).toHaveLength(2); + expect(disclosure.querySelectorAll('ul')).toHaveLength(2); + expect(disclosure.textContent).toContain(locale === 'en' ? '24 hours' : '24 saat'); + expect(disclosure.textContent).toContain( + locale === 'en' + ? 'the person can cancel it on their own data page' + : 'kişi talebi kendi veri sayfasından', + ); + expect(disclosure.textContent).toContain( + locale === 'en' + ? 'If the person is admitted to this scope again within those 24 hours, the erasure still runs.' + : 'Kişi bu 24 saat içinde bu kapsama yeniden üye olsa bile silme işlemi yine yapılır.', + ); + const fieldset = form!.querySelector('fieldset')!; + expect(fieldset.querySelector('legend')?.textContent).toBe( + locale === 'en' ? 'Confirm the erasure' : 'Silme talebini onaylayın', + ); + const box = fieldset.querySelector('input[type="checkbox"]')!; + expect(box.required).toBe(true); + expect(box.getAttribute('aria-required')).toBe('true'); + expect(box.closest('label')?.textContent).toContain(locale === 'en' ? 'Required' : 'Zorunlu'); + expect(form!.checkValidity()).toBe(false); + box.checked = true; + expect(form!.checkValidity()).toBe(true); + const values = fields(form!); + expect([...values.keys()]).toEqual([ + 'csrfToken', + 'idempotencyKey', + 'membershipId', + 'confirm', + ]); + expect(bffAdministrationForm('/api/studio/data-request-erasure', values)).toEqual({ + operation: { + kind: 'createDataErasureForSubject', + membershipId: uiMember.membershipId, + idempotencyKey: snapshot.formKeys[0], + }, + destination: '/studio/data-requests/erasure?membership=' + uiMember.membershipId, + }); + expect(form!.querySelector('button')?.getAttribute('aria-describedby')).toBe( + 'data-erasure-timing', + ); + expect(document.getElementById('data-erasure-timing')).not.toBeNull(); + expect(document.querySelector('script')).toBeNull(); + }, + ); + + it('offers no filing when the page was opened without a Membership, nor without the capability', () => { + const missing = documentFor(erasurePage(null)).document; + expect(forms(missing)).toHaveLength(0); + expect(missing.body.textContent).toContain('No membership was named.'); + expect(missing.querySelector('.auth-data-requests a[href="/studio/members"]')).not.toBeNull(); + const { snapshot } = documentFor(erasurePage()); + const without = documentFor(erasurePage(), { + capabilities: { ...snapshot.capabilities!, canManageMemberships: false }, + }).document; + expect(forms(without)).toHaveLength(0); + expect(without.querySelector('.auth-data-requests')).toBeNull(); + }); +}); + +describe("the administrator's derivations follow the person's page", () => { + it('derives due and cancellable exactly as the person page does for a request the caller filed', () => { + const times = [ + '2026-11-24T09:59:59.000Z', + '2026-11-24T10:00:00.000Z', + '2026-11-24T10:00:01.000Z', + ]; + for (const kind of ['export', 'erasure'] as const) + for (const status of [ + 'requested', + 'scheduled', + 'fulfilling', + 'awaiting_privileged_step', + 'completed', + 'blocked', + 'failed', + 'cancelled', + ] as const) + for (const at of times) { + const item = request({ + kind, + status, + executeAt: kind === 'erasure' ? '2026-11-24T10:00:00.0000000+00:00' : null, + }); + expect(dataRequestDisplayState(item, at)).toBe(dataRequestState(item, at)); + expect(administratorMayCancel(item, at)).toBe(dataRequestCancellable(item, at)); + expect(administratorMayCancel({ ...item, requestedByYou: false }, at)).toBe(false); + expect(administratorMayCancel({ ...item, origin: 'self' }, at)).toBe(false); + } + expect(administratorMayRevoke(exported())).toBe(true); + expect(administratorMayRevoke(exported({ requestedByYou: false }))).toBe(false); + expect(administratorMayRevoke(exported({ origin: 'self' }))).toBe(false); + }); +}); diff --git a/frontend/apps/web/src/components/auth/admin-data-requests.tsx b/frontend/apps/web/src/components/auth/admin-data-requests.tsx new file mode 100644 index 000000000..987394826 --- /dev/null +++ b/frontend/apps/web/src/components/auth/admin-data-requests.tsx @@ -0,0 +1,584 @@ +/* eslint-disable @next/next/no-html-link-for-pages -- Protected views use freshly admitted full document navigation. */ +import type { AdminCopy, DataRequestUiCopy } from '@/i18n/administration-catalogues'; +import type { + NativePageSnapshot, + PageDataRequest, + PageMemberDetail, + PageView, +} from '@/server/auth/page-contract'; + +import { + administratorMayCancel, + administratorMayRevoke, + dataRequestCollectionLabel, + dataRequestDisplayState, + dataRequestFailure, + dataRequestFiledBy, + dataRequestKindLabel, + dataRequestLastRefusal, + dataRequestNextStep, + dataRequestResultCurrent, + dataRequestResultSentence, + dataRequestRetainedLabel, + dataRequestStateIcon, + dataRequestStatusLabel, +} from './admin-data-request-labels'; +import { FormIdentityFields, MutationFields } from './admin-forms'; + +type Copy = Readonly<{ admin: AdminCopy; dataRequest: DataRequestUiCopy; locale: string }>; + +/** Inline presentational glyphs (the same shapes as the person's page); the status text carries the meaning. */ +const ICONS = { + waiting: + 'M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20Zm0 2a8 8 0 1 1 0 16 8 8 0 0 1 0-16Zm-1 3v6l5 3 1-1.7-4-2.4V7h-2Z', + working: + 'M12 4V1L8 5l4 4V6a6 6 0 0 1 5.7 7.9l1.5 1.5A8 8 0 0 0 12 4Zm0 14a6 6 0 0 1-5.7-7.9L4.8 8.6A8 8 0 0 0 12 20v3l4-4-4-4v3Z', + person: 'M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8Zm0 2c-4.4 0-8 2.2-8 5v1h16v-1c0-2.8-3.6-5-8-5Z', + done: 'M9 16.2 4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2Z', + stopped: + 'M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20Zm0 2a8 8 0 0 1 6.3 12.9L7.1 5.7A8 8 0 0 1 12 4ZM5.7 7.1l11.2 11.2A8 8 0 0 1 5.7 7.1Z', + problem: 'M1 21h22L12 2 1 21Zm12-3h-2v-2h2v2Zm0-4h-2v-4h2v4Z', +} as const; +const ACTIVE_EXPORT = ['requested', 'fulfilling']; + +function Instant({ value, locale }: { readonly value: string; readonly locale: string }) { + const text = new Intl.DateTimeFormat(locale, { + dateStyle: 'long', + timeStyle: 'short', + timeZone: 'UTC', + }).format(new Date(value)); + return ; +} +function Size({ bytes, locale }: { readonly bytes: number; readonly locale: string }) { + const large = bytes >= 1024 * 1024; + return ( + + {new Intl.NumberFormat(locale, { + style: 'unit', + unit: large ? 'megabyte' : 'kilobyte', + unitDisplay: 'short', + maximumFractionDigits: 1, + }).format(large ? bytes / (1024 * 1024) : Math.max(0.1, bytes / 1024))} + + ); +} +function Count({ value, locale }: { readonly value: number; readonly locale: string }) { + return {new Intl.NumberFormat(locale).format(value)}; +} + +/** + * Who the request concerns, as the member list shows a member: the name, or a truthful label when no Membership of + * the snapshot could be named (all Revoked, so none was read, or no read answered). + */ +function SubjectName({ + item, + admin, +}: { + readonly item: PageDataRequest; + readonly admin: AdminCopy; +}) { + if (item.subject === 'revoked') return <>{admin('data_requests.subject_revoked')}; + if (!item.subject) return <>{admin('data_requests.name_unavailable')}; + return {item.subject.displayName ?? admin('members.unnamed')}; +} + +function StatusLine({ + item, + preparedAt, + copy, +}: { + readonly item: PageDataRequest; + readonly preparedAt: string; + readonly copy: Copy; +}) { + const state = dataRequestDisplayState(item, preparedAt); + return ( +

+ + + {copy.dataRequest('list.status')}: {dataRequestStatusLabel(state, copy.dataRequest)} + +

+ ); +} + +/** The request's dates and sizes; a `
` reflows to one column at 320 px. */ +function Facts({ + item, + copy, + subject, +}: { + readonly item: PageDataRequest; + readonly copy: Copy; + readonly subject: boolean; +}) { + const { admin, dataRequest, locale } = copy; + const artifact = item.artifact; + const ended = item.completedAt === null && item.updatedAt !== null; + return ( +
+ {subject && ( + <> +
{admin('data_requests.concerns')}
+
+ {item.subject !== null && item.subject !== 'revoked' ? ( + // Only a Membership whose read named the person has a member page to open. + + + + + + ) : ( + + )} +
+ + )} +
{admin('data_requests.filed_by')}
+
{dataRequestFiledBy(item, admin)}
+
{dataRequest('list.requested')}
+
+ +
+ {item.executeAt !== null && item.status === 'scheduled' && ( + <> +
{dataRequest('list.runs_after')}
+
+ +
+ + )} + {item.completedAt !== null && ( + <> +
{dataRequest('list.completed')}
+
+ +
+ + )} + {ended && ['cancelled', 'blocked', 'failed'].includes(item.status) && ( + <> +
{dataRequest('list.ended')}
+
+ +
+ + )} + {artifact !== null && ( + <> +
+ {artifact.readable + ? dataRequest('list.available_until') + : dataRequest('list.expired_on')} +
+
+ +
+
{dataRequest('list.size')}
+
+ +
+ + )} +
+ ); +} + +function Retained({ item, copy }: { readonly item: PageDataRequest; readonly copy: Copy }) { + const { admin, dataRequest, locale } = copy; + if ( + item.kind !== 'erasure' || + (item.retained.length === 0 && !['awaiting_privileged_step', 'completed'].includes(item.status)) + ) + return null; + return ( +
+

{dataRequest('retained.title')}

+ {item.retained.length > 0 && ( + <> +

{dataRequest('retained.intro')}

+
    + {item.retained.map((entry) => ( +
  • + {dataRequestRetainedLabel(entry.kind, admin, dataRequest)}:{' '} + +
  • + ))} +
+ + )} + {item.status !== 'completed' &&

{dataRequest('retained.pending')}

} +

{dataRequest('retained.partial')}

+

{dataRequest('retained.audit_retention')}

+
+ ); +} + +/** ADR-0106 §§ 3, 6, 13: the group's export and erasure requests, newest first; status and counts only. */ +export function DataRequestDirectory({ + snapshot, + view, + copy, +}: { + readonly snapshot: NativePageSnapshot; + readonly view: Extract; + readonly copy: Copy; +}) { + const { admin, dataRequest } = copy; + const next = + view.hasNextPage && view.endCursor !== null + ? '/studio/data-requests?' + new URLSearchParams({ cursor: view.endCursor }) + : null; + return ( +
+

{admin('data_requests.intro')}

+

+ {snapshot.scopeKind === 'tenant' + ? admin('data_requests.scope_tenant') + : admin('data_requests.scope_organization')} +

+

{admin('data_requests.no_download')}

+

{admin('data_requests.no_closure')}

+

+ {admin('data_requests.from_member')}{' '} + {admin('data_requests.open_members')} +

+
+

{admin('data_requests.list_title')}

+ {view.items.length === 0 ? ( +

{admin('data_requests.empty')}

+ ) : ( + + )} + +
+
+ ); +} + +/** One request of the group, with the actions only the administrator who filed it may take. */ +export function DataRequestDetails({ + snapshot, + view, + copy, +}: { + readonly snapshot: NativePageSnapshot; + readonly view: Extract; + readonly copy: Copy; +}) { + const { admin, dataRequest, locale } = copy; + const item = view.request; + const state = dataRequestDisplayState(item, view.preparedAt); + const artifact = item.artifact; + const target = ['requestId', item.id] as const; + // Who else may cancel: the person always, the administrator who filed it; a closure's fan-out never. + const cancellable = + item.origin !== 'closure_fanout' && + ((item.kind === 'export' && item.status === 'requested') || + (item.kind === 'erasure' && state === 'scheduled')); + return ( +
+

+ {admin('data_requests.back')} +

+ {view.result !== null && dataRequestResultCurrent(view.result, item, view.preparedAt) && ( +
+

{dataRequest('result.title')}

+

{dataRequestResultSentence(view.result, admin, dataRequest)}

+
+ )} +

+ {dataRequestKindLabel(item.kind, admin, dataRequest)}:{' '} + +

+ + +

{dataRequestNextStep(item, state, admin, dataRequest)}

+ {item.lastRefusal !== null &&

{dataRequestLastRefusal(item.lastRefusal, admin)}

} + {item.failureReason !== null && item.status === 'failed' && ( +

{dataRequestFailure(item.failureReason, admin, dataRequest)}

+ )} + {artifact !== null && artifact.truncations.length > 0 && ( + <> +

{dataRequest('artifact.truncated')}

+
    + {artifact.truncations.map((part) => ( +
  • + {dataRequestCollectionLabel(part.collection, admin, dataRequest)}:{' '} + {' '} + {dataRequest('artifact.truncated_included')},{' '} + {' '} + {dataRequest('artifact.truncated_total')} +
  • + ))} +
+ + )} + {item.kind === 'export' &&

{admin('data_requests.no_download')}

} + {item.membershipCount > 1 && ( + <> +

{admin('data_requests.memberships_note')}

+
    + {item.membershipIds.map((membershipId, index) => { + const record = ( + <> + {admin('data_requests.membership_record')}{' '} + {index + 1} + + ); + return ( +
  • + {item.subject === 'revoked' ? ( + // Every Membership of this snapshot is Revoked: none has a member page. + record + ) : ( + + {record} + + )} +
  • + ); + })} +
+ {item.membershipCount > item.membershipIds.length && ( +

{admin('data_requests.memberships_more')}

+ )} + + )} + + {snapshot.capabilities?.canManageMemberships && + (administratorMayCancel(item, view.preparedAt) ? ( +
+ +

{admin('data_requests.cancel.hint')}

+ + + ) : ( + cancellable && ( +

+ {item.origin === 'self' + ? admin('data_requests.cancel.person') + : admin('data_requests.cancel.other')} +

+ ) + ))} + {snapshot.capabilities?.canManageMemberships && administratorMayRevoke(item) && artifact && ( +
+ {admin('data_requests.revoke.title')} +

{admin('data_requests.revoke.hint')}

+
+ + + +
+ )} +
+ ); +} + +/** + * The member page's section: this member's requests in the exact current group, and the two filings pre-filled + * for this Membership. The API decides every refusal; the page only withholds a form the list already proves futile. + */ +export function MemberDataRequests({ + snapshot, + member, + requests, + copy, +}: { + readonly snapshot: NativePageSnapshot; + readonly member: PageMemberDetail; + readonly requests: Extract['dataRequests']; + readonly copy: Copy; +}) { + const { admin, dataRequest } = copy; + if (!snapshot.capabilities?.canManageMemberships) return null; + const subject = ['membershipId', member.membershipId] as const; + const items = requests?.items ?? []; + return ( +
+

{admin('data_requests.title')}

+ {!member.inCurrentScope || !requests ? ( +

{admin('data_requests.member.other_scope')}

+ ) : ( + <> +

{admin('data_requests.member.intro')}

+

{admin('data_requests.no_download')}

+ {requests.items === null ? ( +

{admin('data_requests.member.unavailable')}

+ ) : items.length === 0 ? ( +

{admin('data_requests.member.none')}

+ ) : ( + + )} + {requests.items !== null && !requests.complete && ( +

{admin('data_requests.member.partial')}

+ )} +

+ {admin('data_requests.member.all')} +

+
+

{admin('data_requests.export.title')}

+

{admin('data_requests.export.description')}

+

{admin('data_requests.export.replaces')}

+ {items.some((item) => item.kind === 'export' && ACTIVE_EXPORT.includes(item.status)) ? ( +

{admin('data_requests.export.active')}

+ ) : items.some((item) => item.artifact?.readable) ? ( +

{dataRequest('refusal.subject_export_available')}

+ ) : ( +
+ + + + + )} +
+
+

{admin('data_requests.erasure.title')}

+

{admin('data_requests.erasure.summary')}

+ {/* ADR-0106 § 3: this page exists only for an Active or Suspended member; a Revoked one has none. */} +

{dataRequest('refusal.subject_membership_current')}

+

{admin('data_requests.erasure.revoke_first')}

+
+ + )} +
+ ); +} + +/** + * ADR-0106 §§ 3, 11: the erasure filing for a Revoked Membership, the page a revocation leads to. A Revoked Membership + * has no member page and nothing about it is read here: the statement of what is erased and kept, the 24-hour window + * and the explicit confirmation precede the one form, and the API refuses any Membership it does not cover. + */ +export function DataRequestErasure({ + snapshot, + view, + copy, +}: { + readonly snapshot: NativePageSnapshot; + readonly view: Extract; + readonly copy: Copy; +}) { + const { admin, dataRequest } = copy; + if (!snapshot.capabilities?.canManageMemberships) return null; + return ( +
+

+ {admin('data_requests.back')} +

+ {view.membershipId === null ? ( + <> +

{admin('data_requests.erasure_page.missing')}

+

+ {admin('data_requests.open_members')} +

+ + ) : ( + <> +

{admin('data_requests.erasure_page.revoked')}

+

{admin('data_requests.erasure.summary')}

+

{admin('data_requests.erasure_page.only_revoked')}

+
+ {admin('data_requests.erasure.start')} +

{admin('data_requests.erasure.erased_title')}

+
    +
  • {admin('data_requests.erasure.erased_profile')}
  • +
  • {admin('data_requests.erasure.erased_roles')}
  • +
  • {admin('data_requests.erasure.erased_exports')}
  • +
  • {admin('data_requests.erasure.erased_invitations')}
  • +
+

{admin('data_requests.erasure.kept_title')}

+

{admin('data_requests.erasure.kept_intro')}

+
    +
  • {admin('data_requests.erasure.kept_consent')}
  • +
  • {admin('data_requests.erasure.kept_invitations')}
  • +
  • {admin('data_requests.erasure.kept_audit')}
  • +
  • {admin('data_requests.erasure.kept_attribution')}
  • +
  • {admin('data_requests.erasure.kept_receipt')}
  • +
+

{dataRequest('retained.audit_retention')}

+

{dataRequest('erasure.kept_uncounted')}

+

{dataRequest('erasure.kept_partial')}

+

{admin('data_requests.erasure.timing')}

+
+ + +
+ {admin('data_requests.erasure.legend')} + +
+ + +
+ + )} +
+ ); +} diff --git a/frontend/apps/web/src/components/auth/admin-forms.tsx b/frontend/apps/web/src/components/auth/admin-forms.tsx index 622799048..d4487a703 100644 --- a/frontend/apps/web/src/components/auth/admin-forms.tsx +++ b/frontend/apps/web/src/components/auth/admin-forms.tsx @@ -14,7 +14,10 @@ export function MutationFields({ readonly snapshot: NativePageSnapshot; readonly index: number; readonly version: string; - readonly target?: readonly ['membershipId' | 'roleId' | 'invitationId' | 'definitionId', string]; + readonly target?: readonly [ + 'membershipId' | 'roleId' | 'invitationId' | 'definitionId' | 'requestId', + string, + ]; }) { const key = snapshot.formKeys[index]; if (!key || !/^[A-Za-z0-9_-]{43}$/.test(key)) throw new Error('Prepared form unavailable'); diff --git a/frontend/apps/web/src/components/auth/admin-members.tsx b/frontend/apps/web/src/components/auth/admin-members.tsx index 90f464f42..ee12f3f38 100644 --- a/frontend/apps/web/src/components/auth/admin-members.tsx +++ b/frontend/apps/web/src/components/auth/admin-members.tsx @@ -1,7 +1,8 @@ /* eslint-disable @next/next/no-html-link-for-pages -- Protected views use freshly admitted full document navigation. */ -import type { AdminCopy, ProfileCopy } from '@/i18n/administration-catalogues'; +import type { AdminCopy, DataRequestUiCopy, ProfileCopy } from '@/i18n/administration-catalogues'; import type { NativePageSnapshot, PageView } from '@/server/auth/page-contract'; +import { MemberDataRequests } from './admin-data-requests'; import { MutationFields, ProfileFields, ProfileValues } from './admin-forms'; import { roleLabel, statusLabel } from './admin-labels'; import type { FieldCopy } from './custom-field-controls'; @@ -58,6 +59,7 @@ export function MemberDetails({ admin, profile, fieldCopy, + requestCopy, }: { readonly snapshot: NativePageSnapshot; readonly view: Extract; @@ -65,6 +67,11 @@ export function MemberDetails({ readonly admin: AdminCopy; readonly profile: ProfileCopy; readonly fieldCopy: FieldCopy; + readonly requestCopy: Readonly<{ + admin: AdminCopy; + dataRequest: DataRequestUiCopy; + locale: string; + }>; }) { const member = view.member; const target = ['membershipId', member.membershipId] as const; @@ -223,6 +230,12 @@ export function MemberDetails({ )} + ); } diff --git a/frontend/apps/web/src/components/auth/history.test.ts b/frontend/apps/web/src/components/auth/history.test.ts index c85f196b8..7dfbd6401 100644 --- a/frontend/apps/web/src/components/auth/history.test.ts +++ b/frontend/apps/web/src/components/auth/history.test.ts @@ -30,6 +30,31 @@ describe('fixed protected history lifecycle', () => { '/studio/members/019a154b-0000-7000-8000-000000000011', '/studio/members/019a154b-0000-7000-8000-000000000011', ], + ['/studio/data-requests', '/studio/data-requests'], + [ + '/studio/data-requests/019a154b-0000-7000-8000-000000000041', + '/studio/data-requests/019a154b-0000-7000-8000-000000000041', + ], + [ + '/studio/data-requests/019a154b-0000-7000-8000-000000000041?result=export', + '/api/auth/signin', + ], + // A Revoked Membership's erasure page: the one recovery that carries its query. + [ + '/studio/data-requests/erasure?membership=019a154b-0000-7000-8000-000000000011', + '/studio/data-requests/erasure?membership=019a154b-0000-7000-8000-000000000011', + ], + ['/studio/data-requests/erasure', '/api/auth/signin'], + [ + '/studio/data-requests/erasure?membership=019A154B-0000-7000-8000-000000000011', + '/api/auth/signin', + ], + [ + '/studio/data-requests/erasure?membership=019a154b-0000-7000-8000-000000000011&x=1', + '/api/auth/signin', + ], + ['/studio/members/erasure?membership=019a154b-0000-7000-8000-000000000011', '/api/auth/signin'], + ['/studio/data-requests/erasure/019a154b-0000-7000-8000-000000000011', '/api/auth/signin'], ['/api/auth/entry', '/api/auth/entry'], ['/api/auth/signin', '/api/auth/signin'], ['/api/account/profile', '/api/auth/signin'], diff --git a/frontend/apps/web/src/components/auth/history.ts b/frontend/apps/web/src/components/auth/history.ts index 8001b7d43..8670f5304 100644 --- a/frontend/apps/web/src/components/auth/history.ts +++ b/frontend/apps/web/src/components/auth/history.ts @@ -2,5 +2,6 @@ // document stays veiled until a complete, freshly admitted network navigation. // Native documents always carry a fixed GET recovery target: reloading a POST // result could replay a mutation. The inline guard independently closes the DOM -// attribute to the same finite screens; invalid attributes fall back to sign-in. -export const BFF_HISTORY_SOURCE = `(()=>{let leaving=false;addEventListener('pagehide',()=>{leaving=true;document.documentElement.style.visibility='hidden'});addEventListener('pageshow',e=>{if(e.persisted||leaving){document.documentElement.style.visibility='hidden';const r=document.documentElement.getAttribute('data-bff-history-recovery');if(r===null){location.reload()}else{const allowed=['/','/studio','/studio/members','/studio/roles','/studio/invitations','/studio/invitation-policy','/studio/federation','/portal','/portal/profile','/api/auth/entry','/api/auth/signin'];location.replace(allowed.includes(r)||/^\\/studio\\/(?:members|roles|invitations)\\/[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(r)?r:'/api/auth/signin')}}})})();`; +// attribute to the same finite screens (and the erasure page of one Membership, the +// one recovery that needs its query); invalid attributes fall back to sign-in. +export const BFF_HISTORY_SOURCE = `(()=>{let leaving=false;addEventListener('pagehide',()=>{leaving=true;document.documentElement.style.visibility='hidden'});addEventListener('pageshow',e=>{if(e.persisted||leaving){document.documentElement.style.visibility='hidden';const r=document.documentElement.getAttribute('data-bff-history-recovery');if(r===null){location.reload()}else{const allowed=['/','/studio','/studio/members','/studio/roles','/studio/invitations','/studio/invitation-policy','/studio/federation','/studio/data-requests','/portal','/portal/profile','/api/auth/entry','/api/auth/signin'];location.replace(allowed.includes(r)||/^\\/studio\\/(?:(?:members|roles|invitations|data-requests)\\/|data-requests\\/erasure\\?membership=)[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(r)?r:'/api/auth/signin')}}})})();`; diff --git a/frontend/apps/web/src/components/auth/shell.tsx b/frontend/apps/web/src/components/auth/shell.tsx index d5ce30810..4f32c6a42 100644 --- a/frontend/apps/web/src/components/auth/shell.tsx +++ b/frontend/apps/web/src/components/auth/shell.tsx @@ -6,12 +6,18 @@ import { preferredPageLocale, getAdministrationCatalogue, } from '@/i18n/administration-catalogues'; -import type { AdminCopy, ProfileCopy } from '@/i18n/administration-catalogues'; +import type { AdminCopy, DataRequestUiCopy, ProfileCopy } from '@/i18n/administration-catalogues'; import { createAuthTranslator } from '@/i18n/auth-catalogues'; import type { AuthCopy } from '@/i18n/auth-catalogues'; import { optionalPreparedPage } from '@/server/auth/page'; import type { NativePageSnapshot, PageView } from '@/server/auth/page-contract'; +import { dataRequestResultCurrent } from './admin-data-request-labels'; +import { + DataRequestDetails, + DataRequestDirectory, + DataRequestErasure, +} from './admin-data-requests'; import { FederationPage } from './admin-federation'; import { MutationFields, ProfileFields, ProfileValues } from './admin-forms'; import { InvitationDetails, InvitationDirectory, InvitationPolicy } from './admin-invitations'; @@ -41,6 +47,9 @@ function title(kind: PageKind, admin: AdminCopy, profile: ProfileCopy, copy: Aut custom_fields: admin('custom_fields.title'), custom_field: admin('custom_fields.detail_title'), federation: admin('federation.title'), + data_requests: admin('data_requests.title'), + data_request: admin('data_requests.detail_title'), + data_request_erasure: admin('data_requests.erasure_page.title'), }; return titles[kind]; } @@ -51,15 +60,24 @@ function PageContents({ locale, admin, profile, + dataRequest, }: { readonly snapshot: NativePageSnapshot; readonly view: PageView; readonly locale: string; readonly admin: AdminCopy; readonly profile: ProfileCopy; + readonly dataRequest: DataRequestUiCopy; }) { const fieldCopy = getAdministrationCatalogue(locale).messages.admin.custom_fields; + const requestCopy = { admin, dataRequest, locale }; switch (view.kind) { + case 'data_requests': + return ; + case 'data_request': + return ; + case 'data_request_erasure': + return ; case 'custom_fields': return ( @@ -87,6 +105,7 @@ function PageContents({ admin={admin} profile={profile} fieldCopy={fieldCopy} + requestCopy={requestCopy} /> ); case 'roles': @@ -164,7 +183,8 @@ export function PreparedAccountPage({ if (snapshot.outcome.kind === 'ready' && snapshot.outcome.view.kind !== kind) throw new Error('Prepared page mismatch'); const preferred = preferredPageLocale(snapshot); - const { locale, direction, admin, profile } = createAdministrationTranslator(preferred); + const { locale, direction, admin, profile, dataRequest } = + createAdministrationTranslator(preferred); const { copy } = createAuthTranslator(preferred); const capabilities = snapshot.capabilities; const labels = { @@ -230,6 +250,9 @@ export function PreparedAccountPage({ {capabilities?.canManageMemberships && ( {admin('navigation.invitations')} )} + {capabilities?.canManageMemberships && ( + {admin('navigation.subject_data_requests')} + )} {snapshot.scopeKind === 'tenant' && ( {admin('navigation.invitation_policy')} )} @@ -240,6 +263,7 @@ export function PreparedAccountPage({ {admin('navigation.federation')} )} {admin('custom_fields.consent_history')} + {admin('navigation.data_requests')} {admin('navigation.profile')} {admin('navigation.contexts')} {copy('shell.catalog')} @@ -264,7 +288,9 @@ export function PreparedAccountPage({ ? '/studio/invitations' : kind === 'custom_fields' || kind === 'custom_field' ? '/studio/custom-fields' - : '/studio/members' + : kind === 'data_requests' + ? '/studio/data-requests' + : '/studio/members' : snapshot.target } > @@ -281,6 +307,7 @@ export function PreparedAccountPage({ locale={locale} admin={admin} profile={profile} + dataRequest={dataRequest} /> )} @@ -304,8 +331,20 @@ export async function accountPageMetadata(kind: PageKind) { if (!prepared) return { robots: { index: false, follow: false } }; prepared.assertActive(); const locale = preferredPageLocale(prepared.snapshot); - const { admin, profile } = createAdministrationTranslator(locale); + const { admin, profile, dataRequest } = createAdministrationTranslator(locale); const { copy } = createAuthTranslator(locale); - return { title: title(kind, admin, profile, copy), robots: { index: false, follow: false } }; + const outcome = prepared.snapshot.outcome; + // A settled data-request action is announced in the title too, as the person's own page does, only while the + // request is still in the state the result describes. + const done = + outcome.kind === 'ready' && + outcome.view.kind === 'data_request' && + outcome.view.result !== null && + dataRequestResultCurrent(outcome.view.result, outcome.view.request, outcome.view.preparedAt) && + kind === 'data_request'; + return { + title: (done ? dataRequest('result.title') + ' – ' : '') + title(kind, admin, profile, copy), + robots: { index: false, follow: false }, + }; } export const accountShellMetadata = (kind: 'studio' | 'portal') => accountPageMetadata(kind); diff --git a/frontend/apps/web/src/i18n/administration-catalogues.test.ts b/frontend/apps/web/src/i18n/administration-catalogues.test.ts index e7b49b2d5..155e5c896 100644 --- a/frontend/apps/web/src/i18n/administration-catalogues.test.ts +++ b/frontend/apps/web/src/i18n/administration-catalogues.test.ts @@ -9,11 +9,13 @@ import { } from './administration-catalogues'; import { checkCatalogues, publicCallsiteKeys } from '../test/ui-catalogue-checks'; import enAdmin from './messages/en/admin.json'; +import enData from './messages/en/data.json'; import enProfile from './messages/en/profile.json'; import trAdmin from './messages/tr/admin.json'; +import trData from './messages/tr/data.json'; import trProfile from './messages/tr/profile.json'; -function callsites(directory: string, namespace: 'admin' | 'profile'): string[] { +function callsites(directory: string, namespace: 'admin' | 'profile' | 'dataRequest'): string[] { return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { const path = join(directory, entry.name); if (entry.isDirectory()) return entry.name === 'test' ? [] : callsites(path, namespace); @@ -21,23 +23,27 @@ function callsites(directory: string, namespace: 'admin' | 'profile'): string[] const source = readFileSync(path, 'utf8'); // The native form grammar also has an unrelated profile(fields) parser. // UI owners bind these translators through the factory or typed copy port. - return /\b(?:createAdministrationTranslator|AdminCopy|ProfileCopy)\b/.test(source) + return /\b(?:createAdministrationTranslator|AdminCopy|ProfileCopy|DataRequestUiCopy)\b/.test( + source, + ) ? publicCallsiteKeys(source, path, namespace) : []; }); } describe('complete administration and profile UI catalogues', () => { it.each([ - ['admin', enAdmin, trAdmin], - ['profile', enProfile, trProfile], + ['admin', 'admin', enAdmin, trAdmin], + ['profile', 'profile', enProfile, trProfile], + // Studio reads the person's closed data-request catalogue only through literal keys it shares (ADR-0106). + ['dataRequest', 'data', enData, trData], ] as const)( 'validates all production %s callsites and both complete ICU catalogues', - (namespace, en, tr) => { + (namespace, catalogue, en, tr) => { const used = callsites(join(process.cwd(), 'src'), namespace); expect(used.length).toBeGreaterThan(10); checkCatalogues([en, tr], used); - expect(getAdministrationCatalogue('tr-Latn-TR').messages[namespace]).toBe(tr); - expect(getAdministrationCatalogue('ar').messages[namespace]).toBe(en); + expect(getAdministrationCatalogue('tr-Latn-TR').messages[catalogue]).toBe(tr); + expect(getAdministrationCatalogue('ar').messages[catalogue]).toBe(en); }, ); diff --git a/frontend/apps/web/src/i18n/administration-catalogues.ts b/frontend/apps/web/src/i18n/administration-catalogues.ts index 8d25dcd48..313a12829 100644 --- a/frontend/apps/web/src/i18n/administration-catalogues.ts +++ b/frontend/apps/web/src/i18n/administration-catalogues.ts @@ -6,19 +6,26 @@ import type { NativePageSnapshot } from '@/server/auth/page-contract'; import { selectUiLocale, textDirection } from './locale'; import enAdmin from './messages/en/admin.json'; +import enData from './messages/en/data.json'; import enProfile from './messages/en/profile.json'; import trAdmin from './messages/tr/admin.json'; +import trData from './messages/tr/data.json'; import trProfile from './messages/tr/profile.json'; const catalogues = { - en: { admin: enAdmin, profile: enProfile }, - tr: { admin: trAdmin, profile: trProfile }, + en: { admin: enAdmin, profile: enProfile, data: enData }, + tr: { admin: trAdmin, profile: trProfile, data: trData }, }; type Leaves = { [K in keyof T & string]: T[K] extends string ? K : `${K}.${Leaves}`; }[keyof T & string]; export type AdminCopy = (key: Leaves) => string; export type ProfileCopy = (key: Leaves) => string; +/** + * The person-facing data-request catalogue (ADR-0106), read in Studio only where its wording is exactly right for an + * administrator too: the closed status vocabulary, neutral labels and the refusals worded for both readers. + */ +export type DataRequestUiCopy = (key: Leaves) => string; export function getAdministrationCatalogue(locale: string) { const selected = selectUiLocale(locale); @@ -43,7 +50,19 @@ export function createAdministrationTranslator(locale: string) { onError: () => {}, getMessageFallback: () => selected.messages.profile.unavailable, }) as ProfileCopy; - return Object.freeze({ locale: selected.locale, direction: selected.direction, admin, profile }); + const dataRequest = createTranslator({ + locale: selected.locale, + messages: selected.messages.data, + onError: () => {}, + getMessageFallback: () => selected.messages.admin.failure.unavailable, + }) as DataRequestUiCopy; + return Object.freeze({ + locale: selected.locale, + direction: selected.direction, + admin, + profile, + dataRequest, + }); } /** Only the current actor's exact enabled Membership preference selects protected UI. */ diff --git a/frontend/apps/web/src/i18n/messages/en/admin.json b/frontend/apps/web/src/i18n/messages/en/admin.json index 257651ffe..12b158b9c 100644 --- a/frontend/apps/web/src/i18n/messages/en/admin.json +++ b/frontend/apps/web/src/i18n/messages/en/admin.json @@ -8,7 +8,9 @@ "invitations": "Invitations", "invitation_policy": "Invitation lifetime", "custom_fields": "Custom fields", - "federation": "Single sign-on" + "federation": "Single sign-on", + "data_requests": "Your data", + "subject_data_requests": "Data requests" }, "scope": { "tenant": "Institution-wide access", @@ -149,6 +151,134 @@ "policy_read_only": "You can view this policy. Editing requires institution-wide settings permission.", "required": "Required" }, + "data_requests": { + "title": "Data requests", + "detail_title": "Data request", + "intro": "Requests to export or erase the data of members in your current access, newest first. You see each request's status and counts, never the data itself.", + "no_download": "An exported file is available only to the person it concerns, on their own data page. Administrators cannot download it.", + "no_closure": "An account closure is the person's own request and is not shown here.", + "from_member": "To ask for an export, open the member's page. To ask for an erasure, revoke the membership on the member's page first; the page where its erasure is asked for then opens.", + "open_members": "Go to members", + "scope_tenant": "These are the requests about institution memberships. Requests about a branch membership are made and shown in that branch's access.", + "scope_organization": "These are the requests about memberships in your current branch.", + "list_title": "Requests", + "empty": "No data requests have been made in this scope.", + "next_page": "Older requests", + "back": "Back to data requests", + "concerns": "Member", + "name_unavailable": "Member name unavailable", + "subject_revoked": "Revoked member", + "filed_by": "Requested by", + "memberships_note": "This request covers more than one membership record of this person in this scope:", + "membership_record": "Membership record", + "memberships_more": "Only the first 20 records are listed.", + "own_data": "Your data page", + "kind": { + "export": "Data export", + "erasure": "Erasure" + }, + "filed": { + "you": "You", + "other": "Another administrator", + "person": "The person themselves", + "closure": "The person's account closure" + }, + "next": { + "export_requested": "The export is being prepared. This usually takes a few minutes.", + "export_ready": "The file is ready. The person can download it on their own data page until the date shown.", + "export_gone": "The file can no longer be downloaded.", + "erasure_scheduled": "Erasure starts after the time shown. Until then the person can cancel it, and so can the administrator who asked for it.", + "erasure_scheduled_self": "Erasure starts after the time shown. Until then the person can cancel it.", + "erasure_fulfilling": "The member's data in this scope is being erased.", + "erasure_awaiting": "The member's data in this scope has been erased. An operator now completes the last step on the activity records." + }, + "last_refusal": { + "blocked_window": "An operator tried to begin before the waiting time had ended.", + "blocked_hold": "It stopped because the institution has to keep this person's data for now, for example for an open payment matter.", + "blocked_last_administrator": "It stopped because this person is the institution's only administrator. Once another administrator is appointed, a new erasure can be requested." + }, + "failure": { + "export_too_large": "The person's data was too large for one file, so the export failed. Ask the platform operator about the export size limit." + }, + "collection_invitations_issued": "Invitations the person sent", + "retained": { + "consent_evidence": "Records of consents the person gave or withdrew", + "invitation_record": "Records of invitations the person sent or accepted", + "audit_actor_reference": "Activity records of things the person did", + "audit_entity_reference": "Activity records about the person's membership", + "audit_metadata_reference": "Activity records that mention the person", + "federation_actor_reference": "Records of single sign-on set-up steps the person took", + "unserved_group": "Places that could not be processed and keep the person's data for now" + }, + "refusal": { + "request_already_active": "A request of this kind is already in progress for this member in this scope. Wait for it to finish, or cancel it if you asked for it.", + "subject_membership_current": "This person still has an active or suspended membership in this scope. Their data can be erased only once that membership is revoked.", + "blocked_hold": "This cannot go ahead right now because the institution has to keep this member's data for the moment, for example for an open payment matter.", + "blocked_last_administrator": "This member is the institution's only administrator. Appoint another administrator before asking for an erasure.", + "snapshot_too_large": "This person has more membership records in this scope than one request can hold. Ask the platform operator for help.", + "subject_not_admitted": "This person's account is being closed, so no new request can be made about them.", + "data_export_unavailable": "This file is no longer available, so there is nothing to delete.", + "unknown": "This request was refused. Check its current state before trying again." + }, + "result": { + "export": "The export was requested. The file is usually ready within minutes and is then available to the person on their own data page.", + "erasure": "The erasure was requested. It starts after 24 hours; until then you or the person can cancel it.", + "revoked": "The file has been deleted. Nobody can download it any more." + }, + "member": { + "intro": "Requests about this member's data in your current access. You see their status, never the data.", + "other_scope": "Data requests about this member are made in the member's own scope. Change account access to that scope to see or make them.", + "none": "No data requests about this member have been made in this scope.", + "unavailable": "This member's data requests could not be checked just now. The forms below still work, and every request is checked when it is made.", + "partial": "Only the 100 most recent requests of this scope were checked for this member. Older ones are on the data requests page.", + "all": "All data requests" + }, + "export": { + "title": "Export this member's data", + "description": "Prepares one file with the data this institution holds about the person in this scope: their membership and profile, their answers and consents, their invitations and the activity records about them in this scope. The file is available only to the person, on their own data page, for 7 days. You see its status and size, never its content.", + "replaces": "An export cannot be requested while the person still has a file to download, because a new export would delete it.", + "action": "Request an export", + "active": "An export for this member is already being prepared." + }, + "erasure": { + "title": "Erase this member's data", + "summary": "Erasure clears the person's profile and answers in this scope and removes their roles here. Their account and their memberships elsewhere stay as they are.", + "revoke_first": "Revoke it in Membership access first. The revocation is recorded as its own action, and the page where its erasure is asked for then opens.", + "start": "Review the erasure", + "erased_title": "What is erased", + "erased_profile": "The person's name, language and the answers they gave in this scope are cleared.", + "erased_roles": "Their roles in this scope are removed. The revoked membership stays as an empty record.", + "erased_exports": "Copies of their data that can still be downloaded are deleted, and a copy still being prepared is cancelled.", + "erased_invitations": "Invitations they sent in this scope that nobody has accepted yet are withdrawn.", + "kept_title": "What is kept", + "kept_intro": "Some records have to be kept. They no longer hold the person's name or answers, but they still refer to the person by an internal number:", + "kept_consent": "the record of the consents they gave or withdrew, kept as evidence;", + "kept_invitations": "the record of invitations they sent or accepted, including the e-mail address an invitation was sent to;", + "kept_audit": "activity records: after the erasure, an operator removes network addresses, browser details and e-mail addresses from the activity records about the person, including records of what administrators did about them;", + "kept_attribution": "notes of who created or last changed something here;", + "kept_receipt": "this request and its receipt.", + "timing": "Erasure starts 24 hours after you request it. Until then the person can cancel it on their own data page, and you can cancel it on the request's page. If the person is admitted to this scope again within those 24 hours, the erasure still runs.", + "legend": "Confirm the erasure", + "confirm": "I understand what is erased and what is kept, and that erasure cannot be undone once it starts.", + "action": "Request erasure" + }, + "erasure_page": { + "title": "Erase a revoked member's data", + "revoked": "This membership was revoked. It is no longer listed among the members and has no member page.", + "only_revoked": "An erasure can be asked for only while the person has no active or suspended membership in this scope. Otherwise the request is refused and nothing changes.", + "missing": "No membership was named. This page opens for a membership right after it is revoked." + }, + "cancel": { + "hint": "Cancelling ends the request. Nothing about the member changes.", + "other": "Another administrator asked for this request. Only they or the person can cancel it.", + "person": "The person asked for this request themselves. Only they can cancel it." + }, + "revoke": { + "title": "Delete the exported file", + "hint": "Once deleted, nobody can download the file any more, including the person. The request stays as a record.", + "action": "Delete the file now" + } + }, "custom_fields": { "title": "Custom fields", "detail_title": "Custom field revision", diff --git a/frontend/apps/web/src/i18n/messages/en/auth.json b/frontend/apps/web/src/i18n/messages/en/auth.json index 0887cc9f1..b8f5b1e4d 100644 --- a/frontend/apps/web/src/i18n/messages/en/auth.json +++ b/frontend/apps/web/src/i18n/messages/en/auth.json @@ -69,7 +69,8 @@ "scope_current": "Current account access", "scope_choose": "Use this account access", "scope_back": "Return to your account", - "scope_empty": "No other account access is available." + "scope_empty": "No other account access is available.", + "data_requests": "Your data requests" }, "mutation": { "title": "Change not confirmed", diff --git a/frontend/apps/web/src/i18n/messages/en/data.json b/frontend/apps/web/src/i18n/messages/en/data.json new file mode 100644 index 000000000..0900efe26 --- /dev/null +++ b/frontend/apps/web/src/i18n/messages/en/data.json @@ -0,0 +1,238 @@ +{ + "common": { + "title": "Your data", + "skip": "Skip to content", + "intro": "Here you can get a copy of your data, ask for your data to be erased, or close your account, and follow each request.", + "signin": "Sign in to see and make requests about your data.", + "signin_action": "Sign in", + "back_portal": "Back to your portal", + "back_entry": "Back to account entry", + "back_page": "Back to your data requests", + "next_page": "Show older requests", + "next_scopes": "Show more places", + "required": "required", + "script_note": "This page works without JavaScript." + }, + "scope": { + "session_tenant": "These requests concern your institution-wide membership, the one you are signed in with now. Your memberships in branches are separate: to make a request about a branch, switch to that branch first.", + "session_organization": "These requests concern your membership in the branch you are signed in to now. To make a request about another branch or about your institution-wide membership, switch to it first.", + "session_retained": "A membership that is suspended or has ended cannot be switched to. For such a membership, sign out, sign in again and choose \"Your data requests\" before you choose where to continue.", + "switch": "Switch branch or institution", + "entry_intro": "Here you can make and follow requests for each place on this site where you have or had a membership, also where that membership is suspended or has ended. First choose where your request applies.", + "entry_choose": "Where your request applies", + "entry_tenant": "Institution-wide membership", + "entry_organization": "Branch", + "entry_names": "Branch names cannot be shown here. Branches are always listed in the same order, but they are numbered from 1 on each page, and the numbers can change when you join another branch.", + "entry_empty": "No membership or request was found for this account in this institution, so there is nothing to show here.", + "view": "Show requests", + "entry_selected_tenant": "Requests about your institution-wide membership", + "entry_selected_organization": "Requests about your membership in one branch", + "change": "Choose another place", + "entry_time_limit": "For your security, this page works only for a limited time: at most 5 minutes from when you began to sign in. After that, sign in again and choose \"Your data requests\". Requests you have already made are kept.", + "entry_time_until": "This page works until", + "entry_time_left": "Time left when this page was loaded", + "entry_time_under_minute": "less than a minute" + }, + "result": { + "title": "Your action has been recorded", + "export": "Your request for a copy of your data has been recorded. It usually takes a few minutes. This page does not update by itself: come back to it later to see when the file is ready.", + "erasure": "Your erasure request has been recorded. It starts after 24 hours, and you can cancel it until then.", + "closure": "Your account closure request has been recorded. Before anything happens, an operator contacts you by e-mail to confirm it. You can cancel it until the operator begins.", + "cancelled": "The request has been cancelled. Nothing was changed.", + "revoked": "The file has been deleted. You can ask for a new copy whenever you need one." + }, + "export": { + "title": "Get a copy of your data", + "description": "We prepare one file with the data this institution holds about you here: your membership and profile, the answers you gave and your consents, the invitations you received or sent (other people's addresses are left out), and records of activity that concern you.", + "audit_note": "The activity records in the file are the ones this branch or institution can show. They are not your complete history across the institution.", + "timing": "The file is usually ready within minutes. You can then download it for 7 days. When a new copy is ready, the previous file is deleted.", + "action": "Ask for a copy", + "active": "A copy is already being prepared. You can ask again once it is finished." + }, + "erasure": { + "title": "Erase your data here", + "summary": "Erasure clears your profile and answers in this one membership and ends it. Your account and your other memberships, in this institution or elsewhere, stay as they are.", + "start": "See what erasure means", + "active": "An erasure is already scheduled or in progress. You can follow it in the list below.", + "step_title": "Before you ask for erasure", + "erased_title": "What is erased", + "erased_profile": "Your name, your language and the answers you gave in this membership are cleared.", + "erased_roles": "Your roles in this membership are removed and the membership ends, so you lose the access it gave you.", + "erased_exports": "Copies of this membership's data that can still be downloaded are deleted, and a copy that is still being prepared is cancelled.", + "erased_invitations": "Invitations you sent from this membership that nobody has accepted yet are withdrawn.", + "kept_title": "What is kept", + "kept_intro": "Some records are kept. They no longer hold your name or your answers, but they still refer to you by an internal number:", + "kept_consent": "the record of the consents you gave or withdrew, kept as evidence;", + "kept_invitations": "the record of invitations you sent or accepted, including the e-mail address an invitation was sent to; an invitation sent to your e-mail address that you never accepted is kept too, but cannot be counted;", + "kept_audit": "activity records: an operator removes your network address, your browser details and your e-mail address from them, and this request then shows how many records remain;", + "kept_attribution": "notes of who created or last changed something here;", + "kept_receipt": "this request itself, with the records of its files and downloads.", + "kept_uncounted": "Some copies are kept but not counted: records of messages and background work, records used to recognise a repeated submission, encrypted copies of invitation e-mails, delivery copies of e-mails, backups and the sign-in service's logs. The platform does not remove them automatically yet, so they can stay for a long time.", + "kept_partial": "So the list of what is kept is not complete: something that is not listed is not necessarily absent.", + "timing": "Erasure starts 24 hours after you ask for it, and you can cancel it here until then. Once it has run, an operator completes the last step on the activity records.", + "legend": "Confirm erasure", + "confirm": "I understand what is erased and what is kept, and that erasure cannot be undone once it starts.", + "action": "Ask for erasure", + "back": "Keep my data and go back" + }, + "closure": { + "title": "Close your account", + "summary": "Closing your account ends it everywhere: in every institution and branch where you have a membership, not only here.", + "start": "See what closing your account means", + "active": "An account closure is already scheduled. You can follow it or cancel it in the list below.", + "step_title": "Before you close your account", + "warning_title": "Read this before you continue", + "warning_everywhere": "Your account ends in every institution and branch where you have a membership, not only here.", + "warning_email": "Before anything happens, an operator contacts you at the e-mail address of your sign-in account to confirm that you made this request.", + "warning_cancel": "Until the operator begins, you can cancel the request on this page.", + "warning_stops": "As soon as the operator begins, your account stops working. You cannot sign in again, and this cannot be undone.", + "warning_no_status": "From then on there is no page where you can follow the closure. The operator tells you by e-mail when it is complete.", + "warning_data": "Your data is then erased in each institution and branch where that is possible, and your sign-in account is deleted. What is kept is the same as for an erasure, described below.", + "warning_unserved": "In an institution that is suspended or archived, or a branch that is not active, your data is not erased: it stays there until the platform handles it in a separate step that is not in place yet. No page will show you this later.", + "legend": "Confirm account closure", + "confirm_irreversible": "I understand that my account stops working everywhere and that this cannot be undone.", + "confirm_no_status": "I understand that no page to follow the closure remains once it begins.", + "action": "Ask to close my account", + "back": "Keep my account and go back" + }, + "list": { + "title": "Your requests", + "empty": "You have not made any requests here yet.", + "status": "Status", + "requested": "Requested", + "runs_after": "Starts after", + "earliest": "Earliest start", + "ended": "Ended", + "completed": "Completed", + "available_until": "Available until", + "expired_on": "No longer available since", + "size": "File size", + "by_administrator": "An administrator of this institution made this request about you.", + "by_closure": "This erasure is part of your account closure." + }, + "kind": { + "export": "Copy of your data", + "erasure": "Erasure", + "closure": "Account closure" + }, + "status": { + "requested": "Requested", + "scheduled": "Scheduled", + "due": "Starting soon", + "fulfilling": "In progress", + "awaiting_privileged_step": "Waiting for an operator", + "completed": "Completed", + "blocked": "Stopped", + "failed": "Failed", + "cancelled": "Cancelled" + }, + "next": { + "export_requested": "We are preparing your file. This usually takes a few minutes; come back to this page later to see when it is ready.", + "export_ready": "Your file is ready. Download it before the date shown.", + "export_gone": "This file can no longer be downloaded. Ask for a new copy if you need one.", + "erasure_scheduled": "Erasure starts after the time shown. You can cancel it until then.", + "erasure_due": "The waiting time has ended and erasure starts shortly. It can no longer be cancelled.", + "erasure_fulfilling": "Your data here is being erased.", + "erasure_awaiting": "Your data here has been erased. An operator now completes the last step on the activity records. You do not need to do anything.", + "erasure_completed": "Erasure is complete. The list below shows what is kept.", + "closure_scheduled": "An operator contacts you by e-mail to confirm before beginning, which is possible from the time shown. You can cancel until the operator begins.", + "closure_fulfilling": "Your account closure has begun and cannot be undone.", + "closure_completed": "Your account closure is complete.", + "blocked": "This request was stopped before anything was erased.", + "failed": "This request could not be completed.", + "cancelled": "This request was cancelled. Nothing was changed." + }, + "blocked_reason": { + "blocked_hold": "It stopped because your data here is on hold, for example for an open payment matter. Contact the institution; once the hold is lifted, you can ask again.", + "blocked_last_administrator": "It stopped because you are the only administrator of this institution. Once another administrator has been appointed, you can ask again." + }, + "last_refusal": { + "blocked_window": "An operator tried to begin before the waiting time had ended. Your request is still scheduled.", + "blocked_hold": "Your request cannot go ahead yet because your data is on hold, for example for an open payment matter. It stays scheduled and you can cancel it.", + "blocked_last_administrator": "You are the only administrator of an institution. Another administrator has to be appointed there before this can go ahead. Your request stays scheduled and you can cancel it." + }, + "failure": { + "export_too_large": "Your data was too large for one file. Contact the institution for help before you ask again.", + "execution_failed": "Something went wrong while carrying out this request. You can make a new request." + }, + "artifact": { + "download": "Download your file", + "download_hint": "The file is a structured text file in JSON format. Each download is recorded.", + "delete": "Delete this file now", + "delete_hint": "Once deleted, nobody can download the file any more, including you.", + "truncated": "Some parts of the file were shortened to keep it within its size limit:", + "truncated_included": "included", + "truncated_total": "in total", + "part_included": "Included in the file", + "part_total": "In total", + "collection_audit_entries": "Activity records", + "collection_invitations_issued": "Invitations you sent", + "collection_other": "Another part of the file" + }, + "entry": { + "download_deadline": "A download must finish before this page stops working at the time shown above: one that is still running then stops without a complete file. A large file can take several minutes, so if little time is left, sign in again before you download.", + "step_deadline": "Send this form before this page stops working at the time shown above. After that, sign in again and come back to this step: nothing is recorded until you send the form." + }, + "retained": { + "title": "What is kept", + "intro": "These records are kept, with the numbers the institution could count:", + "pending": "The numbers of activity records are provisional: once an operator completes the last step, they are replaced by the exact numbers, which can differ.", + "partial": "This list is not complete: something that is not listed may still be kept without being counted. Records of messages and background work, records used to recognise a repeated submission, encrypted copies of invitation e-mails, delivery copies of e-mails, backups and the sign-in service's logs are kept in this way; the platform does not remove them automatically yet.", + "audit_retention": "How long activity records are kept is set by the platform's retention rules, but their removal is not automatic yet, so they can be kept for longer.", + "kind": { + "consent_evidence": "Records of consents you gave or withdrew", + "invitation_record": "Records of invitations you sent or accepted", + "invitation_envelope": "Encrypted copies of invitation e-mails", + "audit_actor_reference": "Activity records of things you did", + "audit_entity_reference": "Activity records about your membership", + "audit_metadata_reference": "Activity records that mention you", + "unscoped_audit_rows": "Activity records elsewhere in this institution that this request could not reach", + "transport_evidence": "Records of messages between parts of the platform", + "execution_evidence": "Records of background work", + "provider_event_record": "Records from the sign-in service", + "idempotency_cache": "Records used to recognise a repeated submission", + "attribution_reference": "Notes of who created or changed something", + "federation_actor_reference": "Records of single sign-on set-up steps you took", + "request_receipt": "Data requests, files and download records", + "external_copy": "Copies outside the platform, such as e-mail delivery copies and backups", + "unserved_group": "Places that could not be processed and keep your data for now" + } + }, + "action": { + "cancel": "Cancel this request", + "cancel_closure": "Cancel the account closure" + }, + "refusal": { + "request_already_active": "You already have a request of this kind in progress here. Wait for it to finish, or cancel it, before making a new one.", + "blocked_hold": "This cannot go ahead right now because your data here is on hold, for example for an open payment matter. Contact the institution if you have questions.", + "blocked_last_administrator": "You are the only administrator of this institution. Another administrator has to be appointed before your data can be erased.", + "subject_export_available": "A copy of the data is already available to download. A new copy can be requested once that file is deleted or no longer available.", + "subject_membership_current": "This membership is still active or suspended. It has to end before an administrator can ask for its erasure.", + "data_export_unavailable": "This file can no longer be downloaded. Ask for a new copy.", + "data_request_window_ended": "The waiting time for this erasure has ended, so it can no longer be cancelled. It starts shortly.", + "data_request_not_cancellable": "This request can no longer be cancelled: it has already started or ended.", + "subject_is_requester": "Requests about your own data are made on your own data page.", + "snapshot_too_large": "This request covers more memberships than one request can hold. Contact the institution for help.", + "data_export_ticket_limit": "This file has been downloaded too often in a short time, or too often in total. Wait 15 minutes and try again; if it still does not work, ask for a new copy.", + "subject_not_admitted": "Your account is being closed, so no new request can be made." + }, + "error": { + "title": "There is a problem", + "title_unconfirmed": "The outcome is not confirmed yet", + "input": "The form could not be read. Go back to your data requests and try again.", + "confirmation": "Tick every confirmation box to go ahead.", + "csrf": "This page has expired. Go back to your data requests and try again.", + "unauthorized": "Your sign-in has ended. Sign in again to continue.", + "forbidden": "You cannot do this here.", + "not_found": "This request or file could not be found. It may belong to another branch, or your access here has changed.", + "stale": "This request has changed since you opened the page. Go back to see its current state.", + "in_progress": "The same request is still being processed. Wait a moment, then go back to check.", + "key_reuse": "This form was already used for a different request. Go back and try again.", + "outcome_unavailable": "We could not confirm what happened to your earlier attempt. Go back and check your requests before trying again.", + "conflict": "This request cannot go ahead in its current state. Go back to see its current state.", + "busy": "There are too many requests right now. Wait a moment and try again.", + "unavailable": "This service is not available right now. Try again in a few minutes.", + "unconfirmed": "We could not confirm whether your request was recorded. Go back and check your requests before trying again.", + "download": "The download could not be started. Go back and try again." + } +} diff --git a/frontend/apps/web/src/i18n/messages/tr/admin.json b/frontend/apps/web/src/i18n/messages/tr/admin.json index f1a59b4a3..0b8813851 100644 --- a/frontend/apps/web/src/i18n/messages/tr/admin.json +++ b/frontend/apps/web/src/i18n/messages/tr/admin.json @@ -8,7 +8,9 @@ "invitations": "Davetler", "invitation_policy": "Davet geçerlilik süresi", "custom_fields": "Özel alanlar", - "federation": "Çoklu oturum açma" + "federation": "Çoklu oturum açma", + "data_requests": "Verileriniz", + "subject_data_requests": "Veri talepleri" }, "scope": { "tenant": "Kurum genelinde erişim", @@ -149,6 +151,134 @@ "policy_read_only": "Bu kuralı görüntüleyebilirsiniz. Düzenlemek için kurum genelinde ayar yetkisi gerekir.", "required": "Zorunlu" }, + "data_requests": { + "title": "Veri talepleri", + "detail_title": "Veri talebi", + "intro": "Mevcut erişiminizdeki üyelerin verilerinin dışa aktarılması ya da silinmesi için yapılan talepler, en yenisi en üstte. Her talebin durumunu ve sayılarını görürsünüz; verilerin kendisini hiçbir zaman görmezsiniz.", + "no_download": "Dışa aktarılan dosya yalnızca ilgili kişiye, kendi veri sayfasında sunulur. Yöneticiler bu dosyayı indiremez.", + "no_closure": "Hesap kapatma, kişinin yalnızca kendisinin yapabileceği bir taleptir ve burada gösterilmez.", + "from_member": "Dışa aktarma talebinde bulunmak için üyenin sayfasını açın. Silme talebinde bulunmak için önce üyeliği üyenin sayfasından sonlandırın; ardından silme talebinin yapıldığı sayfa açılır.", + "open_members": "Üyelere git", + "scope_tenant": "Bunlar kurum üyelikleriyle ilgili taleplerdir. Bir şube üyeliğiyle ilgili talepler o şubenin erişiminde yapılır ve orada gösterilir.", + "scope_organization": "Bunlar, mevcut şubenizdeki üyeliklerle ilgili taleplerdir.", + "list_title": "Talepler", + "empty": "Bu kapsamda henüz bir veri talebi yapılmadı.", + "next_page": "Daha eski talepler", + "back": "Veri taleplerine dön", + "concerns": "Üye", + "name_unavailable": "Üyenin adı gösterilemiyor", + "subject_revoked": "Üyeliği sonlandırılmış üye", + "filed_by": "Talep eden", + "memberships_note": "Bu talep, bu kişinin bu kapsamdaki birden fazla üyelik kaydını kapsıyor:", + "membership_record": "Üyelik kaydı", + "memberships_more": "Yalnızca ilk 20 kayıt listelenir.", + "own_data": "Kendi veri sayfanız", + "kind": { + "export": "Veri dışa aktarma", + "erasure": "Silme" + }, + "filed": { + "you": "Siz", + "other": "Başka bir yönetici", + "person": "Kişinin kendisi", + "closure": "Kişinin hesap kapatma talebi" + }, + "next": { + "export_requested": "Dışa aktarma hazırlanıyor. Bu genellikle birkaç dakika sürer.", + "export_ready": "Dosya hazır. Kişi, gösterilen tarihe kadar dosyayı kendi veri sayfasından indirebilir.", + "export_gone": "Dosya artık indirilemiyor.", + "erasure_scheduled": "Silme işlemi gösterilen zamandan sonra başlar. O zamana kadar kişi ve talebi yapan yönetici işlemi iptal edebilir.", + "erasure_scheduled_self": "Silme işlemi gösterilen zamandan sonra başlar. O zamana kadar kişi işlemi iptal edebilir.", + "erasure_fulfilling": "Üyenin bu kapsamdaki verileri siliniyor.", + "erasure_awaiting": "Üyenin bu kapsamdaki verileri silindi. İşlem kayıtlarındaki son adımı şimdi bir operatör tamamlıyor." + }, + "last_refusal": { + "blocked_window": "Bir operatör bekleme süresi dolmadan işleme başlamayı denedi.", + "blocked_hold": "Kurumun bu kişinin verilerini şimdilik saklaması gerektiği için, örneğin açık bir ödeme konusu nedeniyle, işlem durduruldu.", + "blocked_last_administrator": "Bu kişi kurumun tek yöneticisi olduğu için işlem durduruldu. Başka bir yönetici atandıktan sonra yeni bir silme talebinde bulunulabilir." + }, + "failure": { + "export_too_large": "Kişinin verileri tek bir dosyaya sığmayacak kadar büyük olduğu için dışa aktarma başarısız oldu. Dışa aktarma boyut sınırı için platform operatörüne başvurun." + }, + "collection_invitations_issued": "Kişinin gönderdiği davetler", + "retained": { + "consent_evidence": "Kişinin verdiği ya da geri çektiği izinlerin kayıtları", + "invitation_record": "Kişinin gönderdiği ya da kabul ettiği davetlerin kayıtları", + "audit_actor_reference": "Kişinin yaptığı işlemlere ait işlem kayıtları", + "audit_entity_reference": "Kişinin üyeliğiyle ilgili işlem kayıtları", + "audit_metadata_reference": "Kişiden söz eden işlem kayıtları", + "federation_actor_reference": "Kişinin tek oturum açma kurulumunda attığı adımların kayıtları", + "unserved_group": "İşlenemeyen ve kişinin verilerini şimdilik saklayan yerler" + }, + "refusal": { + "request_already_active": "Bu kapsamda bu üye için aynı türden bir talep zaten sürüyor. Tamamlanmasını bekleyin ya da talebi siz yaptıysanız iptal edin.", + "subject_membership_current": "Bu kişinin bu kapsamda hâlâ etkin ya da askıdaki bir üyeliği var. Verileri ancak bu üyelik sonlandırıldıktan sonra silinebilir.", + "blocked_hold": "Kurumun bu üyenin verilerini şimdilik saklaması gerektiği için, örneğin açık bir ödeme konusu nedeniyle, bu işlem şu anda ilerleyemiyor.", + "blocked_last_administrator": "Bu üye kurumun tek yöneticisi. Silme talebinde bulunmadan önce başka bir yönetici atayın.", + "snapshot_too_large": "Bu kişinin bu kapsamdaki üyelik kayıtları, tek bir talebin kapsayabileceğinden fazla. Yardım için platform operatörüne başvurun.", + "subject_not_admitted": "Bu kişinin hesabı kapatılıyor; bu nedenle onunla ilgili yeni bir talep oluşturulamaz.", + "data_export_unavailable": "Bu dosya artık mevcut değil; bu yüzden silinecek bir şey yok.", + "unknown": "Bu talep reddedildi. Yeniden denemeden önce güncel durumunu kontrol edin." + }, + "result": { + "export": "Dışa aktarma talep edildi. Dosya genellikle birkaç dakika içinde hazır olur ve ardından kişinin kendi veri sayfasında kullanıma sunulur.", + "erasure": "Silme talep edildi. İşlem 24 saat sonra başlar; o zamana kadar siz ya da kişi talebi iptal edebilirsiniz.", + "revoked": "Dosya silindi. Artık hiç kimse onu indiremez." + }, + "member": { + "intro": "Mevcut erişiminizde bu üyenin verileriyle ilgili talepler. Durumlarını görürsünüz; verilerin kendisini hiçbir zaman görmezsiniz.", + "other_scope": "Bu üyeyle ilgili veri talepleri üyenin kendi kapsamında yapılır. Bunları görmek ya da yeni talepte bulunmak için hesap erişiminizi o kapsama geçirin.", + "none": "Bu kapsamda bu üyeyle ilgili bir veri talebi yapılmadı.", + "unavailable": "Bu üyenin veri talepleri şu anda kontrol edilemedi. Aşağıdaki formlar yine de çalışır; her talep yapıldığı anda kontrol edilir.", + "partial": "Bu üye için yalnızca bu kapsamdaki en yeni 100 talep kontrol edildi. Daha eskileri veri talepleri sayfasındadır.", + "all": "Tüm veri talepleri" + }, + "export": { + "title": "Bu üyenin verilerini dışa aktar", + "description": "Bu kurumun bu kapsamda kişiyle ilgili tuttuğu verileri tek bir dosyada hazırlar: üyeliği ve profili, verdiği yanıtlar ve izinler, davetleri ve bu kapsamda kendisiyle ilgili işlem kayıtları. Dosya 7 gün boyunca yalnızca kişiye, kendi veri sayfasında sunulur. Siz dosyanın durumunu ve boyutunu görürsünüz, içeriğini hiçbir zaman görmezsiniz.", + "replaces": "Kişinin indirebileceği bir dosya hâlâ varken dışa aktarma talep edilemez; çünkü yeni bir dışa aktarma o dosyayı siler.", + "action": "Dışa aktarma talep et", + "active": "Bu üye için zaten bir dışa aktarma hazırlanıyor." + }, + "erasure": { + "title": "Bu üyenin verilerini sil", + "summary": "Silme işlemi kişinin bu kapsamdaki profilini ve yanıtlarını temizler ve buradaki rollerini kaldırır. Hesabı ve başka yerlerdeki üyelikleri olduğu gibi kalır.", + "revoke_first": "Önce üyeliği Üyelik erişimi bölümünden sonlandırın. Sonlandırma ayrı bir işlem olarak kaydedilir; ardından silme talebinin yapıldığı sayfa açılır.", + "start": "Silme işlemini gözden geçir", + "erased_title": "Neler silinir", + "erased_profile": "Kişinin adı, dil tercihi ve bu kapsamda verdiği yanıtlar temizlenir.", + "erased_roles": "Bu kapsamdaki rolleri kaldırılır. Sonlandırılmış üyelik boş bir kayıt olarak kalır.", + "erased_exports": "Henüz indirilebilen veri kopyaları silinir, hazırlanmakta olan bir kopya da iptal edilir.", + "erased_invitations": "Kişinin bu kapsamda gönderdiği ve henüz kimsenin kabul etmediği davetler geri çekilir.", + "kept_title": "Neler saklanır", + "kept_intro": "Bazı kayıtların saklanması gerekir. Bu kayıtlarda artık kişinin adı ya da yanıtları yer almaz, ancak kişiyi bir iç numarayla göstermeye devam ederler:", + "kept_consent": "kişinin verdiği ya da geri çektiği izinlerin kaydı, kanıt olarak;", + "kept_invitations": "kişinin gönderdiği ya da kabul ettiği davetlerin kaydı, davetin gönderildiği e-posta adresi de dahil;", + "kept_audit": "işlem kayıtları: silme işleminden sonra bir operatör, kişiyle ilgili işlem kayıtlarından ağ adreslerini, tarayıcı bilgilerini ve e-posta adreslerini çıkarır; yöneticilerin kişiyle ilgili yaptığı işlemlerin kayıtları da buna dahildir;", + "kept_attribution": "burada bir şeyi kimin oluşturduğuna ya da en son kimin değiştirdiğine dair notlar;", + "kept_receipt": "bu talep ve makbuzu.", + "timing": "Silme işlemi talebinizden 24 saat sonra başlar. O zamana kadar kişi talebi kendi veri sayfasından, siz de talebin sayfasından iptal edebilirsiniz. Kişi bu 24 saat içinde bu kapsama yeniden üye olsa bile silme işlemi yine yapılır.", + "legend": "Silme talebini onaylayın", + "confirm": "Nelerin silineceğini ve nelerin saklanacağını, silme işlemi başladıktan sonra geri alınamayacağını anlıyorum.", + "action": "Silme talep et" + }, + "erasure_page": { + "title": "Sonlandırılmış bir üyenin verilerini sil", + "revoked": "Bu üyelik sonlandırıldı. Artık üyeler arasında listelenmez ve bir üye sayfası yoktur.", + "only_revoked": "Silme talebi ancak kişinin bu kapsamda etkin ya da askıda bir üyeliği yokken yapılabilir. Aksi hâlde talep reddedilir ve hiçbir şey değişmez.", + "missing": "Hiçbir üyelik belirtilmedi. Bu sayfa, bir üyelik sonlandırıldıktan hemen sonra o üyelik için açılır." + }, + "cancel": { + "hint": "İptal etmek talebi sona erdirir. Üyeyle ilgili hiçbir şey değişmez.", + "other": "Bu talebi başka bir yönetici yaptı. Talebi yalnızca o yönetici ya da kişinin kendisi iptal edebilir.", + "person": "Bu talebi kişinin kendisi yaptı. Talebi yalnızca kişi iptal edebilir." + }, + "revoke": { + "title": "Dışa aktarılan dosyayı sil", + "hint": "Dosya silindikten sonra kişi de dahil hiç kimse onu indiremez. Talep bir kayıt olarak kalır.", + "action": "Dosyayı şimdi sil" + } + }, "custom_fields": { "title": "Özel alanlar", "detail_title": "Özel alan sürümü", diff --git a/frontend/apps/web/src/i18n/messages/tr/auth.json b/frontend/apps/web/src/i18n/messages/tr/auth.json index 58f49b262..2924f173e 100644 --- a/frontend/apps/web/src/i18n/messages/tr/auth.json +++ b/frontend/apps/web/src/i18n/messages/tr/auth.json @@ -69,7 +69,8 @@ "scope_current": "Mevcut hesap erişimi", "scope_choose": "Bu hesap erişimini kullan", "scope_back": "Hesabınıza dönün", - "scope_empty": "Başka bir hesap erişimi bulunmuyor." + "scope_empty": "Başka bir hesap erişimi bulunmuyor.", + "data_requests": "Veri talepleriniz" }, "mutation": { "title": "Değişiklik doğrulanamadı", diff --git a/frontend/apps/web/src/i18n/messages/tr/data.json b/frontend/apps/web/src/i18n/messages/tr/data.json new file mode 100644 index 000000000..79e9585fe --- /dev/null +++ b/frontend/apps/web/src/i18n/messages/tr/data.json @@ -0,0 +1,238 @@ +{ + "common": { + "title": "Verileriniz", + "skip": "İçeriğe geç", + "intro": "Burada verilerinizin bir kopyasını alabilir, verilerinizin silinmesini isteyebilir ya da hesabınızı kapatabilir ve her talebinizin durumunu izleyebilirsiniz.", + "signin": "Verilerinizle ilgili talepleri görmek ve yeni talepte bulunmak için giriş yapın.", + "signin_action": "Giriş yap", + "back_portal": "Portalınıza dön", + "back_entry": "Giriş seçeneklerine dön", + "back_page": "Veri taleplerinize dön", + "next_page": "Daha eski talepleri göster", + "next_scopes": "Diğer yerleri göster", + "required": "zorunlu", + "script_note": "Bu sayfa JavaScript olmadan da çalışır." + }, + "scope": { + "session_tenant": "Bu talepler, şu anda giriş yaptığınız kurum genelindeki üyeliğinizle ilgilidir. Şubelerdeki üyelikleriniz bundan ayrıdır: bir şubeyle ilgili talepte bulunmak için önce o şubeye geçin.", + "session_organization": "Bu talepler, şu anda giriş yaptığınız şubedeki üyeliğinizle ilgilidir. Başka bir şubeyle ya da kurum genelindeki üyeliğinizle ilgili talepte bulunmak için önce oraya geçin.", + "session_retained": "Askıya alınmış ya da sona ermiş bir üyeliğe geçilemez. Böyle bir üyelik için oturumu kapatın, yeniden giriş yapın ve nereden devam edeceğinizi seçmeden önce \"Veri talepleriniz\" bağlantısını seçin.", + "switch": "Şubeyi veya kurumu değiştir", + "entry_intro": "Burada, bu sitede üyeliğinizin bulunduğu ya da daha önce bulunduğu her yer için talepte bulunabilir ve taleplerinizi izleyebilirsiniz; üyeliğin askıya alınmış ya da sona ermiş olması buna engel değildir. Önce talebinizin hangi yer için olduğunu seçin.", + "entry_choose": "Talebinizin geçerli olacağı yer", + "entry_tenant": "Kurum genelindeki üyelik", + "entry_organization": "Şube", + "entry_names": "Şube adları burada gösterilemiyor. Şubeler her zaman aynı sırayla listelenir; ancak numaralar her sayfada birden başlar ve başka bir şubeye katıldığınızda değişebilir.", + "entry_empty": "Bu kurumda bu hesaba ait bir üyelik ya da talep bulunamadı; bu yüzden burada gösterilecek bir şey yok.", + "view": "Talepleri göster", + "entry_selected_tenant": "Kurum genelindeki üyeliğinizle ilgili talepler", + "entry_selected_organization": "Bir şubedeki üyeliğinizle ilgili talepler", + "change": "Başka bir yer seç", + "entry_time_limit": "Güvenliğiniz için bu sayfa yalnızca sınırlı bir süre çalışır: giriş yapmaya başladığınız andan itibaren en fazla 5 dakika. Bu süreden sonra yeniden giriş yapın ve \"Veri talepleriniz\" bağlantısını seçin. Daha önce yaptığınız talepler korunur.", + "entry_time_until": "Bu sayfa şu zamana kadar çalışır", + "entry_time_left": "Sayfa yüklendiğinde kalan süre", + "entry_time_under_minute": "bir dakikadan az" + }, + "result": { + "title": "İşleminiz kaydedildi", + "export": "Verilerinizin kopyası için talebiniz kaydedildi. Hazırlanması genellikle birkaç dakika sürer. Bu sayfa kendiliğinden yenilenmez; dosyanın hazır olup olmadığını görmek için daha sonra bu sayfaya dönün.", + "erasure": "Silme talebiniz kaydedildi. Silme işlemi 24 saat sonra başlar; o zamana kadar talebinizi iptal edebilirsiniz.", + "closure": "Hesap kapatma talebiniz kaydedildi. Herhangi bir işlem yapılmadan önce bir operatör talebi doğrulamak için size e-postayla ulaşır. Operatör işleme başlayana kadar talebinizi iptal edebilirsiniz.", + "cancelled": "Talep iptal edildi. Hiçbir şey değişmedi.", + "revoked": "Dosya silindi. İhtiyaç duyduğunuzda yeni bir kopya isteyebilirsiniz." + }, + "export": { + "title": "Verilerinizin bir kopyasını alın", + "description": "Bu kurumun burada sizinle ilgili tuttuğu verileri tek bir dosyada hazırlarız: üyeliğiniz ve profiliniz, verdiğiniz yanıtlar ve rızalarınız, aldığınız ya da gönderdiğiniz davetler (başka kişilerin e-posta adresleri dosyaya eklenmez) ve sizinle ilgili işlem kayıtları.", + "audit_note": "Dosyadaki işlem kayıtları, bu şubenin ya da kurumun gösterebildiği kayıtlardır. Kurumdaki geçmişinizin tamamı değildir.", + "timing": "Dosya genellikle birkaç dakika içinde hazır olur. Ardından 7 gün boyunca indirebilirsiniz. Yeni bir kopya hazır olduğunda önceki dosya silinir.", + "action": "Kopya iste", + "active": "Şu anda bir kopya hazırlanıyor. Hazırlık tamamlandıktan sonra yeniden isteyebilirsiniz." + }, + "erasure": { + "title": "Buradaki verilerinizi silin", + "summary": "Silme işlemi yalnızca bu üyelikteki profilinizi ve yanıtlarınızı temizler ve bu üyeliği sona erdirir. Hesabınız ve bu kurumdaki ya da başka yerlerdeki diğer üyelikleriniz olduğu gibi kalır.", + "start": "Silme işleminin ne anlama geldiğini gör", + "active": "Planlanmış ya da sürmekte olan bir silme işlemi zaten var. Durumunu aşağıdaki listeden izleyebilirsiniz.", + "step_title": "Silme talebinde bulunmadan önce", + "erased_title": "Neler silinir", + "erased_profile": "Bu üyelikteki adınız, dil tercihiniz ve verdiğiniz yanıtlar temizlenir.", + "erased_roles": "Bu üyelikteki rolleriniz kaldırılır ve üyelik sona erer; böylece bu üyeliğin size sağladığı erişimi kaybedersiniz.", + "erased_exports": "Bu üyeliğe ait, hâlâ indirilebilen veri kopyaları silinir; hazırlanmakta olan bir kopya da iptal edilir.", + "erased_invitations": "Bu üyelikle gönderdiğiniz ve henüz kimsenin kabul etmediği davetler geri çekilir.", + "kept_title": "Neler saklanır", + "kept_intro": "Bazı kayıtlar saklanır. Bu kayıtlarda artık adınız ya da yanıtlarınız yer almaz, ancak sizi bir iç numarayla göstermeye devam ederler:", + "kept_consent": "verdiğiniz ya da geri çektiğiniz rızaların kaydı, kanıt olarak;", + "kept_invitations": "gönderdiğiniz ya da kabul ettiğiniz davetlerin kaydı, davetin gönderildiği e-posta adresi de dahil; e-posta adresinize gönderilen ama kabul etmediğiniz davetler de saklanır, ancak sayılamaz;", + "kept_audit": "işlem kayıtları: bir operatör bu kayıtlardan ağ adresinizi, tarayıcı bilgilerinizi ve e-posta adresinizi çıkarır; ardından bu talepte kaç kaydın kaldığı gösterilir;", + "kept_attribution": "burada bir şeyi kimin oluşturduğuna ya da en son kimin değiştirdiğine dair notlar;", + "kept_receipt": "bu talebin kendisi ile dosyalarına ve indirmelerine ait kayıtlar.", + "kept_uncounted": "Bazı kopyalar saklanır ama sayılmaz: platform içi mesaj ve arka plan işlem kayıtları, tekrarlanan gönderimleri tanımak için tutulan kayıtlar, davet e-postalarının şifreli kopyaları, e-postaların teslim kopyaları, yedekler ve giriş hizmetinin günlükleri. Platform bunları henüz otomatik olarak silmez; bu nedenle uzun süre kalabilirler.", + "kept_partial": "Dolayısıyla saklananların listesi eksiksiz değildir: bir şeyin listede yer almaması, saklanmadığı anlamına gelmez.", + "timing": "Silme işlemi talebinizden 24 saat sonra başlar ve o zamana kadar buradan iptal edebilirsiniz. Silme işlemi çalıştıktan sonra işlem kayıtlarındaki son adımı bir operatör tamamlar.", + "legend": "Silme talebini onaylayın", + "confirm": "Nelerin silineceğini ve nelerin saklanacağını, silme işlemi başladıktan sonra geri alınamayacağını anlıyorum.", + "action": "Silinmesini iste", + "back": "Verilerimi koru ve geri dön" + }, + "closure": { + "title": "Hesabınızı kapatın", + "summary": "Hesabınızı kapattığınızda hesabınız her yerde sona erer: yalnızca burada değil, üyeliğinizin bulunduğu tüm kurum ve şubelerde.", + "start": "Hesabınızı kapatmanın ne anlama geldiğini gör", + "active": "Planlanmış bir hesap kapatma talebi zaten var. Aşağıdaki listeden izleyebilir ya da iptal edebilirsiniz.", + "step_title": "Hesabınızı kapatmadan önce", + "warning_title": "Devam etmeden önce bunları okuyun", + "warning_everywhere": "Hesabınız yalnızca burada değil, üyeliğinizin bulunduğu tüm kurum ve şubelerde sona erer.", + "warning_email": "Herhangi bir işlem yapılmadan önce bir operatör, bu talebi sizin yaptığınızı doğrulamak için giriş hesabınıza kayıtlı e-posta adresi üzerinden size ulaşır.", + "warning_cancel": "Operatör işleme başlayana kadar talebinizi bu sayfadan iptal edebilirsiniz.", + "warning_stops": "Operatör işleme başladığı anda hesabınız çalışmaz hale gelir. Bir daha giriş yapamazsınız ve bu işlem geri alınamaz.", + "warning_no_status": "Bu noktadan sonra kapatma işlemini izleyebileceğiniz bir sayfa kalmaz. İşlem tamamlandığında operatör size e-postayla bildirir.", + "warning_data": "Ardından verileriniz bunun mümkün olduğu her kurumda ve şubede silinir ve giriş hesabınız kaldırılır. Saklanan kayıtlar silme işlemindekiyle aynıdır ve aşağıda açıklanmıştır.", + "warning_unserved": "Askıya alınmış ya da arşivlenmiş bir kurumda veya etkin olmayan bir şubede verileriniz silinmez: platform bunları henüz kullanıma sunulmamış ayrı bir adımda ele alana kadar orada kalır. Bunu size daha sonra gösterecek bir sayfa olmayacaktır.", + "legend": "Hesap kapatma talebini onaylayın", + "confirm_irreversible": "Hesabımın her yerde çalışmaz hale geleceğini ve bunun geri alınamayacağını anlıyorum.", + "confirm_no_status": "Kapatma işlemi başladıktan sonra durumunu izleyebileceğim bir sayfa kalmayacağını anlıyorum.", + "action": "Hesabımın kapatılmasını iste", + "back": "Hesabımı koru ve geri dön" + }, + "list": { + "title": "Talepleriniz", + "empty": "Burada henüz bir talepte bulunmadınız.", + "status": "Durum", + "requested": "Talep tarihi", + "runs_after": "Şu zamandan sonra başlar", + "earliest": "En erken başlama zamanı", + "ended": "Sona erme", + "completed": "Tamamlanma", + "available_until": "Şu tarihe kadar indirilebilir", + "expired_on": "Şu zamandan beri indirilemiyor", + "size": "Dosya boyutu", + "by_administrator": "Bu talep, bu kurumun bir yöneticisi tarafından sizinle ilgili olarak yapıldı.", + "by_closure": "Bu silme işlemi hesap kapatma talebinizin bir parçasıdır." + }, + "kind": { + "export": "Veri kopyası", + "erasure": "Silme", + "closure": "Hesap kapatma" + }, + "status": { + "requested": "Talep edildi", + "scheduled": "Planlandı", + "due": "Birazdan başlıyor", + "fulfilling": "Sürüyor", + "awaiting_privileged_step": "Operatör bekleniyor", + "completed": "Tamamlandı", + "blocked": "Durduruldu", + "failed": "Başarısız", + "cancelled": "İptal edildi" + }, + "next": { + "export_requested": "Dosyanızı hazırlıyoruz. Bu genellikle birkaç dakika sürer; hazır olup olmadığını görmek için daha sonra bu sayfaya dönün.", + "export_ready": "Dosyanız hazır. Gösterilen tarihten önce indirin.", + "export_gone": "Bu dosya artık indirilemiyor. İhtiyacınız varsa yeni bir kopya isteyin.", + "erasure_scheduled": "Silme işlemi gösterilen zamandan sonra başlar. O zamana kadar iptal edebilirsiniz.", + "erasure_due": "Bekleme süresi doldu ve silme işlemi birazdan başlayacak. Artık iptal edilemez.", + "erasure_fulfilling": "Buradaki verileriniz siliniyor.", + "erasure_awaiting": "Buradaki verileriniz silindi. İşlem kayıtlarındaki son adımı şimdi bir operatör tamamlıyor. Sizin bir şey yapmanız gerekmiyor.", + "erasure_completed": "Silme işlemi tamamlandı. Saklanan kayıtlar aşağıdaki listede yer alıyor.", + "closure_scheduled": "Bir operatör işleme başlamadan önce doğrulamak için size e-postayla ulaşır; işleme en erken gösterilen zamanda başlanabilir. Operatör başlayana kadar iptal edebilirsiniz.", + "closure_fulfilling": "Hesap kapatma işleminiz başladı ve geri alınamaz.", + "closure_completed": "Hesap kapatma işleminiz tamamlandı.", + "blocked": "Bu talep, hiçbir şey silinmeden önce durduruldu.", + "failed": "Bu talep tamamlanamadı.", + "cancelled": "Bu talep iptal edildi. Hiçbir şey değişmedi." + }, + "blocked_reason": { + "blocked_hold": "Buradaki verileriniz bekletmeye alındığı için, örneğin açık bir ödeme konusu nedeniyle, durduruldu. Kurumla iletişime geçin; bekletme kaldırıldığında yeniden talepte bulunabilirsiniz.", + "blocked_last_administrator": "Bu kurumun tek yöneticisi siz olduğunuz için durduruldu. Başka bir yönetici atandıktan sonra yeniden talepte bulunabilirsiniz." + }, + "last_refusal": { + "blocked_window": "Bir operatör bekleme süresi dolmadan işleme başlamayı denedi. Talebiniz hâlâ planlı durumda.", + "blocked_hold": "Verileriniz bekletmeye alındığı için, örneğin açık bir ödeme konusu nedeniyle, talebiniz henüz ilerleyemiyor. Talebiniz planlı olarak kalır ve iptal edebilirsiniz.", + "blocked_last_administrator": "Bir kurumun tek yöneticisi sizsiniz. Bu talebin ilerleyebilmesi için orada başka bir yöneticinin atanması gerekiyor. Talebiniz planlı olarak kalır ve iptal edebilirsiniz." + }, + "failure": { + "export_too_large": "Verileriniz tek bir dosyaya sığmayacak kadar büyük. Yeniden istemeden önce yardım için kurumla iletişime geçin.", + "execution_failed": "Bu talep yerine getirilirken bir sorun oluştu. Yeni bir talepte bulunabilirsiniz." + }, + "artifact": { + "download": "Dosyanızı indir", + "download_hint": "Dosya, JSON biçiminde yapılandırılmış bir metin dosyasıdır. Her indirme kayıt altına alınır.", + "delete": "Bu dosyayı şimdi sil", + "delete_hint": "Dosya silindikten sonra siz de dahil hiç kimse onu indiremez.", + "truncated": "Dosyanın bazı bölümleri boyut sınırını aşmaması için kısaltıldı:", + "truncated_included": "eklendi", + "truncated_total": "toplam", + "part_included": "Dosyaya eklenen", + "part_total": "Toplam", + "collection_audit_entries": "İşlem kayıtları", + "collection_invitations_issued": "Gönderdiğiniz davetler", + "collection_other": "Dosyanın başka bir bölümü" + }, + "entry": { + "download_deadline": "İndirme, bu sayfa yukarıda gösterilen zamanda çalışmayı bırakmadan önce bitmelidir: o sırada süren bir indirme, dosya tamamlanmadan durur. Büyük bir dosyanın inmesi birkaç dakika sürebilir; az zaman kaldıysa indirmeden önce yeniden giriş yapın.", + "step_deadline": "Formu, bu sayfa yukarıda gösterilen zamanda çalışmayı bırakmadan önce gönderin. Sonrasında yeniden giriş yapıp bu adıma dönün: formu gönderene kadar hiçbir şey kaydedilmez." + }, + "retained": { + "title": "Neler saklanıyor", + "intro": "Aşağıdaki kayıtlar, kurumun sayabildiği adetlerle birlikte saklanıyor:", + "pending": "İşlem kayıtlarının sayıları geçicidir: bir operatör son adımı tamamladığında bunların yerini kesin sayılar alır; bu sayılar farklı olabilir.", + "partial": "Bu liste eksiksiz değildir: listede yer almayan bir şey de sayılmadan saklanıyor olabilir. Platform içi mesaj ve arka plan işlem kayıtları, tekrarlanan gönderimleri tanımak için tutulan kayıtlar, davet e-postalarının şifreli kopyaları, e-postaların teslim kopyaları, yedekler ve giriş hizmetinin günlükleri bu şekilde saklanır; platform bunları henüz otomatik olarak silmez.", + "audit_retention": "İşlem kayıtlarının ne kadar süre saklanacağını platformun saklama kuralları belirler; ancak bu kayıtların silinmesi henüz otomatik değildir, bu nedenle daha uzun süre saklanabilirler.", + "kind": { + "consent_evidence": "Verdiğiniz ya da geri çektiğiniz rızaların kayıtları", + "invitation_record": "Gönderdiğiniz ya da kabul ettiğiniz davetlerin kayıtları", + "invitation_envelope": "Davet e-postalarının şifreli kopyaları", + "audit_actor_reference": "Yaptığınız işlemlere ait işlem kayıtları", + "audit_entity_reference": "Üyeliğinizle ilgili işlem kayıtları", + "audit_metadata_reference": "Sizden söz eden işlem kayıtları", + "unscoped_audit_rows": "Bu talebin ulaşamadığı, kurumun başka yerlerindeki işlem kayıtları", + "transport_evidence": "Platformun bölümleri arasındaki mesajların kayıtları", + "execution_evidence": "Arka plan işlem kayıtları", + "provider_event_record": "Giriş hizmetinden gelen kayıtlar", + "idempotency_cache": "Tekrarlanan gönderimleri tanımak için tutulan kayıtlar", + "attribution_reference": "Bir şeyi kimin oluşturduğuna ya da değiştirdiğine dair notlar", + "federation_actor_reference": "Tek oturum açma kurulumunda attığınız adımların kayıtları", + "request_receipt": "Veri talepleri, dosyalar ve indirme kayıtları", + "external_copy": "Platform dışındaki kopyalar, örneğin e-posta teslim kopyaları ve yedekler", + "unserved_group": "İşlenemeyen ve verilerinizi şimdilik saklayan yerler" + } + }, + "action": { + "cancel": "Bu talebi iptal et", + "cancel_closure": "Hesap kapatma talebini iptal et" + }, + "refusal": { + "request_already_active": "Burada aynı türden, devam eden bir talebiniz zaten var. Yeni bir talepte bulunmadan önce tamamlanmasını bekleyin ya da iptal edin.", + "blocked_hold": "Buradaki verileriniz bekletmeye alındığı için, örneğin açık bir ödeme konusu nedeniyle, bu işlem şu anda ilerleyemiyor. Sorularınız için kurumla iletişime geçin.", + "blocked_last_administrator": "Bu kurumun tek yöneticisi sizsiniz. Verilerinizin silinebilmesi için önce başka bir yöneticinin atanması gerekiyor.", + "subject_export_available": "Verilerin indirilebilir bir kopyası zaten var. O dosya silindikten ya da indirme süresi dolduktan sonra yeni bir kopya istenebilir.", + "subject_membership_current": "Bu üyelik hâlâ etkin ya da askıda. Bir yöneticinin silme talebinde bulunabilmesi için önce üyeliğin sona ermesi gerekir.", + "data_export_unavailable": "Bu dosya artık indirilemiyor. Yeni bir kopya isteyin.", + "data_request_window_ended": "Bu silme işleminin bekleme süresi doldu; bu nedenle artık iptal edilemez. İşlem birazdan başlar.", + "data_request_not_cancellable": "Bu talep artık iptal edilemez: işlem başladı ya da sona erdi.", + "subject_is_requester": "Kendi verilerinizle ilgili talepleri kendi veri sayfanızdan yaparsınız.", + "snapshot_too_large": "Bu talep, tek bir talebin kapsayabileceğinden daha fazla üyeliği içeriyor. Yardım için kurumla iletişime geçin.", + "data_export_ticket_limit": "Bu dosya kısa sürede ya da toplamda çok fazla kez indirildi. 15 dakika bekleyip yeniden deneyin; yine olmazsa yeni bir kopya isteyin.", + "subject_not_admitted": "Hesabınız kapatılıyor; bu nedenle yeni bir talep oluşturulamaz." + }, + "error": { + "title": "Bir sorun oluştu", + "title_unconfirmed": "Sonuç henüz doğrulanmadı", + "input": "Form okunamadı. Veri taleplerinize dönüp yeniden deneyin.", + "confirmation": "Devam etmek için tüm onay kutularını işaretleyin.", + "csrf": "Bu sayfanın süresi doldu. Veri taleplerinize dönüp yeniden deneyin.", + "unauthorized": "Oturumunuz sona erdi. Devam etmek için yeniden giriş yapın.", + "forbidden": "Bu işlemi burada yapamazsınız.", + "not_found": "Bu talep ya da dosya bulunamadı. Başka bir şubeye ait olabilir ya da buradaki erişiminiz değişmiş olabilir.", + "stale": "Siz sayfayı açtıktan sonra bu talep değişti. Güncel durumunu görmek için geri dönün.", + "in_progress": "Aynı talep hâlâ işleniyor. Biraz bekleyin, ardından kontrol etmek için geri dönün.", + "key_reuse": "Bu form başka bir talep için zaten kullanıldı. Geri dönüp yeniden deneyin.", + "outcome_unavailable": "Önceki denemenizin sonucunu doğrulayamadık. Yeniden denemeden önce geri dönüp taleplerinizi kontrol edin.", + "conflict": "Bu talep mevcut durumunda ilerleyemiyor. Güncel durumunu görmek için geri dönün.", + "busy": "Şu anda çok fazla istek var. Biraz bekleyip yeniden deneyin.", + "unavailable": "Bu hizmet şu anda kullanılamıyor. Birkaç dakika sonra yeniden deneyin.", + "unconfirmed": "Talebinizin kaydedilip kaydedilmediğini doğrulayamadık. Yeniden denemeden önce geri dönüp taleplerinizi kontrol edin.", + "download": "İndirme başlatılamadı. Geri dönüp yeniden deneyin." + } +} diff --git a/frontend/apps/web/src/server/auth/consent-response-contract.ts b/frontend/apps/web/src/server/auth/consent-response-contract.ts index 7deb3b7b1..1b49a0454 100644 --- a/frontend/apps/web/src/server/auth/consent-response-contract.ts +++ b/frontend/apps/web/src/server/auth/consent-response-contract.ts @@ -4,7 +4,7 @@ import type { ConsentReceipt, } from '@learnstack/sdk/administration-server'; -import type { NativeConsentSnapshot } from './page-contract.js'; +import type { NativeConsentSnapshot, NativeDataRequestSnapshot } from './page-contract.js'; export type NativeConsentResponseLease = Readonly<{ signal: AbortSignal; cleaned: Promise; @@ -19,3 +19,10 @@ export type NativeConsentData = Readonly<{ formKeys: readonly string[]; }>; export type NativeConsentReceipt = ConsentReceipt; +/** ADR-0106 § 9: the data-request document's lifetime, pinned to its live session or entry owner. */ +export type NativeDataRequestResponseLease = Readonly<{ + signal: AbortSignal; + cleaned: Promise; + pin: (assert: () => void, owner: object, expiresInMs: number) => void; + publish: (value: NativeDataRequestSnapshot) => NativeDataRequestSnapshot; +}>; diff --git a/frontend/apps/web/src/server/auth/data-export-download.test.ts b/frontend/apps/web/src/server/auth/data-export-download.test.ts new file mode 100644 index 000000000..ace4a6cc1 --- /dev/null +++ b/frontend/apps/web/src/server/auth/data-export-download.test.ts @@ -0,0 +1,655 @@ +// @vitest-environment node +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { DATA_EXPORT_STALL_MS, relayDataExport } from './data-export-download'; +import type { DataExportSink } from './data-export-download'; +import type { NativeOperationResult } from './native-operation-contract'; + +const full = 128 * 1024; +const ticket = 'T'.repeat(42) + 'A'; +const renewed = 'R'.repeat(42) + 'A'; +const start = Date.parse('2026-11-23T12:00:00Z'); +const ok = (data: unknown) => + ({ + kind: 'success', + status: 200, + data, + etag: null, + location: null, + replayed: false, + }) as NativeOperationResult; +const refusal = (status: number, code: string, retryAfter?: number) => + ({ + kind: 'api-error', + status, + error: { code, ...(retryAfter === undefined ? {} : { retryAfter }) }, + problem: { + type: 't', + title: 't', + status, + instance: '/', + code, + messageKey: 'lockey_' + code, + correlationId: 'c', + }, + }) as NativeOperationResult; +const notFound = refusal(404, 'not_found'); +const limited = (retryAfter?: number) => refusal(429, 'rate_limited', retryAfter); +const unavailable = (retryAfter?: number) => refusal(503, 'audit_unavailable', retryAfter); +const minted = ( + value: Partial<{ ticket: string; chunkCount: number; byteCount: number; expiresAt: string }> = {}, +) => + ok({ + ticket, + expiresAt: '2026-11-23T12:15:00Z', + chunkCount: 3, + byteCount: 2 * full + 7, + ...value, + }); +const bytes = (index: number) => Buffer.alloc(index < 2 ? full : 7, 0x30 + index); +const chunk = ( + index: number, + value: Partial<{ index: number; count: number; bytes: string }> = {}, +) => ok({ index, count: 3, bytes: bytes(index).toString('base64'), ...value }); +const bundle = () => Buffer.concat([bytes(0), bytes(1), bytes(2)]); + +/** + * A socket stand-in that takes a buffer only when it acknowledges the write, a microtask later (or when a held write + * is released): a buffer zeroed before that point arrives as zeros, exactly as it would on a real socket. + */ +function sink(mode: 'acknowledge' | 'hold' | 'refuse' | 'stall' = 'acknowledge') { + const written: Buffer[] = []; + const handed: Buffer[] = []; + const events: string[] = []; + const held: (() => void)[] = []; + const value: DataExportSink & { + written: Buffer[]; + handed: Buffer[]; + events: string[]; + held: (() => void)[]; + } = { + written, + handed, + events, + held, + begin: vi.fn((byteCount: number) => { + events.push('begin:' + byteCount); + }), + write: vi.fn((buffer: Buffer) => { + handed.push(buffer); + if (mode === 'refuse') return Promise.reject(new Error('closed')); + if (mode === 'stall') return new Promise(() => undefined); + return new Promise((resolve) => { + const acknowledge = () => { + written.push(Buffer.from(buffer)); + events.push('write'); + resolve(); + }; + if (mode === 'hold') held.push(acknowledge); + else queueMicrotask(acknowledge); + }); + }), + end: vi.fn(async () => { + events.push('end'); + }), + abort: vi.fn(() => { + events.push('abort'); + }), + }; + return value; +} +const clock = () => start; +/** Lets every continuation that does not wait for a timer run. */ +const flush = async () => { + for (let turn = 0; turn < 200; ++turn) await Promise.resolve(); +}; +const relay = ( + input: Partial[0]> & + Pick[0], 'read'>, +) => + relayDataExport({ + mint: async () => minted(), + sink: sink(), + signal: new AbortController().signal, + now: clock, + ...input, + }); + +afterEach(() => { + vi.useRealTimers(); +}); + +describe('ADR-0107 § 4 download relay', () => { + it('relays every chunk in order with the exact length, then zeroes each buffer once taken', async () => { + const out = sink(); + const read = vi.fn(async (_ticket: string, index: number) => chunk(index)); + expect(await relay({ read, sink: out })).toEqual({ kind: 'completed' }); + expect(out.events).toEqual(['begin:' + (2 * full + 7), 'write', 'write', 'write', 'end']); + // The sink copies at acknowledgement: a buffer zeroed before the socket took it would compare unequal. + expect(Buffer.concat(out.written).equals(bundle())).toBe(true); + expect(read.mock.calls.map(([, index]) => index)).toEqual([0, 1, 2]); + for (const buffer of out.handed) expect(buffer.every((byte) => byte === 0)).toBe(true); + }); + + it('keeps one chunk in flight: the next read waits until the socket took the previous one', async () => { + const out = sink('hold'); + const read = vi.fn(async (_ticket: string, index: number) => chunk(index)); + const run = relay({ read, sink: out }); + for (let taken = 0; taken < 3; ++taken) { + await flush(); + expect(read).toHaveBeenCalledTimes(taken + 1); + expect(out.held).toHaveLength(1); + // Still held: the buffer handed to the socket is intact until the write settles. + expect(out.handed[taken]!.equals(bytes(taken))).toBe(true); + out.held.shift()!(); + } + expect(await run).toEqual({ kind: 'completed' }); + expect(read).toHaveBeenCalledTimes(3); + }); + + it('refuses before any byte when the ticket is refused or the first chunk fails', async () => { + const limit = refusal(409, 'business_rule_violation'); + const out = sink(); + expect(await relay({ mint: async () => limit, read: vi.fn(), sink: out })).toEqual({ + kind: 'refused', + stage: 'ticket', + result: limit, + }); + const failed = { kind: 'transport-error' } as NativeOperationResult; + expect(await relay({ read: async () => failed, sink: out })).toEqual({ + kind: 'refused', + stage: 'chunk', + result: failed, + }); + expect(out.begin).not.toHaveBeenCalled(); + expect(out.abort).not.toHaveBeenCalled(); + }); + + const malformed = [ + ['a chunk of another index', 1, chunk(1, { index: 2 })], + ['a chunk of another count', 1, chunk(1, { count: 4 })], + ['a short full chunk', 1, chunk(1, { bytes: Buffer.alloc(full - 1).toString('base64') })], + ['an oversized last chunk', 2, chunk(2, { bytes: Buffer.alloc(8).toString('base64') })], + ] as const; + it.each(malformed)( + 'aborts after the headers on %s and never ends the body', + async (_name, at, bad) => { + const out = sink(); + const outcome = await relay({ + read: async (_ticket, index) => (index === at ? bad : chunk(index)), + sink: out, + }); + expect(outcome).toEqual({ kind: 'aborted' }); + expect(out.events.at(-1)).toBe('abort'); + expect(out.end).not.toHaveBeenCalled(); + }, + ); + + it.each([ + ['a first chunk of another index', chunk(0, { index: 1 })], + ['a first chunk of another count', chunk(0, { count: 4 })], + ['a short first chunk', chunk(0, { bytes: Buffer.alloc(full - 1).toString('base64') })], + ['an oversized first chunk', chunk(0, { bytes: Buffer.alloc(full + 3).toString('base64') })], + ])('proves the first chunk before any header: %s is a clean refusal', async (_name, bad) => { + const out = sink(); + expect(await relay({ read: async () => bad, sink: out })).toEqual({ + kind: 'refused', + stage: 'chunk', + result: null, + }); + expect(out.begin).not.toHaveBeenCalled(); + expect(out.write).not.toHaveBeenCalled(); + expect(out.abort).not.toHaveBeenCalled(); + }); + + it('refuses a ticket whose geometry contradicts the chunk size or whose expiry is no instant', async () => { + for (const ticketValue of [minted({ chunkCount: 2 }), minted({ expiresAt: 'later' })]) { + const read = vi.fn(); + expect(await relay({ mint: async () => ticketValue, read })).toEqual({ + kind: 'refused', + stage: 'ticket', + result: null, + }); + expect(read).not.toHaveBeenCalled(); + } + }); + + it('resumes at the failed index with a new ticket after any 404', async () => { + const out = sink(); + const tickets: string[] = []; + let mints = 0; + const outcome = await relay({ + mint: async () => minted(mints++ === 0 ? {} : { ticket: renewed }), + read: async (value, index) => { + tickets.push(value + ':' + index); + return value === ticket && index === 1 ? notFound : chunk(index); + }, + sink: out, + }); + expect(outcome).toEqual({ kind: 'completed' }); + expect(tickets).toEqual([ticket + ':0', ticket + ':1', renewed + ':1', renewed + ':2']); + expect(Buffer.concat(out.written).equals(bundle())).toBe(true); + }); + + it('stops after exactly two renewals, and when a renewal changes the bundle', async () => { + let out = sink(); + let mints = 0; + expect( + await relay({ + mint: async () => { + mints += 1; + return minted(); + }, + read: async (_ticket, index) => (index === 0 ? chunk(0) : notFound), + sink: out, + }), + ).toEqual({ kind: 'aborted' }); + // The first ticket and two renewals: a third renewal is never minted. + expect(mints).toBe(3); + out = sink(); + mints = 0; + expect( + await relay({ + mint: async () => minted(mints++ ? { chunkCount: 4, byteCount: 3 * full + 1 } : {}), + read: async (_ticket, index) => (index === 0 ? chunk(0) : notFound), + sink: out, + }), + ).toEqual({ kind: 'aborted' }); + expect(out.abort).toHaveBeenCalledOnce(); + }); + + it('answers a renewal refused before any byte as the ticket’s refusal', async () => { + const out = sink(); + let first = true; + const gone = refusal(409, 'business_rule_violation'); + expect( + await relay({ + mint: async () => { + if (first) { + first = false; + return minted(); + } + return gone; + }, + read: async () => notFound, + sink: out, + }), + ).toEqual({ kind: 'refused', stage: 'ticket', result: gone }); + expect(out.begin).not.toHaveBeenCalled(); + }); + + it('destroys the connection when a renewal is refused after bytes were sent', async () => { + const out = sink(); + let first = true; + const gone = refusal(409, 'business_rule_violation'); + expect( + await relay({ + mint: async () => { + if (first) { + first = false; + return minted(); + } + return gone; + }, + read: async (_ticket, index) => (index === 0 ? chunk(0) : notFound), + sink: out, + }), + ).toEqual({ kind: 'aborted' }); + expect(out.events).toEqual(['begin:' + (2 * full + 7), 'write', 'abort']); + expect(out.end).not.toHaveBeenCalled(); + }); + + it('aborts on cancellation, on the ticket deadline and on a sink that takes no more', async () => { + const controller = new AbortController(); + let out = sink(); + expect( + await relay({ + read: async (_ticket, index) => { + if (index === 1) controller.abort(); + return chunk(index); + }, + sink: out, + signal: controller.signal, + }), + ).toEqual({ kind: 'aborted' }); + expect(out.end).not.toHaveBeenCalled(); + out = sink(); + let time = start; + expect( + await relay({ + read: async (_ticket, index) => { + time += 16 * 60 * 1000; + return chunk(index); + }, + sink: out, + now: () => time, + }), + ).toEqual({ kind: 'aborted' }); + out = sink('refuse'); + expect(await relay({ read: async (_ticket, index) => chunk(index), sink: out })).toEqual({ + kind: 'aborted', + }); + expect(out.abort).toHaveBeenCalledOnce(); + expect(out.handed[0]!.every((byte) => byte === 0)).toBe(true); + }); + + it('ends at a ticket expiry earlier than fifteen minutes, and at the owner’s end', async () => { + let out = sink(); + let time = start; + expect( + await relay({ + mint: async () => minted({ expiresAt: '2026-11-23T12:02:00Z' }), + read: async (_ticket, index) => { + if (index === 1) time += 3 * 60 * 1000; + return chunk(index); + }, + sink: out, + now: () => time, + }), + ).toEqual({ kind: 'aborted' }); + expect(out.end).not.toHaveBeenCalled(); + out = sink(); + time = start; + expect( + await relay({ + read: async (_ticket, index) => { + if (index === 1) time += 2 * 60 * 1000; + return chunk(index); + }, + sink: out, + now: () => time, + ownerDeadline: start + 60 * 1000, + }), + ).toEqual({ kind: 'aborted' }); + expect(out.end).not.toHaveBeenCalled(); + }); +}); + +describe('ADR-0107 § 4 download relay under the API admission budget', () => { + const paced = () => { + vi.useFakeTimers({ now: start, toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + return () => Date.now(); + }; + + it('pauses on a 429 for its Retry-After, then reads the same index with the same ticket', async () => { + const now = paced(); + const out = sink(); + const reads: string[] = []; + let refused = false; + let mints = 0; + const run = relay({ + mint: async () => { + mints += 1; + return minted(); + }, + read: async (value, index) => { + reads.push(value + ':' + index); + if (index === 1 && !refused) { + refused = true; + return limited(7); + } + return chunk(index); + }, + sink: out, + now, + }); + await flush(); + expect(reads).toEqual([ticket + ':0', ticket + ':1']); + await vi.advanceTimersByTimeAsync(6999); + expect(reads).toHaveLength(2); + await vi.advanceTimersByTimeAsync(1); + expect(await run).toEqual({ kind: 'completed' }); + expect(reads).toEqual([ticket + ':0', ticket + ':1', ticket + ':1', ticket + ':2']); + expect(mints).toBe(1); + expect(Buffer.concat(out.written).equals(bundle())).toBe(true); + }); + + it('waits the default when a 429 names no usable Retry-After, and a 503 only when it names one', async () => { + const now = paced(); + let refused = false; + const reads: number[] = []; + const run = relay({ + read: async (_ticket, index) => { + reads.push(index); + if (index === 2 && !refused) { + refused = true; + return limited(); + } + return chunk(index); + }, + now, + }); + await flush(); + expect(reads).toEqual([0, 1, 2]); + await vi.advanceTimersByTimeAsync(4999); + expect(reads).toHaveLength(3); + await vi.advanceTimersByTimeAsync(1); + expect(await run).toEqual({ kind: 'completed' }); + expect(reads).toEqual([0, 1, 2, 2]); + + refused = false; + const paused = relay({ + read: async (_ticket, index) => { + if (index === 1 && !refused) { + refused = true; + return unavailable(30); + } + return chunk(index); + }, + now, + }); + await flush(); + await vi.advanceTimersByTimeAsync(30_000); + expect(await paused).toEqual({ kind: 'completed' }); + + // A 503 without Retry-After is a failure: after the headers it destroys the connection. + const out = sink(); + expect( + await relay({ + read: async (_ticket, index) => (index === 1 ? unavailable() : chunk(index)), + sink: out, + now, + }), + ).toEqual({ kind: 'aborted' }); + expect(out.abort).toHaveBeenCalledOnce(); + }); + + it('keeps pausing through repeated 429s, at least a second and at most a minute each, without spending a renewal', async () => { + const now = paced(); + const answers = [limited(0), limited(3600), limited(2), notFound, notFound]; + const reads: string[] = []; + let mints = 0; + const run = relay({ + mint: async () => minted(mints++ === 0 ? {} : { ticket: renewed }), + read: async (value, index) => { + reads.push(value.slice(0, 1) + index); + return index === 1 && answers.length ? answers.shift()! : chunk(index); + }, + now, + }); + await flush(); + expect(reads).toEqual(['T0', 'T1']); + // Retry-After 0 still waits a second. + await vi.advanceTimersByTimeAsync(999); + expect(reads).toHaveLength(2); + await vi.advanceTimersByTimeAsync(1); + expect(reads).toHaveLength(3); + // Retry-After 3600 is capped at one minute. + await vi.advanceTimersByTimeAsync(59_999); + expect(reads).toHaveLength(3); + await vi.advanceTimersByTimeAsync(1); + expect(reads).toHaveLength(4); + await vi.advanceTimersByTimeAsync(2000); + // Three pauses spent no renewal: both 404s still resume. + expect(await run).toEqual({ kind: 'completed' }); + expect(reads).toEqual(['T0', 'T1', 'T1', 'T1', 'T1', 'R1', 'R1', 'R2']); + expect(mints).toBe(3); + }); + + it('pauses a renewal the API refuses at admission, then mints again', async () => { + const now = paced(); + const answers = [minted(), limited(3), minted({ ticket: renewed })]; + const reads: string[] = []; + let mints = 0; + const run = relay({ + mint: async () => { + mints += 1; + return answers.shift()!; + }, + read: async (value, index) => { + reads.push(value.slice(0, 1) + index); + return value === ticket && index === 1 ? notFound : chunk(index); + }, + now, + }); + await flush(); + expect(mints).toBe(2); + await vi.advanceTimersByTimeAsync(2999); + expect(mints).toBe(2); + await vi.advanceTimersByTimeAsync(1); + expect(await run).toEqual({ kind: 'completed' }); + expect(mints).toBe(3); + expect(reads).toEqual(['T0', 'T1', 'R1', 'R2']); + }); + + it('does not take a pause that would reach the deadline: it destroys the connection at once', async () => { + const now = paced(); + let out = sink(); + expect( + await relay({ + mint: async () => minted({ expiresAt: '2026-11-23T12:00:30Z' }), + read: async (_ticket, index) => (index === 1 ? limited(40) : chunk(index)), + sink: out, + now, + }), + ).toEqual({ kind: 'aborted' }); + expect(out.events).toEqual(['begin:' + (2 * full + 7), 'write', 'abort']); + expect(Date.now()).toBe(start); + out = sink(); + expect( + await relay({ + read: async (_ticket, index) => (index === 1 ? limited(30) : chunk(index)), + sink: out, + now, + ownerDeadline: start + 20_000, + }), + ).toEqual({ kind: 'aborted' }); + expect(Date.now()).toBe(start); + }); + + it('pauses before the headers too, but refuses cleanly when the first chunk cannot start within a minute', async () => { + const now = paced(); + let out = sink(); + let refused = false; + const run = relay({ + read: async (_ticket, index) => { + if (index === 0 && !refused) { + refused = true; + return limited(20); + } + return chunk(index); + }, + sink: out, + now, + }); + await flush(); + // Nothing is promised to the browser while the first chunk waits. + expect(out.begin).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(20_000); + expect(await run).toEqual({ kind: 'completed' }); + expect(out.events[0]).toBe('begin:' + (2 * full + 7)); + + out = sink(); + const busy = limited(60); + expect( + await relay({ + read: async (_ticket, index) => (index === 0 ? busy : chunk(index)), + sink: out, + now, + }), + ).toEqual({ kind: 'refused', stage: 'chunk', result: busy }); + expect(out.begin).not.toHaveBeenCalled(); + expect(Date.now()).toBe(start + 20_000); + }); + + it('ends a pause at once when the response is cancelled', async () => { + const now = paced(); + const controller = new AbortController(); + const out = sink(); + const run = relay({ + read: async (_ticket, index) => (index === 1 ? limited(30) : chunk(index)), + sink: out, + signal: controller.signal, + now, + }); + await flush(); + controller.abort(); + expect(await run).toEqual({ kind: 'aborted' }); + expect(Date.now()).toBe(start); + }); +}); + +describe('ADR-0107 § 4 download relay against a stalled client', () => { + const paced = () => { + vi.useFakeTimers({ now: start, toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + return () => Date.now(); + }; + + it('destroys the connection when a write makes no progress, and zeroes the held buffer', async () => { + const now = paced(); + const out = sink('stall'); + const run = relay({ read: async (_ticket, index) => chunk(index), sink: out, now }); + await flush(); + await vi.advanceTimersByTimeAsync(DATA_EXPORT_STALL_MS - 1); + expect(out.abort).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + expect(await run).toEqual({ kind: 'aborted' }); + expect(out.abort).toHaveBeenCalledOnce(); + expect(out.end).not.toHaveBeenCalled(); + expect(out.handed).toHaveLength(1); + expect(out.handed[0]!.every((byte) => byte === 0)).toBe(true); + }); + + it('cuts a pending write at the deadline when that comes first, and a stalled end too', async () => { + const now = paced(); + let out = sink('stall'); + const run = relay({ + mint: async () => minted({ expiresAt: '2026-11-23T12:00:10Z' }), + read: async (_ticket, index) => chunk(index), + sink: out, + now, + }); + await flush(); + await vi.advanceTimersByTimeAsync(10_000); + expect(await run).toEqual({ kind: 'aborted' }); + expect(out.abort).toHaveBeenCalledOnce(); + + out = sink(); + const never = new Promise(() => undefined); + const stalledEnd = relay({ + read: async (_ticket, index) => chunk(index), + sink: { ...out, end: () => never }, + now, + }); + await flush(); + await vi.advanceTimersByTimeAsync(DATA_EXPORT_STALL_MS); + expect(await stalledEnd).toEqual({ kind: 'aborted' }); + expect(out.abort).toHaveBeenCalledOnce(); + }); + + it('stops waiting for a write as soon as the response is cancelled', async () => { + const now = paced(); + const controller = new AbortController(); + const out = sink('stall'); + const run = relay({ + read: async (_ticket, index) => chunk(index), + sink: out, + signal: controller.signal, + now, + }); + await flush(); + controller.abort(); + expect(await run).toEqual({ kind: 'aborted' }); + expect(Date.now()).toBe(start); + }); +}); diff --git a/frontend/apps/web/src/server/auth/data-export-download.ts b/frontend/apps/web/src/server/auth/data-export-download.ts new file mode 100644 index 000000000..665f96381 --- /dev/null +++ b/frontend/apps/web/src/server/auth/data-export-download.ts @@ -0,0 +1,216 @@ +import type { DataExportChunk, DataExportTicket } from '@learnstack/sdk/administration-server'; + +import type { NativeOperationResult } from './native-operation-contract.js'; + +/** ADR-0107 § 4: every chunk but the last holds exactly this much plaintext. */ +const CHUNK_BYTES = 128 * 1024; +/** A ticket authorizes reads for fifteen minutes; no relay outlives it. */ +const TICKET_LIFETIME_MS = 15 * 60 * 1000; +/** + * The API answers every chunk refusal with the same `404`. A ticket is bound to the credential that minted it, so a + * refresh during a long download ends that ticket and the next chunk answers `404`; a chunk the API cannot open + * answers the same. The OpenAPI document's recovery is a new ticket resumed at the failed index: the relay does that + * for any `404`, at most this many times, never for a refusal of the first mint. + */ +const MAXIMUM_RESUMES = 2; +/** + * Every API call is one request under the visitor's admission budget, so a large export meets `429` part way. A `429`, + * or a `503` that names its `Retry-After`, is a pause, not a failure: the API refused it before reading the ticket or + * rolled the read back, so the relay waits and repeats the same call (a chunk read with the same index and ticket, a + * renewal as a new mint). A missing or unusable `Retry-After` on a `429` waits the default, `0` still waits a second, + * and no pause exceeds the one-minute window. + */ +const MINIMUM_PAUSE_MS = 1_000; +const DEFAULT_PAUSE_MS = 5_000; +const MAXIMUM_PAUSE_MS = 60_000; +/** A write or end that makes no progress for this long destroys the connection, like any failure after the headers. */ +export const DATA_EXPORT_STALL_MS = 60_000; + +/** The response the relay owns once the first chunk is proven: headers, ordered writes, end or destruction. */ +export type DataExportSink = Readonly<{ + begin: (byteCount: number) => void; + /** Resolves after the bytes are handed to the socket; rejects when the response can take no more. */ + write: (bytes: Buffer) => Promise; + end: () => Promise; + /** Destroys the connection: a short body never completes, so no partial file reads as finished. */ + abort: () => void; +}>; +export type DataExportRelayOutcome = + | Readonly<{ kind: 'completed' }> + /** Refused before any byte: the caller still owns an ordinary document response. */ + | Readonly<{ kind: 'refused'; stage: 'ticket' | 'chunk'; result: NativeOperationResult | null }> + /** Failed after the headers: the connection was destroyed. */ + | Readonly<{ kind: 'aborted' }>; + +/** The wait a refusal asks for, or null when it is a failure rather than a pause. */ +function pauseFor(result: NativeOperationResult): number | null { + if (result.kind !== 'api-error' || (result.status !== 429 && result.status !== 503)) return null; + const seconds = + 'retryAfter' in result.error && + typeof result.error.retryAfter === 'number' && + Number.isSafeInteger(result.error.retryAfter) && + result.error.retryAfter >= 0 + ? result.error.retryAfter + : null; + if (seconds === null) return result.status === 429 ? DEFAULT_PAUSE_MS : null; + return Math.min(MAXIMUM_PAUSE_MS, Math.max(MINIMUM_PAUSE_MS, seconds * 1000)); +} + +/** Resolves after `ms`, or at once when the signal aborts; it never holds the process open. */ +function wait(ms: number, signal: AbortSignal): Promise { + return new Promise((resolve) => { + if (signal.aborted) { + resolve(); + return; + } + // `done` runs only after `timer` is assigned: from the timer itself, or from a later abort. + const done = () => { + clearTimeout(timer); + signal.removeEventListener('abort', done); + resolve(); + }; + const timer = setTimeout(done, ms); + timer.unref(); + signal.addEventListener('abort', done, { once: true }); + }); +} + +/** + * Mints a ticket, reads the chunks in index order and relays them as one body, one chunk in flight. Each chunk is + * proven (index, count, exact size) before a byte of it is written, and its decoded buffer is zeroed after the write + * settles. Nothing outlives the deadline: the ticket's expiry, fifteen minutes, or `ownerDeadline` (the instant the + * response's owner ends, in `now`'s clock), whichever is first. The ticket lives only in this closure: it never + * reaches a header, URL, page or log. + */ +export async function relayDataExport( + input: Readonly<{ + mint: () => Promise; + read: (ticket: string, index: number) => Promise; + sink: DataExportSink; + signal: AbortSignal; + now: () => number; + ownerDeadline?: number; + }>, +): Promise { + const deadlineOf = (granted: DataExportTicket) => + Math.min( + Date.parse(granted.expiresAt), + input.now() + TICKET_LIFETIME_MS, + input.ownerDeadline ?? Number.POSITIVE_INFINITY, + ); + // The first mint pauses for nothing: no ticket is held yet, so its refusal is the person's answer. + const minted = await input.mint(); + if (minted.kind !== 'success') return { kind: 'refused', stage: 'ticket', result: minted }; + const first = minted.data as DataExportTicket; + let ticket = first.ticket; + const count = first.chunkCount; + const byteCount = first.byteCount; + let deadline = deadlineOf(first); + if (count !== Math.ceil(byteCount / CHUNK_BYTES) || Number.isNaN(deadline)) + return { kind: 'refused', stage: 'ticket', result: null }; + // Before the headers the browser waits with nothing to show: the download starts within one pause window, or the + // person gets the refusal document instead. + const startBy = input.now() + MAXIMUM_PAUSE_MS; + let begun = false; + let resumes = 0; + const fail = (result: NativeOperationResult | null): DataExportRelayOutcome => { + if (!begun) return { kind: 'refused', stage: 'chunk', result }; + input.sink.abort(); + return { kind: 'aborted' }; + }; + /** + * One API call, repeated after each pause it asks for. A pause that would reach the deadline (or, before the + * headers, the start bound) is not taken: the refusal is returned at once. Null means the response was cancelled. + */ + const call = async ( + operation: () => Promise, + ): Promise => { + for (;;) { + const result = await operation(); + if (input.signal.aborted) return null; + const pause = pauseFor(result); + const limit = begun ? deadline : Math.min(deadline, startBy); + if (pause === null || input.now() + pause >= limit) return result; + await wait(pause, input.signal); + if (input.signal.aborted) return null; + } + }; + /** + * Settles one sink operation, or reports that it made no progress within the stall bound, before the deadline or, + * when given, before `cancel` aborts. + */ + const progress = async (operation: Promise, cancel?: AbortSignal): Promise => { + // A write still pending when the connection is destroyed rejects later; that rejection is expected. + operation.catch(() => undefined); + const bound = Math.min(DATA_EXPORT_STALL_MS, deadline - input.now()); + if (bound <= 0) return false; + const settled = new AbortController(); + try { + return await Promise.race([ + operation.then(() => true), + wait(bound, cancel ? AbortSignal.any([settled.signal, cancel]) : settled.signal).then( + () => false, + ), + ]); + } finally { + settled.abort(); + } + }; + for (let index = 0; index < count; ) { + if (input.signal.aborted || input.now() >= deadline) return fail(null); + const read = await call(() => input.read(ticket, index)); + if (read === null) return fail(null); + if (read.kind !== 'success') { + if (read.kind !== 'api-error' || read.status !== 404 || resumes >= MAXIMUM_RESUMES) + return fail(read); + resumes += 1; + const renewed = await call(() => input.mint()); + if (renewed === null) return fail(null); + // A refused renewal is the ticket's own answer (the file is gone, or a bound is reached). + if (renewed.kind !== 'success') + return begun ? fail(renewed) : { kind: 'refused', stage: 'ticket', result: renewed }; + const next = renewed.data as DataExportTicket; + const renewedDeadline = deadlineOf(next); + // A resumed download continues the same bundle only: the geometry must be the one already promised. + if ( + next.chunkCount !== count || + next.byteCount !== byteCount || + Number.isNaN(renewedDeadline) + ) + return fail(null); + ticket = next.ticket; + deadline = renewedDeadline; + continue; + } + const chunk = read.data as DataExportChunk; + const expected = index < count - 1 ? CHUNK_BYTES : byteCount - (count - 1) * CHUNK_BYTES; + if (chunk.index !== index || chunk.count !== count) return fail(null); + const bytes = Buffer.from(chunk.bytes, 'base64'); + if (bytes.length !== expected) { + bytes.fill(0); + return fail(null); + } + try { + if (!begun) { + input.sink.begin(byteCount); + begun = true; + } + if (!(await progress(input.sink.write(bytes), input.signal))) return fail(null); + } catch { + begun = true; + return fail(null); + } finally { + // After a destroyed connection too: the socket no longer sends what it still held. + bytes.fill(0); + } + index += 1; + } + try { + // A finished response ends its own lease, so the end is judged by its own settlement and not by the signal: a + // response that closes instead rejects it. + if (!(await progress(input.sink.end()))) return fail(null); + } catch { + return fail(null); + } + return { kind: 'completed' }; +} diff --git a/frontend/apps/web/src/server/auth/data-request-administration.test.ts b/frontend/apps/web/src/server/auth/data-request-administration.test.ts new file mode 100644 index 000000000..9bec99079 --- /dev/null +++ b/frontend/apps/web/src/server/auth/data-request-administration.test.ts @@ -0,0 +1,917 @@ +import type { + MembershipDetail, + SubjectDataRequest, + SubjectDataRequestPage, +} from '@learnstack/sdk/administration-server'; +import { describe, expect, it, vi } from 'vitest'; + +import { renderBffDocument } from './html'; +import { + BFF_ADMIN_FORMS, + BffDataRequestConfirmationError, + DATA_REQUEST_ADMIN_FORMS, + DATA_REQUEST_ADMIN_REFUSALS, + bffAdministrationForm, + dataRequestAdministrationDestination, + dataRequestAdministrationRefusal, +} from './http-forms'; +import { BFF_POST_PATHS, DATA_REQUEST_DOCUMENT_PATHS, bffActionDocumentTarget } from './http-paths'; +import type { BffPage } from './http-protocol'; +import { NativeApiError } from './native-contract'; +import { DATA_REQUEST_REFUSALS } from './native-data-request-http'; +import type { NativeOperation, NativeOperationResult } from './native-operation-contract'; +import type { + DataRequestAdministrationRefusal, + NativePageSnapshot, + PageCapabilities, + PageDataRequest, +} from './page-contract'; +import { nativeDocumentPlan, preloadPage } from './page-preload'; +import { BffSessionError } from './session-contract'; +import { + dataRequestErasureTarget, + isBffRecoveryTarget, + isBffRedirectTarget, + isNativeReturnPath, +} from './session-path'; +import snapshot from '../../../../../../backend/openapi/v1.json'; +import { dataRequestRefusalSentence } from '../../components/auth/admin-data-request-labels'; +import { createAdministrationTranslator } from '../../i18n/administration-catalogues'; +import { + ADMINISTRATOR_ROUTES, + ENVELOPE_REASONS, + identityDataRequestReasons, +} from '../../test/data-request-reasons'; + +const requestId = '019a154b-0000-7000-8000-000000000041'; +const memberId = '019a154b-0000-7000-8000-000000000012'; +const otherMember = '019a154b-0000-7000-8000-000000000013'; +/** A Revoked Membership: the API answers its detail 404, as `MembershipAdministrationAssignmentTests` pins. */ +const revokedMember = '019a154b-0000-7000-8000-000000000019'; +const erasurePage = '/studio/data-requests/erasure?membership=' + memberId; +const userId = '019a154b-0000-7000-8000-0000000000ff'; +const organizationId = '019a154b-0000-7000-8000-000000000014'; +const key = 'k'.repeat(43); +const csrfToken = 'C'.repeat(43); +const pageInfo = { nextCursor: null, previousCursor: null, hasNext: false, hasPrevious: false }; +const capabilities: PageCapabilities = { + canReadTenantMembers: true, + canReadOrganizationMembers: false, + canWriteMemberProfiles: true, + canManageMemberships: true, + canReadRoles: false, + canChangeRoleGrants: false, + canAdoptRoleRelease: false, + canWriteOwnProfile: true, + canManageOrganizations: false, + canManageCustomFields: false, + canManageFederation: false, +}; +const membership = (id: string, value: Partial = {}): MembershipDetail => ({ + membershipId: id, + userId, + organizationId: null, + // The detail read answers only an Active or Suspended Membership. + status: 'Active', + displayName: 'Subject ' + id.slice(-2), + preferredLocale: 'tr', + roleIds: ['019a154b-0000-7000-8000-0000000000aa'], + version: '9', + ...value, +}); +const receipt = (value: Partial = {}): SubjectDataRequest => ({ + id: requestId, + kind: 'erasure', + origin: 'administrator', + status: 'scheduled', + createdAt: '2026-11-23T10:00:00.0000000+00:00', + updatedAt: null, + completedAt: null, + lastRefusal: null, + failureReason: null, + retained: [], + artifact: null, + version: '0', + executeAt: '2026-11-24T10:00:00.0000000+00:00', + requestedByYou: true, + membershipIds: [memberId], + ...value, +}); +const success = (data: unknown): NativeOperationResult => + ({ + kind: 'success', + status: 200, + data, + etag: null, + location: null, + replayed: false, + }) as NativeOperationResult; +const refused = (status: number, errors?: Record) => + ({ + kind: 'api-error', + status, + error: { code: 'unknown' }, + problem: { + status, + type: 'about:blank', + title: 'private-upstream-title', + instance: '/owned', + code: status === 409 ? 'business_rule_violation' : 'not_found', + messageKey: 'lockey_private', + correlationId: 'private-correlation', + ...(errors ? { errors } : {}), + }, + }) as NativeOperationResult; +const page = (items: SubjectDataRequest[], nextCursor: string | null = null) => + success({ + items, + pageInfo: { ...pageInfo, nextCursor, hasNext: nextCursor !== null }, + } satisfies SubjectDataRequestPage); +const base: Omit = { + target: '/studio/data-requests', + site: { + displayName: 'School', + defaultLocale: 'en', + enabledLocales: ['en', 'tr'], + theme: null, + showPlatformAttribution: true, + }, + session: { + state: 'authenticated', + displayName: 'School', + expiresAt: 1800000300000, + limitedByAbsolute: false, + csrfToken, + }, + scopeKind: 'tenant', + formKeys: [key], +}; +function fixture( + results: Partial>, + memberships: Readonly> = {}, +) { + const read = vi.fn(async (operation: NativeOperation): Promise => { + if (operation.kind === 'getMembership') + return ( + memberships[operation.id] ?? + (operation.id === revokedMember ? refused(404) : success(membership(operation.id))) + ); + return ( + { + getOwnCapabilities: success(capabilities), + getOwnProfile: success({ displayName: 'Actor', preferredLocale: 'en', version: '1' }), + getMembershipCustomFields: success({ membershipId: memberId, version: '9', fields: [] }), + ...results, + }[operation.kind] ?? { kind: 'invalid-request' } + ); + }); + const wrap = vi.fn((cursor: string) => 'sealed-' + cursor.length); + return { + read, + wrap, + operations: () => read.mock.calls.map(([operation]) => operation), + load: (target: string, organization: string | null = null) => { + const plan = nativeDocumentPlan(target, false); + return preloadPage(plan, { ...base, target: plan.target }, organization, read, wrap); + }, + }; +} +const ready = (value: NativePageSnapshot, kind: K) => { + if (value.outcome.kind !== 'ready' || value.outcome.view.kind !== kind) + throw new Error('Expected ' + kind); + return value.outcome.view as Extract['view'] & { + kind: K; + }; +}; + +describe('administrator data-request pages: native preparation (ADR-0106 §§ 3, 6, 13)', () => { + it('lists twenty requests, names each subject as the member list does and seals the cursor', async () => { + const exportId = '019a154b-0000-7000-8000-000000000042'; + const readmitted = receipt({ + id: '019a154b-0000-7000-8000-000000000043', + kind: 'export', + executeAt: null, + // A re-admitted person: the Revoked tombstone first, the current Membership second. + membershipIds: [revokedMember, otherMember], + }); + const items = [ + receipt({ membershipIds: [revokedMember] }), + receipt({ id: exportId, kind: 'export', executeAt: null }), + readmitted, + receipt({ + id: '019a154b-0000-7000-8000-000000000044', + origin: 'self', + requestedByYou: false, + membershipIds: [otherMember], + }), + ]; + const test = fixture({ listDataRequests: page(items, 'raw-api-cursor') }); + const view = ready(await test.load('/studio/data-requests'), 'data_requests'); + expect(test.operations()).toEqual([ + { kind: 'getOwnCapabilities' }, + { kind: 'getOwnProfile' }, + { kind: 'listDataRequests', limit: 20 }, + // One read per distinct first Membership, never per request, and none for the administrator's erasure. + { kind: 'getMembership', id: memberId }, + { kind: 'getMembership', id: revokedMember }, + { kind: 'getMembership', id: otherMember }, + ]); + expect(view.endCursor).toBe('sealed-14'); + expect(test.wrap).toHaveBeenCalledExactlyOnceWith('raw-api-cursor'); + const subject = (id: string) => ({ + membershipId: id, + displayName: 'Subject ' + id.slice(-2), + status: 'Active', + organizationScoped: false, + }); + expect(view.items.map((item) => item.subject)).toEqual([ + 'revoked', + subject(memberId), + // Its tombstone's read was refused; the other request's read of its current Membership names it. + subject(otherMember), + subject(otherMember), + ]); + const serialized = JSON.stringify(view); + for (const secret of [userId, 'raw-api-cursor', '0000000000aa', '"tr"', 'roleIds']) + expect(serialized).not.toContain(secret); + expect(Date.parse(view.preparedAt)).toBeGreaterThan(0); + }); + + it.each([ + ['an administrator erasure', { origin: 'administrator' }], + ['an erasure awaiting the operator', { origin: 'self', status: 'awaiting_privileged_step' }], + ['a completed erasure', { origin: 'self', status: 'completed' }], + ['a fan-out erasure that completed', { origin: 'closure_fanout', status: 'completed' }], + ] as const)( + 'never reads the subject of %s, whose Memberships are all Revoked', + async (_, value) => { + const test = fixture({ + listDataRequests: page([receipt({ ...value, membershipIds: [memberId, otherMember] })]), + getDataRequest: success(receipt({ ...value, membershipIds: [memberId, otherMember] })), + }); + for (const target of ['/studio/data-requests', '/studio/data-requests/' + requestId]) { + const result = await test.load(target); + if (result.outcome.kind !== 'ready') throw new Error('Expected a ready page'); + const view = result.outcome.view; + const item = + view.kind === 'data_requests' + ? view.items[0]! + : (view as { request: PageDataRequest }).request; + expect(item.subject).toBe('revoked'); + } + expect(test.operations().map((operation) => operation.kind)).not.toContain('getMembership'); + }, + ); + + it('keeps reading the subject of a scheduled or running self-filed erasure and of every export', async () => { + const items = [ + receipt({ origin: 'self', membershipIds: [memberId] }), + receipt({ + id: '019a154b-0000-7000-8000-000000000045', + origin: 'self', + status: 'fulfilling', + membershipIds: [otherMember], + }), + receipt({ + id: '019a154b-0000-7000-8000-000000000046', + kind: 'export', + status: 'completed', + executeAt: null, + membershipIds: [revokedMember], + }), + ]; + const test = fixture({ listDataRequests: page(items) }); + const view = ready(await test.load('/studio/data-requests'), 'data_requests'); + expect( + test + .operations() + .filter((operation) => operation.kind === 'getMembership') + .map((operation) => (operation as { id: string }).id), + ).toEqual([memberId, otherMember, revokedMember]); + // An export of a revoked person is not known to be Revoked: its refused read leaves it unnamed. + expect( + view.items.map((item) => + typeof item.subject === 'object' ? (item.subject?.membershipId ?? null) : item.subject, + ), + ).toEqual([memberId, otherMember, null]); + }); + + it('keeps a page usable when a subject read is refused, and never fails it for a name', async () => { + const exported = receipt({ kind: 'export', executeAt: null }); + const test = fixture({ listDataRequests: page([exported]) }, { [memberId]: refused(404) }); + const view = ready(await test.load('/studio/data-requests'), 'data_requests'); + expect(view.items[0]!.subject).toBeNull(); + const mismatch = fixture( + { listDataRequests: page([exported]) }, + { [memberId]: success(membership(otherMember)) }, + ); + expect( + ready(await mismatch.load('/studio/data-requests'), 'data_requests').items[0]!.subject, + ).toBeNull(); + }); + + const exportsOf = (ids: readonly string[]) => + page( + ids.map((id, index) => + receipt({ + id: '019a154b-0000-7000-8000-0000000002' + String(index).padStart(2, '0'), + kind: 'export', + executeAt: null, + membershipIds: [id], + }), + ), + ); + const twelve = Array.from( + { length: 12 }, + (_, index) => '019a154b-0000-7000-8000-0000000001' + String(index).padStart(2, '0'), + ); + + it('reads subjects four at a time and lets no read outlive a failed page', async () => { + const ids = twelve; + let open = 0; + let peak = 0; + let settled = 0; + const gate: (() => void)[] = []; + const test = fixture({ listDataRequests: exportsOf(ids) }); + const common = test.read.getMockImplementation()!; + test.read.mockImplementation(async (operation) => { + if (operation.kind !== 'getMembership') return common(operation); + open += 1; + peak = Math.max(peak, open); + await new Promise((resolve) => gate.push(resolve)); + open -= 1; + settled += 1; + if (operation.id === ids[1]) throw new BffSessionError('revoked'); + return success(membership(operation.id)); + }); + const loading = test.load('/studio/data-requests'); + let rejected = false; + void loading.catch(() => { + rejected = true; + }); + for (let round = 0; round < 40 && !rejected; round += 1) { + await new Promise((resolve) => setTimeout(resolve, 0)); + gate.splice(0).forEach((release) => release()); + } + await expect(loading).rejects.toThrow(BffSessionError); + expect(peak).toBe(4); + // The failure stops further reads, and the page settles only after every started read did. + const started = test.operations().filter((operation) => operation.kind === 'getMembership'); + expect(started.length).toBeLessThan(ids.length); + expect(settled).toBe(started.length); + }); + + const stopsAfter = async (failure: (id: string) => NativeOperationResult | never) => { + const ids = twelve; + const test = fixture({ listDataRequests: exportsOf(ids) }); + const common = test.read.getMockImplementation()!; + test.read.mockImplementation(async (operation) => + operation.kind === 'getMembership' && operation.id === ids[1] + ? failure(operation.id) + : common(operation), + ); + const view = ready(await test.load('/studio/data-requests'), 'data_requests'); + const started = test + .operations() + .filter((operation) => operation.kind === 'getMembership') + .map((operation) => (operation as { id: string }).id); + expect(started).toContain(ids[1]); + // No identifier is taken once the failure is known; every unread or failed subject stays unnamed. + expect(started.length).toBeLessThan(ids.length); + for (const item of view.items) + expect(item.subject === null).toBe( + !started.includes(item.membershipIds[0]!) || item.membershipIds[0] === ids[1], + ); + }; + + it.each([429, 500, 503])( + 'stops further subject reads after a %s and still renders the page', + (status) => stopsAfter(() => refused(status)), + ); + + it.each(['response', 'deadline'] as const)( + 'degrades a thrown %s transport failure of a subject read instead of failing the page', + (reason) => + stopsAfter(() => { + throw new NativeApiError(reason); + }), + ); + + it('still fails the page for a cancelled subject read', async () => { + const test = fixture( + { listDataRequests: exportsOf([memberId]) }, + { [memberId]: { kind: 'cancelled' } }, + ); + await expect(test.load('/studio/data-requests')).rejects.toThrow(BffSessionError); + }); + + it('withholds the pages before any data-request read without the membership capability', async () => { + for (const target of [ + '/studio/data-requests', + '/studio/data-requests/' + requestId, + erasurePage, + '/studio/data-requests/erasure', + ]) { + const test = fixture({ + getOwnCapabilities: success({ ...capabilities, canManageMemberships: false }), + }); + const result = await test.load(target); + expect(result.outcome).toMatchObject({ kind: 'failure', reason: 'denied', status: 403 }); + expect(test.operations().map((operation) => operation.kind)).toEqual([ + 'getOwnCapabilities', + 'getOwnProfile', + ]); + } + }); + + it('reads one request with its closed result and keeps at most twenty Membership identifiers', async () => { + const many = Array.from( + { length: 30 }, + (_, index) => '019a154b-0000-7000-8000-0000000003' + String(index).padStart(2, '0'), + ); + const test = fixture({ getDataRequest: success(receipt({ membershipIds: many })) }); + const view = ready( + await test.load('/studio/data-requests/' + requestId + '?result=erasure'), + 'data_request', + ); + // The administrator's erasure concerns a Revoked person: no member read. + expect(test.operations().slice(2)).toEqual([{ kind: 'getDataRequest', id: requestId }]); + expect(view.result).toBe('erasure'); + expect(view.request.subject).toBe('revoked'); + expect(view.request.membershipIds).toEqual(many.slice(0, 20)); + expect(view.request.membershipCount).toBe(30); + const exported = fixture({ + getDataRequest: success(receipt({ kind: 'export', executeAt: null, membershipIds: many })), + }); + await exported.load('/studio/data-requests/' + requestId); + expect(exported.operations().slice(2)).toEqual([ + { kind: 'getDataRequest', id: requestId }, + { kind: 'getMembership', id: many[0] }, + ]); + expect( + ready( + await fixture({ getDataRequest: success(receipt()) }).load( + '/studio/data-requests/' + requestId, + ), + 'data_request', + ).result, + ).toBeNull(); + }); + + it('admits only the closed query of each data-request document', () => { + expect(nativeDocumentPlan('/studio/data-requests?cursor=YWJj', false)).toMatchObject({ + kind: 'data_requests', + cursor: 'YWJj', + limit: 20, + }); + for (const target of [ + '/studio/data-requests?limit=100', + '/studio/data-requests?result=export', + '/studio/data-requests/' + requestId + '?result=closure', + '/studio/data-requests/' + requestId + '?cursor=YWJj', + '/studio/data-requests/' + requestId + '?result=export&result=erasure', + '/studio/data-requests/' + requestId.toUpperCase(), + '/studio/data-requests/' + requestId + '/artifact', + ]) + expect(() => nativeDocumentPlan(target, false), target).toThrow(); + expect(isNativeReturnPath('/studio/data-requests')).toBe(true); + expect(isNativeReturnPath('/studio/data-requests/' + requestId)).toBe(true); + expect(isNativeReturnPath('/studio/data-requests/' + requestId + '?result=export')).toBe(false); + }); + + it('admits the erasure page with only one canonical Membership and reads nothing about it', async () => { + expect(nativeDocumentPlan(erasurePage, false)).toEqual({ + target: '/studio/data-requests/erasure', + kind: 'data_request_erasure', + limit: 20, + selectedFieldId: null, + consentCursor: undefined, + membershipId: memberId, + }); + expect(nativeDocumentPlan('/studio/data-requests/erasure', false)).toMatchObject({ + kind: 'data_request_erasure', + membershipId: null, + }); + for (const target of [ + erasurePage.toUpperCase(), + '/studio/data-requests/erasure?membership=' + memberId.toUpperCase(), + '/studio/data-requests/erasure?membership=019a154b-0000-4000-8000-000000000012', + '/studio/data-requests/erasure?membership=x', + '/studio/data-requests/erasure?membership=', + erasurePage + '&membership=' + otherMember, + erasurePage + '&result=erasure', + erasurePage + '&cursor=YWJj', + '/studio/data-requests/erasure?result=erasure', + '/studio/data-requests/erasure/' + memberId, + '/studio/members/' + memberId + '?membership=' + memberId, + '/studio/data-requests/' + requestId + '?membership=' + memberId, + ]) + expect(() => nativeDocumentPlan(target, false), target).toThrow(); + const test = fixture({}); + const view = ready(await test.load(erasurePage), 'data_request_erasure'); + expect(view).toEqual({ kind: 'data_request_erasure', membershipId: memberId }); + expect(test.operations()).toEqual([{ kind: 'getOwnCapabilities' }, { kind: 'getOwnProfile' }]); + // The erasure page is the one recovery and redirect target that carries a query; queries never return authority. + expect(dataRequestErasureTarget(memberId)).toBe(erasurePage); + expect(() => dataRequestErasureTarget(memberId.toUpperCase())).toThrow(); + expect(isNativeReturnPath('/studio/data-requests/erasure')).toBe(true); + expect(isNativeReturnPath(erasurePage)).toBe(false); + expect(isBffRecoveryTarget(erasurePage)).toBe(true); + expect(isBffRedirectTarget(erasurePage)).toBe(true); + const result = '/studio/data-requests/' + requestId + '?result=erasure'; + expect(isBffRecoveryTarget(result)).toBe(false); + expect(isBffRedirectTarget(result)).toBe(true); + for (const hostile of [ + erasurePage + '&x=1', + erasurePage.replace('membership', 'member'), + '/studio/data-requests/' + requestId + '?result=closure', + '/studio/data-requests/' + requestId + '?result=export&result=erasure', + '//other.example' + erasurePage, + 'https://other.example' + result, + ]) { + expect(isBffRecoveryTarget(hostile), hostile).toBe(false); + expect(isBffRedirectTarget(hostile), hostile).toBe(false); + } + }); + + it("shows a member's own requests only in the member's exact group, and an unavailable list as such", async () => { + const mine = receipt({ membershipIds: [otherMember, memberId] }); + const theirs = receipt({ + id: '019a154b-0000-7000-8000-000000000044', + membershipIds: [otherMember], + }); + const test = fixture({ + getMembership: success(membership(memberId)), + listDataRequests: page([mine, theirs], 'more'), + }); + const view = ready(await test.load('/studio/members/' + memberId), 'member'); + expect(test.operations()).toContainEqual({ kind: 'listDataRequests', limit: 100 }); + expect(view.dataRequests).toMatchObject({ complete: false }); + expect(view.dataRequests!.items!.map((item) => item.id)).toEqual([mine.id]); + expect(view.dataRequests!.items![0]!.subject).toEqual({ + membershipId: memberId, + displayName: 'Subject 12', + status: 'Active', + organizationScoped: false, + }); + // Another group's member: the list would be the wrong group's, so it is not read. + const other = fixture({}); + other.read.mockImplementation(async (operation) => + operation.kind === 'getMembership' + ? success(membership(memberId, { organizationId })) + : operation.kind === 'getOwnCapabilities' + ? success(capabilities) + : operation.kind === 'getMembershipCustomFields' + ? success({ membershipId: memberId, version: '9', fields: [] }) + : success({ displayName: 'Actor', preferredLocale: 'en', version: '1' }), + ); + const outside = ready(await other.load('/studio/members/' + memberId), 'member'); + expect(outside.dataRequests).toBeUndefined(); + expect(other.operations().map((operation) => operation.kind)).not.toContain('listDataRequests'); + const unavailable = fixture({ listDataRequests: refused(503) }); + const degraded = ready(await unavailable.load('/studio/members/' + memberId), 'member'); + expect(degraded.dataRequests).toMatchObject({ items: null, complete: false }); + // A transport failure (deadline, oversized or non-JSON body) also hides only the section. + for (const reason of ['response', 'deadline'] as const) { + const thrown = fixture({}); + const common = thrown.read.getMockImplementation()!; + thrown.read.mockImplementation(async (operation) => { + if (operation.kind === 'listDataRequests') throw new NativeApiError(reason); + return common(operation); + }); + const result = await thrown.load('/studio/members/' + memberId); + expect(result.outcome.kind).toBe('ready'); + expect(ready(result, 'member').dataRequests).toMatchObject({ items: null, complete: false }); + } + // A session failure or cancellation still fails the page. + for (const failure of [new BffSessionError('revoked'), new BffSessionError('cancelled')]) { + const failing = fixture({}); + const common = failing.read.getMockImplementation()!; + failing.read.mockImplementation(async (operation) => { + if (operation.kind === 'listDataRequests') throw failure; + return common(operation); + }); + await expect(failing.load('/studio/members/' + memberId)).rejects.toBe(failure); + } + const cancelled = fixture({ listDataRequests: { kind: 'cancelled' } }); + await expect(cancelled.load('/studio/members/' + memberId)).rejects.toThrow(BffSessionError); + const denied = fixture({ + getOwnCapabilities: success({ ...capabilities, canManageMemberships: false }), + }); + expect( + ready(await denied.load('/studio/members/' + memberId), 'member').dataRequests, + ).toBeUndefined(); + }); +}); + +describe('administrator data-request forms (ADR-0106 §§ 3, 10, 11; ADR-0107 § 4)', () => { + const form = (path: string, fields: Record) => + bffAdministrationForm(path, new URLSearchParams(fields)); + const create = { csrfToken, idempotencyKey: key, membershipId: memberId }; + const write = { csrfToken, idempotencyKey: key, version: '9223372036854775807', requestId }; + + it('owns exactly four closed POST paths, all action documents and none a native data page', () => { + const paths = Object.keys(DATA_REQUEST_ADMIN_FORMS); + expect(paths).toEqual([ + '/api/studio/data-request-export', + '/api/studio/data-request-erasure', + '/api/studio/data-request-cancel', + '/api/studio/data-request-revoke', + ]); + for (const path of paths) { + expect(BFF_POST_PATHS).toContain(path); + expect(BFF_ADMIN_FORMS[path]).toBe(DATA_REQUEST_ADMIN_FORMS[path]); + expect(bffActionDocumentTarget(path)).toBe(true); + } + // The person's data-request routes answer their own native document, never an action document. + expect(DATA_REQUEST_DOCUMENT_PATHS.length).toBeGreaterThan(10); + for (const path of DATA_REQUEST_DOCUMENT_PATHS) { + expect(bffActionDocumentTarget(path), path).toBe(false); + expect(paths).not.toContain(path); + } + }); + + it('maps each form to its one operation and fixed destinations', () => { + expect(form('/api/studio/data-request-export', create)).toEqual({ + operation: { + kind: 'createDataExportForSubject', + membershipId: memberId, + idempotencyKey: key, + }, + destination: '/studio/members/' + memberId, + }); + // A Revoked Membership has no member page: the erasure recovers to the page it was filed from. + expect(form('/api/studio/data-request-erasure', { ...create, confirm: 'erase' })).toEqual({ + operation: { + kind: 'createDataErasureForSubject', + membershipId: memberId, + idempotencyKey: key, + }, + destination: erasurePage, + }); + expect(form('/api/studio/data-request-cancel', write)).toEqual({ + operation: { + kind: 'cancelDataRequest', + id: requestId, + version: '9223372036854775807', + idempotencyKey: key, + }, + destination: '/studio/data-requests/' + requestId, + }); + expect(form('/api/studio/data-request-revoke', write).operation).toMatchObject({ + kind: 'revokeDataExport', + id: requestId, + }); + }); + + it('re-checks the erasure confirmation as its own recoverable refusal', () => { + for (const fields of [create, { ...create, confirm: 'yes' }, { ...create, confirm: '' }]) + expect(() => form('/api/studio/data-request-erasure', fields)).toThrow( + BffDataRequestConfirmationError, + ); + // A malformed target is never recoverable: the Membership grammar comes first. + let thrown: unknown; + try { + form('/api/studio/data-request-erasure', { ...create, membershipId: 'x' }); + } catch (error) { + thrown = error; + } + expect(thrown).toBeInstanceOf(Error); + expect(thrown).not.toBeInstanceOf(BffDataRequestConfirmationError); + }); + + it.each([ + ['/api/studio/data-request-export', { ...create, membershipId: memberId.toUpperCase() }], + [ + '/api/studio/data-request-export', + { ...create, membershipId: '019a154b-0000-4000-8000-000000000012' }, + ], + ['/api/studio/data-request-export', { ...create, confirm: 'erase' }], + ['/api/studio/data-request-export', { ...create, tenantId: organizationId }], + ['/api/studio/data-request-export', { csrfToken, membershipId: memberId }], + ['/api/studio/data-request-export', { ...create, idempotencyKey: 'short' }], + ['/api/studio/data-request-cancel', { ...write, version: '01' }], + ['/api/studio/data-request-cancel', { ...write, version: '9223372036854775808' }], + ['/api/studio/data-request-cancel', { ...write, requestId: 'x' }], + ['/api/studio/data-request-revoke', { ...write, membershipId: memberId }], + ['/api/studio/data-request-revoke', { csrfToken, idempotencyKey: key, requestId }], + ])('refuses %s with a hostile or incomplete form', (path, fields) => { + expect(() => form(path, fields as Record)).toThrow(); + }); + + it('refuses a duplicated field', () => { + const fields = new URLSearchParams(create); + fields.append('membershipId', otherMember); + expect(() => bffAdministrationForm('/api/studio/data-request-export', fields)).toThrow(); + }); + + it('redirects a settled action to its request page with a closed result, and creation only by its exact Location', () => { + const location = '/api/v1/identity/data-requests/' + requestId; + expect( + dataRequestAdministrationDestination( + '/api/studio/data-request-export', + '/studio/members/' + memberId, + location, + ), + ).toBe('/studio/data-requests/' + requestId + '?result=export'); + expect( + dataRequestAdministrationDestination( + '/api/studio/data-request-erasure', + '/studio/members/' + memberId, + location, + ), + ).toBe('/studio/data-requests/' + requestId + '?result=erasure'); + expect( + dataRequestAdministrationDestination( + '/api/studio/data-request-cancel', + '/studio/data-requests/' + requestId, + null, + ), + ).toBe('/studio/data-requests/' + requestId + '?result=cancelled'); + expect( + dataRequestAdministrationDestination( + '/api/studio/data-request-revoke', + '/studio/data-requests/' + requestId, + null, + ), + ).toBe('/studio/data-requests/' + requestId + '?result=revoked'); + for (const bad of [ + null, + '/api/v1/identity/me/data-requests/' + requestId, + location + '/cancellations', + 'https://other.example' + location, + location.toUpperCase(), + ]) + expect( + dataRequestAdministrationDestination( + '/api/studio/data-request-export', + '/studio/members/' + memberId, + bad, + ), + ).toBeNull(); + expect( + dataRequestAdministrationDestination('toString', '/studio/members/' + memberId, location), + ).toBeNull(); + expect( + dataRequestAdministrationDestination( + '/api/studio/invitation-create', + '/studio/invitations', + location, + ), + ).toBeNull(); + }); +}); + +/** Reasons only the person's download routes answer; no administrator route can, and the test proves it. */ +const PERSON_ONLY = new Set(['lockey_data_export_ticket_limit']); +const REFUSALS: readonly DataRequestAdministrationRefusal[] = [ + 'request_already_active', + 'blocked_hold', + 'blocked_last_administrator', + 'subject_export_available', + 'subject_membership_current', + 'subject_is_requester', + 'subject_not_admitted', + 'snapshot_too_large', + 'data_export_unavailable', + 'data_request_window_ended', + 'data_request_not_cancellable', + 'unknown', +]; + +describe('administrator data-request refusals (ADR-0106 § 7)', () => { + it('maps every reason to the refusal of its own name', () => { + for (const [reason, refusal] of Object.entries(DATA_REQUEST_ADMIN_REFUSALS)) + expect(refusal, reason).toBe(reason.slice('lockey_'.length)); + }); + + it('names every reason the administrator routes or the Identity code can answer', () => { + const reasons = identityDataRequestReasons(ADMINISTRATOR_ROUTES); + expect(reasons.size).toBeGreaterThan(15); + const unmapped = [...reasons].filter( + (reason) => + !Object.hasOwn(DATA_REQUEST_ADMIN_REFUSALS, reason) && + !ENVELOPE_REASONS.has(reason) && + !PERSON_ONLY.has(reason), + ); + expect(unmapped).toEqual([]); + // A person-only reason never appears in an administrator route's contract. + const documented = JSON.stringify( + Object.entries(snapshot.paths).filter(([path]) => + path.startsWith('/api/v1/identity/data-requests'), + ), + ); + for (const reason of PERSON_ONLY) { + expect(documented).not.toContain(reason); + expect(documented).not.toContain(reason.slice('lockey_'.length)); + } + // The administrator's map is the person's map without the download-only reason. + expect(Object.keys(DATA_REQUEST_ADMIN_REFUSALS).sort()).toEqual( + Object.keys(DATA_REQUEST_REFUSALS) + .filter((reason) => !PERSON_ONLY.has(reason)) + .sort(), + ); + }); + + it('picks the first known reason of errors.$ or errors.artifact, else the generic refusal', () => { + expect( + dataRequestAdministrationRefusal({ $: [{ key: 'lockey_subject_membership_current' }] }), + ).toBe('subject_membership_current'); + expect( + dataRequestAdministrationRefusal({ artifact: [{ key: 'lockey_data_export_unavailable' }] }), + ).toBe('data_export_unavailable'); + expect( + dataRequestAdministrationRefusal({ + $: [{ key: 'lockey_future_reason' }, { key: 'lockey_request_already_active' }], + }), + ).toBe('request_already_active'); + expect( + dataRequestAdministrationRefusal({ + membershipId: [{ key: 'lockey_request_already_active' }], + }), + ).toBe('unknown'); + expect(dataRequestAdministrationRefusal({ $: [{ key: 'toString' }] })).toBe('unknown'); + expect(dataRequestAdministrationRefusal(undefined)).toBe('unknown'); + }); + + it.each(['en', 'tr'] as const)('gives every refusal its own %s sentence', (locale) => { + const { admin, dataRequest } = createAdministrationTranslator(locale); + const sentences = REFUSALS.map((refusal) => + dataRequestRefusalSentence(refusal, admin, dataRequest), + ); + expect(new Set(sentences).size).toBe(REFUSALS.length); + const fallback = createAdministrationTranslator(locale).admin('failure.unavailable'); + for (const sentence of sentences) { + expect(sentence).not.toBe(fallback); + expect(sentence).not.toMatch(/lockey_|\{|\}/); + } + }); +}); + +describe('administrator data-request recovery document', () => { + const site = base.site; + const render = (value: Partial>, locale = 'en') => + new DOMParser().parseFromString( + renderBffDocument(site, { + kind: 'mutation_error', + action: '/api/studio/data-request-erasure', + destination: erasurePage, + fields: [ + ['csrfToken', csrfToken], + ['idempotencyKey', key], + ['membershipId', memberId], + ['confirm', 'erase'], + ], + reason: 'denied', + retryable: false, + dataRequest: { refusal: null }, + locale, + ...value, + } as BffPage), + 'text/html', + ); + + it.each(REFUSALS)('explains %s in one alert, with no retry and no API text', (refusal) => { + for (const locale of ['en', 'tr']) { + const document = render({ dataRequest: { refusal }, retryable: true }, locale); + const { admin, dataRequest } = createAdministrationTranslator(locale); + expect(document.querySelector('[role="alert"]')?.textContent).toBe( + dataRequestRefusalSentence(refusal, admin, dataRequest), + ); + expect(document.querySelector('form')).toBeNull(); + expect(document.querySelector('a[href="' + erasurePage + '"]')).not.toBeNull(); + expect(document.body.textContent).not.toMatch(/private-|lockey_/); + expect(document.documentElement.getAttribute('data-bff-history-recovery')).toBe(erasurePage); + expect(document.querySelector('a[href="/account/data"]') !== null).toBe( + refusal === 'subject_is_requester', + ); + } + }); + + it('keeps the template sentence and a deliberate same-request retry for an unconfirmed outcome', () => { + const document = render({ reason: 'unavailable', retryable: true }); + expect(document.querySelector('[role="alert"]')?.textContent).toBe( + 'The result could not be confirmed. Check the item before deciding whether to retry this same request.', + ); + const form = document.querySelector('form')!; + expect(form.getAttribute('action')).toBe('/api/studio/data-request-erasure'); + expect([...form.querySelectorAll('input')].map((input) => [input.name, input.value])).toEqual([ + ['csrfToken', csrfToken], + ['idempotencyKey', key], + ['membershipId', memberId], + ['confirm', 'erase'], + ]); + }); + + it('asks for the confirmation again, in Turkish too, without a resubmission form', () => { + for (const [locale, text] of [ + ['en', 'Tick every confirmation box to go ahead.'], + ['tr', 'Devam etmek için tüm onay kutularını işaretleyin.'], + ] as const) { + const document = render({ reason: 'validation' }, locale); + expect(document.querySelector('[role="alert"]')?.textContent).toBe(text); + expect(document.querySelector('form')).toBeNull(); + expect(document.documentElement.lang).toBe(locale); + } + }); +}); diff --git a/frontend/apps/web/src/server/auth/data-request-copy.ts b/frontend/apps/web/src/server/auth/data-request-copy.ts new file mode 100644 index 000000000..03df90d18 --- /dev/null +++ b/frontend/apps/web/src/server/auth/data-request-copy.ts @@ -0,0 +1,243 @@ +/** The closed native data-request copy (ADR-0106 § 9, ADR-0107 §§ 4, 6 and 7); every key exists in en and tr. */ +export const dataRequestKeys = [ + 'common.title', + 'common.skip', + 'common.intro', + 'common.signin', + 'common.signin_action', + 'common.back_portal', + 'common.back_entry', + 'common.back_page', + 'common.next_page', + 'common.next_scopes', + 'common.required', + 'common.script_note', + 'scope.session_tenant', + 'scope.session_organization', + 'scope.session_retained', + 'scope.switch', + 'scope.entry_intro', + 'scope.entry_choose', + 'scope.entry_tenant', + 'scope.entry_organization', + 'scope.entry_names', + 'scope.entry_empty', + 'scope.view', + 'scope.entry_selected_tenant', + 'scope.entry_selected_organization', + 'scope.change', + 'scope.entry_time_limit', + 'scope.entry_time_until', + 'scope.entry_time_left', + 'scope.entry_time_under_minute', + 'result.title', + 'result.export', + 'result.erasure', + 'result.closure', + 'result.cancelled', + 'result.revoked', + 'export.title', + 'export.description', + 'export.audit_note', + 'export.timing', + 'export.action', + 'export.active', + 'erasure.title', + 'erasure.summary', + 'erasure.start', + 'erasure.active', + 'erasure.step_title', + 'erasure.erased_title', + 'erasure.erased_profile', + 'erasure.erased_roles', + 'erasure.erased_exports', + 'erasure.erased_invitations', + 'erasure.kept_title', + 'erasure.kept_intro', + 'erasure.kept_consent', + 'erasure.kept_invitations', + 'erasure.kept_audit', + 'erasure.kept_attribution', + 'erasure.kept_receipt', + 'erasure.kept_uncounted', + 'erasure.kept_partial', + 'erasure.timing', + 'erasure.legend', + 'erasure.confirm', + 'erasure.action', + 'erasure.back', + 'closure.title', + 'closure.summary', + 'closure.start', + 'closure.active', + 'closure.step_title', + 'closure.warning_title', + 'closure.warning_everywhere', + 'closure.warning_email', + 'closure.warning_cancel', + 'closure.warning_stops', + 'closure.warning_no_status', + 'closure.warning_data', + 'closure.warning_unserved', + 'closure.legend', + 'closure.confirm_irreversible', + 'closure.confirm_no_status', + 'closure.action', + 'closure.back', + 'list.title', + 'list.empty', + 'list.status', + 'list.requested', + 'list.runs_after', + 'list.earliest', + 'list.ended', + 'list.completed', + 'list.available_until', + 'list.expired_on', + 'list.size', + 'list.by_administrator', + 'list.by_closure', + 'kind.export', + 'kind.erasure', + 'kind.closure', + 'status.requested', + 'status.scheduled', + 'status.due', + 'status.fulfilling', + 'status.awaiting_privileged_step', + 'status.completed', + 'status.blocked', + 'status.failed', + 'status.cancelled', + 'next.export_requested', + 'next.export_ready', + 'next.export_gone', + 'next.erasure_scheduled', + 'next.erasure_due', + 'next.erasure_fulfilling', + 'next.erasure_awaiting', + 'next.erasure_completed', + 'next.closure_scheduled', + 'next.closure_fulfilling', + 'next.closure_completed', + 'next.blocked', + 'next.failed', + 'next.cancelled', + 'blocked_reason.blocked_hold', + 'blocked_reason.blocked_last_administrator', + 'last_refusal.blocked_window', + 'last_refusal.blocked_hold', + 'last_refusal.blocked_last_administrator', + 'failure.export_too_large', + 'failure.execution_failed', + 'artifact.download', + 'artifact.download_hint', + 'artifact.delete', + 'artifact.delete_hint', + 'artifact.truncated', + 'artifact.truncated_included', + 'artifact.truncated_total', + 'artifact.part_included', + 'artifact.part_total', + 'artifact.collection_audit_entries', + 'artifact.collection_invitations_issued', + 'artifact.collection_other', + 'entry.download_deadline', + 'entry.step_deadline', + 'retained.title', + 'retained.intro', + 'retained.pending', + 'retained.partial', + 'retained.audit_retention', + 'retained.kind.consent_evidence', + 'retained.kind.invitation_record', + 'retained.kind.invitation_envelope', + 'retained.kind.audit_actor_reference', + 'retained.kind.audit_entity_reference', + 'retained.kind.audit_metadata_reference', + 'retained.kind.unscoped_audit_rows', + 'retained.kind.transport_evidence', + 'retained.kind.execution_evidence', + 'retained.kind.provider_event_record', + 'retained.kind.idempotency_cache', + 'retained.kind.attribution_reference', + 'retained.kind.federation_actor_reference', + 'retained.kind.request_receipt', + 'retained.kind.external_copy', + 'retained.kind.unserved_group', + 'action.cancel', + 'action.cancel_closure', + 'refusal.request_already_active', + 'refusal.blocked_hold', + 'refusal.blocked_last_administrator', + 'refusal.subject_export_available', + 'refusal.subject_membership_current', + 'refusal.data_export_unavailable', + 'refusal.data_request_window_ended', + 'refusal.data_request_not_cancellable', + 'refusal.subject_is_requester', + 'refusal.snapshot_too_large', + 'refusal.data_export_ticket_limit', + 'refusal.subject_not_admitted', + 'error.title', + 'error.title_unconfirmed', + 'error.input', + 'error.confirmation', + 'error.csrf', + 'error.unauthorized', + 'error.forbidden', + 'error.not_found', + 'error.stale', + 'error.in_progress', + 'error.key_reuse', + 'error.outcome_unavailable', + 'error.conflict', + 'error.busy', + 'error.unavailable', + 'error.unconfirmed', + 'error.download', +] as const; +export type DataRequestKey = (typeof dataRequestKeys)[number]; +export type DataRequestCopy = (key: DataRequestKey) => string; +export type DataRequestCatalogues = Readonly<{ en: unknown; tr: unknown }>; + +/** + * Native startup supplies the same authored JSON the catalogue tests validate. A missing, extra, empty, oversized or + * parameterized message refuses startup: this document interpolates nothing, so numbers and dates stand apart. + */ +export function prepareDataRequestCatalogues(catalogues: DataRequestCatalogues) { + const prepared = new Map<'en' | 'tr', ReadonlyMap>(); + for (const locale of ['en', 'tr'] as const) { + const values = new Map(); + const visit = (value: unknown, prefix = '') => { + if (!value || typeof value !== 'object' || Array.isArray(value)) + throw new Error('Data request catalogue unavailable'); + for (const [key, child] of Object.entries(value)) { + const path = prefix ? prefix + '.' + key : key; + if (typeof child === 'string') { + if ( + !dataRequestKeys.includes(path as DataRequestKey) || + !child.trim() || + child.length > 1000 || + /[{}<>]/.test(child) || + child.includes(String.fromCharCode(0)) + ) + throw new Error('Data request catalogue unavailable'); + values.set(path as DataRequestKey, child); + } else visit(child, path); + } + }; + visit(catalogues[locale]); + if (values.size !== dataRequestKeys.length) + throw new Error('Data request catalogue unavailable'); + prepared.set(locale, values); + } + /** Turkish for an Accept-Language whose first range is Turkish, as the consent entry decides; else English. */ + return (acceptLanguage: string | null) => { + const locale = /^tr(?:[-,; ]|$)/i.test(acceptLanguage ?? '') ? 'tr' : 'en'; + const messages = prepared.get(locale)!; + const phrase: DataRequestCopy = (key) => + messages.get(key) ?? messages.get('error.unavailable')!; + return Object.freeze({ locale, phrase }); + }; +} diff --git a/frontend/apps/web/src/server/auth/data-request-html.test.ts b/frontend/apps/web/src/server/auth/data-request-html.test.ts new file mode 100644 index 000000000..d1aaa3c6b --- /dev/null +++ b/frontend/apps/web/src/server/auth/data-request-html.test.ts @@ -0,0 +1,828 @@ +import { readFileSync } from 'node:fs'; +import { runInNewContext } from 'node:vm'; + +import { + DATA_EXPORT_ARTIFACT_STATUSES, + DATA_REQUEST_FAILURE_REASONS, + DATA_REQUEST_KINDS, + DATA_REQUEST_LAST_REFUSALS, + DATA_REQUEST_ORIGINS, + DATA_REQUEST_RETAINED_KINDS, + DATA_REQUEST_STATUSES, +} from '@learnstack/sdk/administration-server'; +import type { OwnDataRequest } from '@learnstack/sdk/administration-server'; +import { describe, expect, it, vi } from 'vitest'; + +import { dataRequestKeys, prepareDataRequestCatalogues } from './data-request-copy'; +import { + DATA_REQUEST_HISTORY_SOURCE, + DATA_REQUEST_VOCABULARY, + dataRequestCancellable, + dataRequestHistorySource, + dataRequestState, + renderDataRequestDocument, +} from './data-request-html'; +import type { DataRequestDocument, DataRequestPage } from './data-request-html'; +import { DATA_REQUEST_REFUSALS } from './native-data-request-http'; +import snapshot from '../../../../../../backend/openapi/v1.json'; +import en from '../../i18n/messages/en/data.json'; +import tr from '../../i18n/messages/tr/data.json'; +import { + ENVELOPE_REASONS, + PERSON_ROUTES, + identityDataRequestReasons, +} from '../../test/data-request-reasons'; +import { checkCatalogues, publicCallsiteKeys } from '../../test/ui-catalogue-checks'; + +const nonce = 'N'.repeat(22) + '=='; +const proof = 'c'.repeat(43); +const keys = Array.from({ length: 8 }, (_, index) => String(index).repeat(43)); +const select = prepareDataRequestCatalogues({ en, tr }); +const base = (value: Partial = {}): OwnDataRequest => ({ + id: '019a154b-0000-7000-8000-000000000041', + kind: 'export', + origin: 'self', + status: 'requested', + createdAt: '2026-11-23T10:00:00Z', + updatedAt: null, + completedAt: null, + lastRefusal: null, + failureReason: null, + retained: [], + artifact: null, + version: '3', + executeAt: null, + ...value, +}); +const page = (value: Partial = {}): DataRequestPage => ({ + kind: 'data_requests', + mode: 'session', + scope: 'organization', + group: null, + scopes: null, + requests: { + items: [], + pageInfo: { nextCursor: null, previousCursor: null, hasNext: false, hasPrevious: false }, + }, + step: null, + result: null, + preparedAt: '2026-11-23T12:00:00.000Z', + entryExpiresAt: null, + csrfToken: proof, + formKeys: keys, + ...value, +}); +const render = (value: Partial = {}, locale: 'en' | 'tr' = 'en') => + new DOMParser().parseFromString( + renderDataRequestDocument( + { kind: 'page', page: page(value) }, + { locale, phrase: select(locale === 'tr' ? 'tr' : 'en').phrase, nonce }, + ), + 'text/html', + ); + +describe('the closed data-request copy', () => { + it('has equal, plain en/tr catalogues used through literal keys only', () => { + const source = readFileSync('src/server/auth/data-request-html.ts', 'utf8'); + const used = publicCallsiteKeys(source, 'data-request-html.ts', 'text'); + expect(used.length).toBeGreaterThan(80); + checkCatalogues([en, tr], [...used, ...dataRequestKeys]); + expect(new Set(dataRequestKeys).size).toBe(dataRequestKeys.length); + expect(select('tr-TR,tr;q=0.9').phrase('common.title')).toBe(tr.common.title); + expect(select('de').phrase('common.title')).toBe(en.common.title); + expect(select(null).locale).toBe('en'); + expect(() => publicCallsiteKeys('text(problem.messageKey)', 'dirty.ts', 'text')).toThrow( + 'literal', + ); + }); + + it('refuses a catalogue that is incomplete, extended, parameterized or marked up', () => { + const missing = structuredClone(tr) as Record>; + delete missing.refusal!.subject_not_admitted; + const extra = structuredClone(en) as Record>; + extra.refusal!.unknown = 'Unknown'; + const parameter = structuredClone(en); + parameter.export.action = 'Ask for {count} copies'; + const markup = structuredClone(tr); + markup.export.action = 'Kopya'; + for (const catalogues of [ + { en, tr: missing }, + { en: extra, tr }, + { en: parameter, tr }, + { en, tr: markup }, + ]) + expect(() => prepareDataRequestCatalogues(catalogues)).toThrow( + 'Data request catalogue unavailable', + ); + }); + + it('names every closed wire value the SDK admits', () => { + expect(Object.keys(DATA_REQUEST_VOCABULARY.KINDS).sort()).toEqual( + [...DATA_REQUEST_KINDS].sort(), + ); + expect(Object.keys(DATA_REQUEST_VOCABULARY.STATUSES).sort()).toEqual( + [...DATA_REQUEST_STATUSES, 'due'].sort(), + ); + expect(Object.keys(DATA_REQUEST_VOCABULARY.LAST_REFUSALS).sort()).toEqual( + [...DATA_REQUEST_LAST_REFUSALS].sort(), + ); + expect(Object.keys(DATA_REQUEST_VOCABULARY.FAILURES).sort()).toEqual( + [...DATA_REQUEST_FAILURE_REASONS].sort(), + ); + expect(Object.keys(DATA_REQUEST_VOCABULARY.RETAINED).sort()).toEqual( + [...DATA_REQUEST_RETAINED_KINDS].sort(), + ); + const schemas = snapshot.components.schemas as unknown as Record< + string, + { properties: Record } + >; + const own = schemas.OwnDataRequestResponse!.properties; + expect([...DATA_REQUEST_STATUSES].sort()).toEqual([...own.status!.enum!].sort()); + expect([...DATA_REQUEST_KINDS].sort()).toEqual([...own.kind!.enum!].sort()); + expect([...DATA_REQUEST_LAST_REFUSALS, null]).toEqual(own.lastRefusal!.enum); + expect([...DATA_REQUEST_FAILURE_REASONS, null]).toEqual(own.failureReason!.enum); + expect([...DATA_REQUEST_RETAINED_KINDS].sort()).toEqual( + [...schemas.DataRequestRetainedResponse!.properties.kind!.enum!].sort(), + ); + // The two lists a receipt is gated by that the renderer does not print by name: one drift refuses the whole page. + expect([...DATA_REQUEST_ORIGINS].sort()).toEqual([...own.origin!.enum!].sort()); + expect([...DATA_EXPORT_ARTIFACT_STATUSES].sort()).toEqual( + [...schemas.DataExportArtifactResponse!.properties.status!.enum!].sort(), + ); + }); + + it('has one sentence for every refusal reason the API documents or emits', () => { + const reasons = identityDataRequestReasons(PERSON_ROUTES); + expect(reasons.size).toBeGreaterThan(12); + const unmapped = [...reasons].filter( + (reason) => !Object.hasOwn(DATA_REQUEST_REFUSALS, reason) && !ENVELOPE_REASONS.has(reason), + ); + expect(unmapped).toEqual([]); + for (const key of Object.values(DATA_REQUEST_REFUSALS)) expect(dataRequestKeys).toContain(key); + // The brief's closed list is all present, so a key removed from the map fails here too. + expect(Object.keys(DATA_REQUEST_REFUSALS).sort()).toEqual( + [ + 'lockey_request_already_active', + 'lockey_blocked_hold', + 'lockey_blocked_last_administrator', + 'lockey_subject_export_available', + 'lockey_subject_membership_current', + 'lockey_data_export_unavailable', + 'lockey_data_request_window_ended', + 'lockey_data_request_not_cancellable', + 'lockey_subject_is_requester', + 'lockey_snapshot_too_large', + 'lockey_data_export_ticket_limit', + 'lockey_subject_not_admitted', + ].sort(), + ); + }); +}); + +describe('accessible native data-request documents', () => { + it('has one h1, landmarks, a skip link, list semantics and no table', () => { + const document = render({ + requests: { + items: [ + base(), + base({ + id: '019a154b-0000-7000-8000-000000000042', + kind: 'closure', + status: 'scheduled', + executeAt: '2026-11-24T10:00:00Z', + }), + ], + pageInfo: { nextCursor: null, previousCursor: null, hasNext: false, hasPrevious: false }, + }, + }); + expect(document.querySelectorAll('h1')).toHaveLength(1); + expect(document.querySelector('main#main')?.getAttribute('tabindex')).toBe('-1'); + expect(document.querySelector('a.skip')?.getAttribute('href')).toBe('#main'); + expect(document.documentElement.getAttribute('lang')).toBe('en'); + expect(document.querySelectorAll('ul.requests > li > article')).toHaveLength(2); + for (const article of document.querySelectorAll('article')) + expect(document.getElementById(article.getAttribute('aria-labelledby')!)?.tagName).toBe('H3'); + for (const section of document.querySelectorAll('section')) + expect(document.getElementById(section.getAttribute('aria-labelledby')!)?.tagName).toBe('H2'); + expect(document.querySelector('table')).toBeNull(); + for (const icon of document.querySelectorAll('svg')) { + expect(icon.getAttribute('aria-hidden')).toBe('true'); + expect(icon.getAttribute('focusable')).toBe('false'); + expect(icon.parentElement?.textContent).toContain(en.list.status + ':'); + } + expect(document.querySelector('time')?.getAttribute('datetime')).toBe('2026-11-23T10:00:00Z'); + for (const button of document.querySelectorAll('button')) + expect(button.textContent?.trim()).not.toBe(''); + const css = document.querySelector('style')!.textContent!; + expect(css).toContain('min-height:44px'); + expect(css).toContain(':focus-visible'); + expect(css).toContain('prefers-reduced-motion'); + }); + + it('groups each confirmation in a fieldset with a legend and labelled required boxes', () => { + for (const [step, boxes] of [ + ['erasure', 1], + ['closure', 2], + ] as const) { + const document = render({ step }); + const fieldset = document.querySelector('form fieldset')!; + expect(fieldset.querySelector('legend')?.textContent).toBe(en[step].legend); + const inputs = fieldset.querySelectorAll('input[type="checkbox"]'); + expect(inputs).toHaveLength(boxes); + for (const input of inputs) { + expect(input.hasAttribute('required')).toBe(true); + expect(input.closest('label')?.textContent?.length).toBeGreaterThan(20); + } + expect(document.querySelector('main')?.getAttribute('data-data-request-view')).toBe( + 'session_' + step, + ); + } + }); + + it('announces a result without script and keeps errors in an alert', () => { + const done = render({ result: 'revoked' }); + expect(done.querySelector('[role="status"]')?.textContent).toContain(en.result.revoked); + expect(done.title.startsWith(en.result.title)).toBe(true); + const failure = new DOMParser().parseFromString( + renderDataRequestDocument( + { kind: 'error', message: 'refusal.blocked_hold', back: { kind: 'page', mode: 'entry' } }, + { locale: 'tr', phrase: select('tr').phrase, nonce }, + ), + 'text/html', + ); + expect(failure.querySelector('[role="alert"]')?.textContent).toContain(tr.refusal.blocked_hold); + expect([...failure.querySelectorAll('a.action')].map((a) => a.getAttribute('href'))).toEqual([ + '/account/data', + '/api/auth/entry', + ]); + }); + + it('derives due and cancellable from the closed status and executeAt only', () => { + const at = '2026-11-23T12:00:00.000Z'; + const scheduled = base({ + kind: 'erasure', + status: 'scheduled', + executeAt: '2026-11-23T12:00:01Z', + }); + const due = base({ kind: 'erasure', status: 'scheduled', executeAt: '2026-11-23T12:00:00Z' }); + expect(dataRequestState(scheduled, at)).toBe('scheduled'); + expect(dataRequestState(due, at)).toBe('due'); + expect(dataRequestCancellable(scheduled, at)).toBe(true); + expect(dataRequestCancellable(due, at)).toBe(false); + const closure = base({ + kind: 'closure', + status: 'scheduled', + executeAt: '2026-11-20T12:00:00Z', + }); + expect(dataRequestCancellable(closure, at)).toBe(true); + expect(dataRequestCancellable({ ...closure, status: 'fulfilling' }, at)).toBe(false); + expect(dataRequestCancellable(base(), at)).toBe(true); + expect(dataRequestCancellable(base({ status: 'fulfilling' }), at)).toBe(false); + expect( + dataRequestCancellable( + base({ kind: 'erasure', origin: 'closure_fanout', status: 'scheduled' }), + at, + ), + ).toBe(false); + }); + + it('escapes every printed value and refuses a malformed proof, key, group or nonce', () => { + expect(() => + renderDataRequestDocument( + { kind: 'page', page: page({ csrfToken: '' }) }, + { locale: 'en', phrase: select('en').phrase, nonce }, + ), + ).toThrow('Data request response unavailable'); + expect(() => + renderDataRequestDocument( + { kind: 'page', page: page({ mode: 'entry', scope: null, group: ''; + const html = renderDataRequestDocument( + { + kind: 'page', + page: page( + listed([ + base({ id: hostile, version: hostile }), + base({ + id: hostile, + status: 'completed', + completedAt: '2026-11-22T10:00:00Z', + artifact: { + id: hostile, + status: 'available', + expiresAt: '2026-11-30T10:00:00Z', + purgedAt: null, + byteCount: 10, + chunkCount: 1, + truncations: [], + version: hostile, + readable: true, + }, + }), + ]), + ), + }, + { locale: 'en', phrase: select('en').phrase, nonce }, + ); + expect(html).not.toContain('' + + escape(title) + + '

' + + text('common.title') + + '

' + + body + + '
' + ); +} diff --git a/frontend/apps/web/src/server/auth/entry-cursor.ts b/frontend/apps/web/src/server/auth/entry-cursor.ts index 46f3490d9..f62bda3ab 100644 --- a/frontend/apps/web/src/server/auth/entry-cursor.ts +++ b/frontend/apps/web/src/server/auth/entry-cursor.ts @@ -13,7 +13,10 @@ type EntryCursorBinding = Readonly<{ | 'invitations' | 'custom_fields' | 'custom_revisions' - | 'consent_history'; + | 'consent_history' + | 'data_requests' + | 'data_request_scopes' + | 'group_data_requests'; }>; const VERSION = 1; const MAX_PLAINTEXT_BYTES = 739; diff --git a/frontend/apps/web/src/server/auth/html.test.ts b/frontend/apps/web/src/server/auth/html.test.ts index 5a1ac21d6..a0df7e136 100644 --- a/frontend/apps/web/src/server/auth/html.test.ts +++ b/frontend/apps/web/src/server/auth/html.test.ts @@ -208,6 +208,26 @@ it('entry recovery does not manufacture a selection when a label or membership i expect(empty.body.textContent).toContain('No institution access'); expect(empty.querySelector('form[action="/api/auth/entry/select"]')).toBeNull(); expect(empty.querySelector('a[href="/api/auth/entry"]')).not.toBeNull(); + // The data-request page serves an account; a person with none is not sent to a page that cannot admit them. + expect(empty.querySelector('a[href="/account/data"]')).not.toBeNull(); + const unread = new DOMParser().parseFromString( + renderBffDocument(site(), { + kind: 'entry', + entry: { ...entry, displayLabel: 'My account', contexts: null }, + }), + 'text/html', + ); + expect(unread.querySelector('a[href="/account/data"]')).not.toBeNull(); + const missing = new DOMParser().parseFromString( + renderBffDocument(site(), { + kind: 'entry', + entry: { ...entry, displayLabel: 'My account', identityState: 'missing', contexts: null }, + }), + 'text/html', + ); + expect(missing.querySelector('form[action="/api/auth/entry/create"]')).not.toBeNull(); + expect(missing.querySelector('a[href="/account/data"]')).toBeNull(); + expect(missing.querySelector('a[href="/account/consents"]')).not.toBeNull(); }); it('uncertain mutation recovery keeps the original key and edits escaped in a deliberate native form', () => { const fields = [ diff --git a/frontend/apps/web/src/server/auth/html.ts b/frontend/apps/web/src/server/auth/html.ts index 6fa2c5a47..0ed46f5b5 100644 --- a/frontend/apps/web/src/server/auth/html.ts +++ b/frontend/apps/web/src/server/auth/html.ts @@ -1,5 +1,6 @@ import 'server-only'; +import { dataRequestRefusalSentence } from '@/components/auth/admin-data-request-labels'; import { languageLabel, permissionLabel, @@ -17,7 +18,7 @@ import { createPublicTranslator } from '@/i18n/catalogues'; import type { BffPage } from './http-protocol'; import type { PageSite } from './page-contract'; -import { isNativeReturnPath } from './session-path'; +import { isBffRecoveryTarget, isNativeReturnPath } from './session-path'; function scopeContent(page: Extract, copy: AuthCopy): string { const selection = page.selection; @@ -63,10 +64,12 @@ function entryContent(page: Extract, copy: AuthCopy) return `

${escape(copy('entry.reauthenticate'))}

${signout}`; const label = `

${escape(copy('entry.account'))}: ${escape(entry.displayLabel)}

${escape(copy('entry.confirm'))}

`; const retry = `

${escape(copy('entry.retry'))}

${escape(copy('consents.title'))}

`; + // A person with no account holds no data here, and the data-request routes refuse an unknown binding as signed out. + const dataRequests = `

${escape(copy('entry.data_requests'))}

`; if (entry.identityState === 'missing') return `${label}

${escape(copy('entry.missing'))}

${proof}${retry}${signout}`; if (!entry.contexts) - return `${label}

${escape(copy('entry.unavailable'))}

${retry}${signout}`; + return `${label}

${escape(copy('entry.unavailable'))}

${retry}${dataRequests}${signout}`; const choices = entry.contexts.items .map( (item) => @@ -77,7 +80,7 @@ function entryContent(page: Extract, copy: AuthCopy) entry.contexts.hasNextPage && entry.contexts.endCursor !== null ? `

${escape(copy('entry.next'))}

` : ''; - return `${label}${choices ? `
    ${choices}
` : `

${escape(copy('entry.empty'))}

`}${next}${retry}${signout}`; + return `${label}${choices ? `
    ${choices}
` : `

${escape(copy('entry.empty'))}

`}${next}${retry}${dataRequests}${signout}`; } function entryFailureContent( page: Extract, @@ -268,6 +271,40 @@ function federationMutationContent( return `

${escape(message)}

${escape(copy('mutation.federation_back'))}

`; } +/** + * ADR-0106 § 7: a refused or unconfirmed data-request action. A closed refusal has its own sentence and is never + * retried; a generic outcome keeps the template's sentence and its deliberate same-request retry. No API text is shown. + */ +function dataRequestMutationContent( + page: Extract, + copy: AuthCopy, + locale: string, +): string { + const { admin, dataRequest } = createAdministrationTranslator(locale); + const refusal = page.dataRequest?.refusal ?? null; + const generic: Record['reason'], string> = { + denied: copy('mutation.denied'), + stale: copy('mutation.stale'), + in_progress: copy('mutation.in_progress'), + key_reuse: copy('mutation.key_reuse'), + unavailable: copy('mutation.unavailable'), + validation: dataRequest('error.confirmation'), + }; + const message = + refusal === null + ? generic[page.reason] + : dataRequestRefusalSentence(refusal, admin, dataRequest); + const own = + refusal === 'subject_is_requester' + ? `

${escape(admin('data_requests.own_data'))}

` + : ''; + const retry = + refusal === null && page.retryable + ? `
${page.fields.map(([name, value]) => hidden(name, value)).join('')}` + : ''; + return `

${escape(message)}

${own}

${escape(copy('mutation.lookup'))}

${retry}`; +} + function mutationContent( page: Extract, copy: AuthCopy, @@ -276,6 +313,8 @@ function mutationContent( ): string { if (page.action.startsWith('/api/studio/federation-')) return federationMutationContent(page, copy, locale); + if (page.action.startsWith('/api/studio/data-request-')) + return dataRequestMutationContent(page, copy, locale); const customField = customFieldMutationContent(page, locale, site); if (customField !== null) return customField; if (page.reason === 'validation' && page.action.startsWith('/api/studio/invitation-')) @@ -402,7 +441,7 @@ export function renderBffDocument( }

${escape(copy('shell.catalog'))}

`; const recovery = - page.kind === 'mutation_error' && isNativeReturnPath(page.destination) + page.kind === 'mutation_error' && isBffRecoveryTarget(page.destination) ? page.destination : page.kind === 'entry' || page.kind === 'scope_choices' || diff --git a/frontend/apps/web/src/server/auth/http-admission.test.ts b/frontend/apps/web/src/server/auth/http-admission.test.ts index f6c338c28..44fdfb2dd 100644 --- a/frontend/apps/web/src/server/auth/http-admission.test.ts +++ b/frontend/apps/web/src/server/auth/http-admission.test.ts @@ -142,6 +142,41 @@ describe('pinned Next / native BFF admission seam', () => { h.stop(); } }); + it.each([ + [ + '/api/studio/data-request-cancel', + { requestId: '019a154b-0000-7000-8000-000000000041' }, + '/studio/data-requests/019a154b-0000-7000-8000-000000000041?result=cancelled', + ], + [ + '/api/studio/membership-status', + { membershipId: '019a154b-0000-7000-8000-000000000011', status: 'Revoked' }, + '/studio/data-requests/erasure?membership=019a154b-0000-7000-8000-000000000011', + ], + ])( + 'a settled %s keeps its closed data-request destination through the Next seam', + async (path, fields, destination) => { + const f = fixture(); + const h = harness(f); + try { + const active = await f.login(); + const result = await h.run(path, { + method: 'POST', + body: new URLSearchParams({ + csrfToken: active.finished.session.csrfToken, + idempotencyKey: 'deliberate-data-request-key', + version: '3', + ...fields, + }).toString(), + cookie: active.cookie, + }); + expect(result.response?.status).toBe(303); + expect(result.response!.headers.get('location')).toBe('https://' + bffHost + destination); + } finally { + h.stop(); + } + }, + ); it('no provider/cookie/session work runs before native live-host bootstrap, including auth POST', async () => { const f = fixture(); const h = harness(f); diff --git a/frontend/apps/web/src/server/auth/http-admission.ts b/frontend/apps/web/src/server/auth/http-admission.ts index 7ec2f6484..1e3d72204 100644 --- a/frontend/apps/web/src/server/auth/http-admission.ts +++ b/frontend/apps/web/src/server/auth/http-admission.ts @@ -9,7 +9,7 @@ import { readPublicAdmission } from '../public-admission'; import type { BffPageRenderer } from './http-protocol'; import { bffRequestOwner } from './request-owner'; import { bffSessionProtocol } from './session-owner'; -import { isNativeReturnPath } from './session-path'; +import { isBffRedirectTarget } from './session-path'; /** Host admission must already be published by the real bootstrap. */ export async function admitBffHttp( @@ -53,10 +53,11 @@ export async function admitBffHttp( const headers = new Headers(response.headers); const location = headers.get('location'); // Next's middleware adapter requires an absolute Location. Only the independently - // verified host and the owner's closed return paths can form a local redirect. + // verified host and the owner's closed destinations (return paths, and the data-request + // pages with their one closed query) can form a local redirect. if (location?.startsWith('/')) { if ( - !isNativeReturnPath(location) && + !isBffRedirectTarget(location) && !['/api/auth/entry', '/api/auth/signin', '/invitations', '/invitations/confirm'].includes( location, ) diff --git a/frontend/apps/web/src/server/auth/http-forms.ts b/frontend/apps/web/src/server/auth/http-forms.ts index b48b7d259..8dc5a1965 100644 --- a/frontend/apps/web/src/server/auth/http-forms.ts +++ b/frontend/apps/web/src/server/auth/http-forms.ts @@ -9,6 +9,11 @@ import { FEDERATION_FORMS, federationForm } from './federation-forms.js'; import { BffInputError } from './input-error.js'; import type { NativeScope } from './native-contract.js'; import type { NativeOperation } from './native-operation-contract.js'; +import type { + DataRequestAdministrationRefusal, + DataRequestAdministrationResult, +} from './page-contract.js'; +import { dataRequestErasureTarget } from './session-path.js'; export { bffCursor, bffPageQuery } from './page-query.js'; @@ -134,15 +139,86 @@ export class BffProfileInputError extends BffInputError { super(); } } +/** A data-request erasure without its explicit confirmation is recoverable after its proof and target grammar. */ +export class BffDataRequestConfirmationError extends BffInputError {} /** User-editable invitation values are recoverable after proof/target grammar succeeds. */ export class BffInvitationInputError extends BffInputError { constructor(readonly invalidFields: readonly ('email' | 'offeredRole' | 'days')[]) { super(); } } +/** + * ADR-0106 §§ 3, 10, 11 and ADR-0107 § 4: the administrator's data-request forms. A creation names a Membership of + * the context's group, never a User; cancellation carries the request's version and revocation the artifact's. The + * erasure's explicit confirmation is re-checked here, before any API work. + */ +export const DATA_REQUEST_ADMIN_FORMS: Readonly> = Object.freeze({ + '/api/studio/data-request-export': ['csrfToken', 'idempotencyKey', 'membershipId'], + '/api/studio/data-request-erasure': ['csrfToken', 'idempotencyKey', 'membershipId', 'confirm'], + '/api/studio/data-request-cancel': [...common, 'requestId'], + '/api/studio/data-request-revoke': [...common, 'requestId'], +}); +/** + * The closed refusals of those routes (`errors.$` or `errors.artifact` of a 409 `business_rule_violation`). A reason + * missing here renders the generic refusal; the catalogue test fails on every API reason this table does not name. + */ +export const DATA_REQUEST_ADMIN_REFUSALS: Readonly< + Record> +> = Object.freeze({ + lockey_request_already_active: 'request_already_active', + lockey_blocked_hold: 'blocked_hold', + lockey_blocked_last_administrator: 'blocked_last_administrator', + lockey_subject_export_available: 'subject_export_available', + lockey_subject_membership_current: 'subject_membership_current', + lockey_subject_is_requester: 'subject_is_requester', + lockey_subject_not_admitted: 'subject_not_admitted', + lockey_snapshot_too_large: 'snapshot_too_large', + lockey_data_export_unavailable: 'data_export_unavailable', + lockey_data_request_window_ended: 'data_request_window_ended', + lockey_data_request_not_cancellable: 'data_request_not_cancellable', +}); +/** One refusal from the reasons an API problem carries; never the API's own text. */ +export function dataRequestAdministrationRefusal( + errors: Readonly[]>> | undefined, +): DataRequestAdministrationRefusal { + for (const reason of [...(errors?.['$'] ?? []), ...(errors?.['artifact'] ?? [])]) + if (Object.hasOwn(DATA_REQUEST_ADMIN_REFUSALS, reason.key)) + return DATA_REQUEST_ADMIN_REFUSALS[reason.key]!; + return 'unknown'; +} +const DATA_REQUEST_RESULTS: Readonly> = + Object.freeze({ + '/api/studio/data-request-export': 'export', + '/api/studio/data-request-erasure': 'erasure', + '/api/studio/data-request-cancel': 'cancelled', + '/api/studio/data-request-revoke': 'revoked', + }); +/** + * The fixed same-host 303 after a settled data-request action: the request's own page with its closed result. A + * creation's request comes only from the exact `Location` the SDK validated; anything else is refused (null). + */ +export function dataRequestAdministrationDestination( + path: string, + destination: string, + location: string | null, +): string | null { + if (!Object.hasOwn(DATA_REQUEST_RESULTS, path)) return null; + const result = DATA_REQUEST_RESULTS[path]!; + let request = destination; + if (result === 'export' || result === 'erasure') { + const match = + /^\/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})$/.exec( + location ?? '', + ); + if (!match) return null; + request = '/studio/data-requests/' + match[1]; + } + return request + '?result=' + result; +} export const BFF_ADMIN_FORMS: Readonly> = Object.freeze({ ...CUSTOM_FIELD_FORMS, ...FEDERATION_FORMS, + ...DATA_REQUEST_ADMIN_FORMS, '/api/studio/membership-profile': [...common, 'membershipId', 'displayName', 'preferredLocale'], '/api/studio/membership-roles': [...common, 'membershipId', 'roleIds'], '/api/studio/membership-status': [...common, 'membershipId', 'status'], @@ -180,11 +256,15 @@ function profile(fields: URLSearchParams) { if (invalid.length) throw new BffProfileInputError(Object.freeze(invalid)); return result; } +/** + * One administration form's operation, the fixed GET its refusal recovers to, and, where it differs, the fixed GET a + * settled action answers with a 303. + */ export function bffAdministrationForm( path: string, fields: URLSearchParams, customFields?: MembershipCustomFields, -): Readonly<{ operation: NativeOperation; destination: string }> { +): Readonly<{ operation: NativeOperation; destination: string; settledDestination?: string }> { if (Object.hasOwn(CUSTOM_FIELD_FORMS, path)) return customFieldForm(path, fields, customFields); // ADR-0099: federation forms carry no idempotency key; the connection revision converges them. if (Object.hasOwn(FEDERATION_FORMS, path)) return federationForm(path, fields); @@ -260,7 +340,35 @@ export function bffAdministrationForm( destination: '/studio/invitation-policy', }; } + if (path === '/api/studio/data-request-export' || path === '/api/studio/data-request-erasure') { + const membershipId = id(required(fields, 'membershipId')); + const erasure = path === '/api/studio/data-request-erasure'; + // ADR-0106 § 11: the explicit confirmation the page asked for, re-checked before any API work. + if (erasure && fields.get('confirm') !== 'erase') throw new BffDataRequestConfirmationError(); + return { + operation: { + kind: erasure ? 'createDataErasureForSubject' : 'createDataExportForSubject', + membershipId, + idempotencyKey, + }, + // A Revoked Membership has no member page: an erasure recovers to the erasure page it was filed from. + destination: erasure + ? dataRequestErasureTarget(membershipId) + : '/studio/members/' + membershipId, + }; + } const write = { version: readVersion(), idempotencyKey }; + if (path === '/api/studio/data-request-cancel' || path === '/api/studio/data-request-revoke') { + const requestId = id(required(fields, 'requestId')); + return { + operation: { + kind: path === '/api/studio/data-request-cancel' ? 'cancelDataRequest' : 'revokeDataExport', + ...write, + id: requestId, + }, + destination: '/studio/data-requests/' + requestId, + }; + } if (path === '/api/studio/invitation-revoke' || path === '/api/studio/invitation-reissue') { const invitationId = id(required(fields, 'invitationId')); return { @@ -306,6 +414,9 @@ export function bffAdministrationForm( status: status as 'Active' | 'Suspended' | 'Revoked', }, destination: status === 'Revoked' ? '/studio/members' : destination, + // ADR-0106 § 3: a Revoked Membership has no member page; its erasure is filed on the page the revocation + // leads to, which reads nothing about it. + ...(status === 'Revoked' ? { settledDestination: dataRequestErasureTarget(member) } : {}), }; } } diff --git a/frontend/apps/web/src/server/auth/http-paths.ts b/frontend/apps/web/src/server/auth/http-paths.ts index be69b60e7..38dc6a08d 100644 --- a/frontend/apps/web/src/server/auth/http-paths.ts +++ b/frontend/apps/web/src/server/auth/http-paths.ts @@ -10,6 +10,19 @@ export const BFF_POST_PATHS = Object.freeze([ '/api/auth/invitation/cancel', '/api/auth/entry/consents', '/api/auth/entry/consents/withdraw', + '/api/auth/entry/data-requests', + '/api/auth/entry/data-requests/export', + '/api/auth/entry/data-requests/erasure', + '/api/auth/entry/data-requests/closure', + '/api/auth/entry/data-requests/cancel', + '/api/auth/entry/data-requests/revoke', + '/api/auth/entry/data-requests/download', + '/api/account/data-requests/export', + '/api/account/data-requests/erasure', + '/api/account/data-requests/closure', + '/api/account/data-requests/cancel', + '/api/account/data-requests/revoke', + '/api/account/data-requests/download', '/api/studio/custom-field-create', '/api/studio/custom-field-revise', '/api/studio/custom-field-publish', @@ -23,6 +36,10 @@ export const BFF_POST_PATHS = Object.freeze([ '/api/studio/invitation-revoke', '/api/studio/invitation-reissue', '/api/studio/invitation-policy', + '/api/studio/data-request-export', + '/api/studio/data-request-erasure', + '/api/studio/data-request-cancel', + '/api/studio/data-request-revoke', '/api/studio/federation-test', '/api/studio/federation-configure', '/api/studio/federation-rotate-secret', @@ -45,6 +62,18 @@ export const BFF_POST_PATHS = Object.freeze([ '/api/studio/role-manifest-adoption', '/api/account/profile', ]); +/** + * ADR-0106 § 9, ADR-0107 § 4: the native data-request document and its fixed actions. Only the pre-Next data-request + * handler serves them; Next and the BFF protocol answer them `404`. + */ +export const DATA_REQUEST_DOCUMENT_PATHS = Object.freeze([ + '/account/data', + ...BFF_POST_PATHS.filter( + (path) => + path.startsWith('/api/auth/entry/data-requests') || + path.startsWith('/api/account/data-requests/'), + ), +]); export function bffPostTarget(method: string, target: string): boolean { return method === 'POST' && BFF_POST_PATHS.includes(target); } @@ -53,6 +82,7 @@ export function bffPostTarget(method: string, target: string): boolean { export function bffActionDocumentTarget(target: string): boolean { return ( BFF_POST_PATHS.includes(target) && + !DATA_REQUEST_DOCUMENT_PATHS.includes(target) && (target.startsWith('/api/studio/') || target.startsWith('/api/account/') || target === '/api/auth/switch' || diff --git a/frontend/apps/web/src/server/auth/http-protocol.ts b/frontend/apps/web/src/server/auth/http-protocol.ts index 22cb154f2..7beac12ab 100644 --- a/frontend/apps/web/src/server/auth/http-protocol.ts +++ b/frontend/apps/web/src/server/auth/http-protocol.ts @@ -23,15 +23,20 @@ import { } from './federation-forms.js'; import { BFF_ADMIN_FORMS, + BffDataRequestConfirmationError, BffProfileInputError, BffInvitationInputError, + DATA_REQUEST_ADMIN_FORMS, bffAdministrationForm, bffContextHint, bffCursor, bffScope, + dataRequestAdministrationDestination, + dataRequestAdministrationRefusal, } from './http-forms.js'; import { bffActivity, bffForm, bffQuery, bffRoute, exactBffOrigin } from './http-input.js'; import type { BffHttpRequest } from './http-input.js'; +import { DATA_REQUEST_DOCUMENT_PATHS } from './http-paths.js'; import { NativeApiError } from './native-contract.js'; import type { NativeOperationResult } from './native-operation-contract.js'; import type { NativeActionPage, NativeEntrySnapshot, ScopeChoices } from './page-contract.js'; @@ -47,7 +52,7 @@ import type { SessionBinding, SessionProjection, } from './session-contract.js'; -import { isNativeReturnPath } from './session-path.js'; +import { dataRequestErasureTarget, isNativeReturnPath } from './session-path.js'; import { bffSecretEquals, isBffOpaque } from './session-store.js'; const opaque = () => randomBytes(32).toString('base64url'); @@ -368,8 +373,8 @@ export function createBffHttpProtocol(store: BffSessionStore, preparation?: Nati const httpSignal = request.signal; let postDeadline: AbortSignal | undefined; const path = request.target.split('?', 1)[0]!; - // Recipient actions belong only to the pre-Next native handler. - if (path.startsWith('/api/auth/invitation/')) + // Recipient and data-request actions belong only to their pre-Next native handlers. + if (path.startsWith('/api/auth/invitation/') || DATA_REQUEST_DOCUMENT_PATHS.includes(path)) return result(request, { code: 'not_found' }, 404); // An inert public query is not a logout action. Only an owned proof-cookie // family selects the root return protocol; unrecognized states touch nothing. @@ -739,6 +744,8 @@ export function createBffHttpProtocol(store: BffSessionStore, preparation?: Nati const csrf = fields.get('csrfToken'); if (!current || !session || !bffSecretEquals(csrf, session.csrfToken)) return result(request, { code: 'csrf' }, 403); + // ADR-0106: a data-request action's recovery names its closed refusal, or none for a generic outcome. + const dataRequestForm = Object.hasOwn(DATA_REQUEST_ADMIN_FORMS, path); let customFields: MembershipCustomFields | undefined; if ( (path === '/api/account/custom-fields' || @@ -825,6 +832,25 @@ export function createBffHttpProtocol(store: BffSessionStore, preparation?: Nati 400, ); } + if (error instanceof BffDataRequestConfirmationError) + return await actionDocument( + request, + render, + current, + { + kind: 'mutation_error', + action: path, + // Thrown only after the Membership identifier passed its canonical grammar; a Revoked + // Membership has no member page, so the erasure page it was filed from is the recovery. + destination: dataRequestErasureTarget(fields.get('membershipId')!), + fields: [['csrfToken', csrf!]], + reason: 'validation', + retryable: false, + dataRequest: { refusal: null }, + }, + { code: 'validation_failed' }, + 400, + ); if (error instanceof BffFederationInputError) return await actionDocument( request, @@ -909,6 +935,7 @@ export function createBffHttpProtocol(store: BffSessionStore, preparation?: Nati reason: 'unavailable', // An unconfirmed federation write is settled by Resume, never resubmitted (ADR-0099). retryable: !Object.hasOwn(FEDERATION_FORMS, path), + ...(dataRequestForm ? { dataRequest: { refusal: null } } : {}), }, { code: 'unavailable' }, 503, @@ -937,6 +964,15 @@ export function createBffHttpProtocol(store: BffSessionStore, preparation?: Nati { code: settled }, 200, ); + if (dataRequestForm) { + const destination = dataRequestAdministrationDestination( + path, + form.destination, + outcome.location, + ); + if (destination === null) throw new BffSessionError('response'); + return redirect(request, destination, []); + } if (path === '/api/studio/invitation-create') { const location = outcome.location; const match = @@ -946,7 +982,7 @@ export function createBffHttpProtocol(store: BffSessionStore, preparation?: Nati if (!match) throw new BffSessionError('response'); return redirect(request, '/studio/invitations/' + match[1], []); } - return redirect(request, form.destination, []); + return redirect(request, form.settledDestination ?? form.destination, []); } const status = outcome.kind === 'api-error' @@ -998,23 +1034,33 @@ export function createBffHttpProtocol(store: BffSessionStore, preparation?: Nati outcome.kind === 'api-error' && outcome.error.code === 'validation_failed' ? Object.keys(outcome.error.fieldErrors) : []; + // ADR-0106 § 7: a closed business refusal is final for this request; it is explained, never retried. + const refusal = + dataRequestForm && + outcome.kind === 'api-error' && + outcome.status === 409 && + outcome.problem.code === 'business_rule_violation' + ? dataRequestAdministrationRefusal(outcome.problem.errors) + : null; const reason = - code === 'validation_failed' && - (path === '/api/account/profile' || - path === '/api/studio/membership-profile' || - path.startsWith('/api/studio/invitation-') || - Object.hasOwn(CUSTOM_FIELD_FORMS, path) || - Object.hasOwn(FEDERATION_FORMS, path)) - ? 'validation' - : code === 'concurrency_conflict' - ? 'stale' - : code === 'request_in_progress' - ? 'in_progress' - : code === 'idempotency_key_reuse' - ? 'key_reuse' - : [401, 403, 404].includes(status) - ? 'denied' - : 'unavailable'; + refusal !== null + ? 'denied' + : code === 'validation_failed' && + (path === '/api/account/profile' || + path === '/api/studio/membership-profile' || + path.startsWith('/api/studio/invitation-') || + Object.hasOwn(CUSTOM_FIELD_FORMS, path) || + Object.hasOwn(FEDERATION_FORMS, path)) + ? 'validation' + : code === 'concurrency_conflict' + ? 'stale' + : code === 'request_in_progress' + ? 'in_progress' + : code === 'idempotency_key_reuse' + ? 'key_reuse' + : [401, 403, 404].includes(status) + ? 'denied' + : 'unavailable'; return await actionDocument( request, render, @@ -1043,6 +1089,7 @@ export function createBffHttpProtocol(store: BffSessionStore, preparation?: Nati ...(Object.hasOwn(FEDERATION_FORMS, path) ? { federation: { invalid: [], outcome: null } } : {}), + ...(dataRequestForm ? { dataRequest: { refusal } } : {}), }, { code }, status, diff --git a/frontend/apps/web/src/server/auth/native-administration-client.ts b/frontend/apps/web/src/server/auth/native-administration-client.ts index d2d001a87..578c67f45 100644 --- a/frontend/apps/web/src/server/auth/native-administration-client.ts +++ b/frontend/apps/web/src/server/auth/native-administration-client.ts @@ -6,16 +6,43 @@ import type { NativeBinding, NativeScope } from './native-contract.js'; import type { NativeAdministrationCaller, NativeRetainedConsentCaller, + NativeRetainedDataRequestCaller, NativeOperationResult, NativeOperation, + RetainedDataRequestOperation, } from './native-operation-contract.js'; +/** The closed retained data-request entry set (ADR-0106 § 9); only its own caller performs these. */ +const RETAINED_DATA_REQUESTS: readonly string[] = Object.freeze([ + 'listRetainedDataRequestScopes', + 'listRetainedDataRequests', + 'createRetainedDataExport', + 'createRetainedDataErasure', + 'createRetainedAccountClosure', + 'cancelRetainedDataRequest', + 'revokeRetainedDataExport', + 'mintRetainedDataExportTicket', + 'readRetainedDataExportChunk', +] satisfies readonly RetainedDataRequestOperation['kind'][]); +/** Selector-free operations: a retained entry carries no tenant or organization header. */ +const UNSCOPED: readonly string[] = Object.freeze([ + 'listOwnConsentScopes', + 'listOwnConsentHistory', + 'withdrawOwnFieldConsent', + ...RETAINED_DATA_REQUESTS, +]); + /** One explicit dispatcher over the generated SDK's finite operations; no generic HTTP capability escapes. */ export function createNativeAdministrationCaller( configuration: NativeApiConfiguration, transport: typeof fetch, ) { - return createCaller(configuration, transport) satisfies NativeAdministrationCaller; + const caller = createCaller(configuration, transport); + // A session credential never performs a retained-entry data-request operation. + return ((token, binding, operation, signal) => + RETAINED_DATA_REQUESTS.includes(operation.kind) + ? Promise.resolve({ kind: 'invalid-request' }) + : caller(token, binding, operation, signal)) satisfies NativeAdministrationCaller; } export function createNativeRetainedConsentCaller( configuration: NativeApiConfiguration, @@ -23,12 +50,23 @@ export function createNativeRetainedConsentCaller( ): NativeRetainedConsentCaller { return createCaller(configuration, transport); } +/** The retained data-request entry's own caller: only its closed operations, never a scoped one. */ +export function createNativeRetainedDataRequestCaller( + configuration: NativeApiConfiguration, + transport: typeof fetch, +): NativeRetainedDataRequestCaller { + const caller = createCaller(configuration, transport); + return (token, binding, operation, signal) => + RETAINED_DATA_REQUESTS.includes(operation.kind) + ? caller(token, binding, operation, signal) + : Promise.resolve({ kind: 'invalid-request' }); +} function createCaller(configuration: NativeApiConfiguration, transport: typeof fetch) { const request = createNativeApiTransport(configuration, transport); return async ( token: string, binding: NativeBinding & Partial, - operation: NativeOperation, + operation: NativeOperation | RetainedDataRequestOperation, signal: AbortSignal, ): Promise => { if (signal.aborted) return { kind: 'cancelled' }; @@ -38,11 +76,7 @@ function createCaller(configuration: NativeApiConfiguration, transport: typeof f return await request( token, binding, - ['listOwnConsentScopes', 'listOwnConsentHistory', 'withdrawOwnFieldConsent'].includes( - operation.kind, - ) - ? null - : (binding as NativeBinding & NativeScope), + UNSCOPED.includes(operation.kind) ? null : (binding as NativeBinding & NativeScope), path, init, signal, @@ -165,6 +199,104 @@ function createCaller(configuration: NativeApiConfiguration, transport: typeof f }); break; + case 'listOwnDataRequests': + result = await sdk.listOwnDataRequests({ + ...read, + cursor: operation.cursor, + limit: operation.limit, + }); + break; + case 'createOwnDataExport': + case 'createOwnDataErasure': + case 'createOwnAccountClosure': + result = await sdk[operation.kind]({ idempotencyKey: operation.idempotencyKey, signal }); + break; + case 'cancelOwnDataRequest': + case 'revokeOwnDataExport': + result = await sdk[operation.kind]( + operation.id, + write(operation.version, operation.idempotencyKey), + ); + break; + case 'mintOwnDataExportTicket': + result = await sdk.mintOwnDataExportTicket(operation.id, read); + break; + case 'readOwnDataExportChunk': + result = await sdk.readOwnDataExportChunk( + operation.id, + operation.ticket, + operation.index, + read, + ); + break; + case 'listRetainedDataRequestScopes': + result = await sdk.listRetainedDataRequestScopes({ + ...read, + cursor: operation.cursor, + limit: operation.limit, + }); + break; + case 'listRetainedDataRequests': + result = await sdk.listRetainedDataRequests(operation.group, { + ...read, + cursor: operation.cursor, + limit: operation.limit, + }); + break; + case 'createRetainedDataExport': + case 'createRetainedDataErasure': + case 'createRetainedAccountClosure': + result = await sdk[operation.kind](operation.group, { + idempotencyKey: operation.idempotencyKey, + signal, + }); + break; + case 'cancelRetainedDataRequest': + case 'revokeRetainedDataExport': + result = await sdk[operation.kind]( + operation.group, + operation.id, + write(operation.version, operation.idempotencyKey), + ); + break; + case 'mintRetainedDataExportTicket': + result = await sdk.mintRetainedDataExportTicket(operation.group, operation.id, read); + break; + case 'readRetainedDataExportChunk': + result = await sdk.readRetainedDataExportChunk( + operation.group, + operation.id, + operation.ticket, + operation.index, + read, + ); + break; + + case 'listDataRequests': + result = await sdk.listDataRequests({ + ...read, + cursor: operation.cursor, + limit: operation.limit, + }); + break; + case 'getDataRequest': + result = await sdk.getDataRequest(operation.id, read); + break; + case 'createDataExportForSubject': + case 'createDataErasureForSubject': + result = await sdk[operation.kind](operation.membershipId, { + idempotencyKey: operation.idempotencyKey, + signal, + }); + break; + case 'cancelDataRequest': + case 'revokeDataExport': + result = await sdk[operation.kind]( + operation.id, + write(operation.version, operation.idempotencyKey), + ); + break; + case 'listMemberships': result = await sdk.listMemberships({ ...read, diff --git a/frontend/apps/web/src/server/auth/native-api-transport.ts b/frontend/apps/web/src/server/auth/native-api-transport.ts index 8240da4ff..f6caf0f74 100644 --- a/frontend/apps/web/src/server/auth/native-api-transport.ts +++ b/frontend/apps/web/src/server/auth/native-api-transport.ts @@ -140,6 +140,10 @@ export function createNativeApiTransport( const cancel = () => { if (reader) cancellation ??= reader.cancel().catch(() => undefined); }; + // A data-export chunk body is decrypted plaintext. Every byte buffer read here is zeroed once the response is + // built or refused: the returned Response holds its own copy (Fetch's body extraction copies a BufferSource). + const chunks: Uint8Array[] = []; + let body: Uint8Array | undefined; try { interrupted(); const response = await transport(apiOrigin + path, { @@ -159,21 +163,23 @@ export function createNativeApiTransport( if ( response.redirected || response.headers.has('set-cookie') || - (response.status < 400 && ![200, 201].includes(response.status)) || + // The transport admits every success status an operation of the closed clients declares: 202 is a + // data-request creation's acceptance (ADR-0106 § 10). It does not decide which operation expects which: + // each SDK operation refuses any success status other than its own as `unexpected-status`. + (response.status < 400 && ![200, 201, 202].includes(response.status)) || media !== (response.status < 400 ? 'application/json' : 'application/problem+json') ) throw new NativeApiError('response'); - const chunks: Uint8Array[] = []; let bytes = 0; while (reader) { const chunk = await reader.read(); interrupted(); if (chunk.done) break; + chunks.push(chunk.value); bytes += chunk.value.byteLength; if (bytes > NATIVE_API_MAX_BYTES) throw new NativeApiError('response'); - chunks.push(chunk.value); } - const body = new Uint8Array(bytes); + body = new Uint8Array(bytes); let offset = 0; for (const chunk of chunks) { body.set(chunk, offset); @@ -195,6 +201,8 @@ export function createNativeApiTransport( interrupted(); throw error instanceof NativeApiError ? error : new NativeApiError('transport'); } finally { + for (const chunk of chunks) chunk.fill(0); + body?.fill(0); signal.removeEventListener('abort', cancel); cancel(); if (cancellation) await cancellation; diff --git a/frontend/apps/web/src/server/auth/native-data-request-client.test.ts b/frontend/apps/web/src/server/auth/native-data-request-client.test.ts new file mode 100644 index 000000000..045a5f36a --- /dev/null +++ b/frontend/apps/web/src/server/auth/native-data-request-client.test.ts @@ -0,0 +1,259 @@ +// @vitest-environment node +import { describe, expect, it, vi } from 'vitest'; + +import { + createNativeAdministrationCaller, + createNativeRetainedDataRequestCaller, +} from './native-administration-client'; +import type { RetainedDataRequestOperation } from './native-operation-contract'; + +const id = '019a154b-0000-7000-8000-000000000011'; +const tenant = '019a154b-0000-7000-8000-0000000000ff'; +const configuration = { + apiOrigin: 'https://api.example.test', + secret: 'private-hop-'.padEnd(48, 'x'), + nativeSourceSecret: Buffer.from(Array.from({ length: 32 }, (_, index) => index + 1)).toString( + 'base64url', + ), +}; +const binding = { host: 'institution.example.test:3000', source: '203.0.113.19' }; +const json = (value: unknown, status = 200, headers: Record = {}) => + new Response(JSON.stringify(value), { + status, + headers: { 'content-type': 'application/json', 'cache-control': 'no-store', ...headers }, + }); +const signal = () => new AbortController().signal; + +describe('native data-request operation sources (ADR-0106 § 9)', () => { + it('performs the retained set selector-free and nothing else on the retained caller', async () => { + const transport = vi.fn(async () => + json({ + items: [], + pageInfo: { nextCursor: null, previousCursor: null, hasNext: false, hasPrevious: false }, + }), + ); + const caller = createNativeRetainedDataRequestCaller(configuration, transport); + expect( + ( + await caller( + 'owned-token', + binding, + { kind: 'listRetainedDataRequests', group: 'tenant', limit: 20 }, + signal(), + ) + ).kind, + ).toBe('success'); + expect(transport.mock.calls[0]![0]).toBe( + 'https://api.example.test/api/v1/identity/data-request-entry/requests?group=tenant&limit=20', + ); + const headers = new Headers(transport.mock.calls[0]![1]!.headers); + expect(headers.get('X-LearnStack-Native-Session-Secret')).toBe( + configuration.nativeSourceSecret, + ); + expect(headers.has('X-LearnStack-Native-Tenant-Id')).toBe(false); + expect(headers.has('X-LearnStack-Native-Organization-Id')).toBe(false); + for (const operation of [ + { kind: 'listOwnDataRequests', limit: 20 }, + { kind: 'listOwnConsentScopes' }, + { kind: 'getOwnCapabilities' }, + ]) + expect( + await caller( + 'owned-token', + binding, + operation as unknown as RetainedDataRequestOperation, + signal(), + ), + ).toEqual({ kind: 'invalid-request' }); + expect(transport).toHaveBeenCalledOnce(); + }); + + it('keeps own operations in the session scope and refuses retained ones on the session caller', async () => { + const transport = vi.fn(async () => + json({ id, kind: 'export', status: 'requested', version: '0' }, 202, { + etag: '"0"', + location: '/api/v1/identity/me/data-requests/' + id, + }), + ); + const caller = createNativeAdministrationCaller(configuration, transport); + const scoped = { ...binding, tenantId: tenant, organizationId: null }; + const result = await caller( + 'owned-token', + scoped, + { kind: 'createOwnDataExport', idempotencyKey: 'k'.repeat(43) }, + signal(), + ); + expect(result).toMatchObject({ kind: 'success', status: 202 }); + const init = transport.mock.calls[0]![1]!; + expect(new Headers(init.headers).get('X-LearnStack-Native-Tenant-Id')).toBe(tenant); + expect(new Headers(init.headers).get('Idempotency-Key')).toBe('k'.repeat(43)); + expect( + await caller( + 'owned-token', + scoped, + { kind: 'listRetainedDataRequestScopes' } as never, + signal(), + ), + ).toEqual({ kind: 'invalid-request' }); + expect(transport).toHaveBeenCalledOnce(); + }); + + it('admits 202 as a success status and still refuses any other 2xx', async () => { + const accepted = vi.fn(async () => + json({ id, kind: 'export', status: 'requested', version: '0' }, 202, { + etag: '"0"', + location: '/api/v1/identity/me/data-requests/' + id, + }), + ); + const caller = createNativeAdministrationCaller(configuration, accepted); + const scoped = { ...binding, tenantId: tenant, organizationId: null }; + const own = { kind: 'createOwnDataExport', idempotencyKey: 'k'.repeat(43) } as const; + expect(await caller('owned-token', scoped, own, signal())).toMatchObject({ + kind: 'success', + status: 202, + }); + const other = createNativeAdministrationCaller( + configuration, + vi.fn(async () => json({}, 203)), + ); + await expect(other('owned-token', scoped, own, signal())).rejects.toThrow(); + }); + + it('refuses a 202 for every operation whose success is 200 or 201: the transport admits it, the SDK does not', async () => { + const transport = vi.fn(async () => + json({ displayName: 'Person', preferredLocale: null, version: '1' }, 202, { etag: '"1"' }), + ); + const caller = createNativeAdministrationCaller(configuration, transport); + const scoped = { ...binding, tenantId: tenant, organizationId: null }; + for (const operation of [ + { kind: 'getOwnProfile' }, + { + kind: 'createInvitation', + invitation: { email: 'person@example.test', roleId: id, roleVersion: '1' }, + idempotencyKey: 'k'.repeat(43), + }, + { kind: 'mintOwnDataExportTicket', id }, + ] as const) + expect(await caller('owned-token', scoped, operation, signal())).toEqual({ + kind: 'invalid-response', + reason: 'unexpected-status', + }); + expect(transport).toHaveBeenCalledTimes(3); + }); + + it('zeroes every buffer of a chunk body the transport read, once the response holds its own copy', async () => { + const plain = Buffer.alloc(131072, 0x61); + const payload = Buffer.from( + JSON.stringify({ index: 0, count: 2, bytes: plain.toString('base64') }), + ); + const parts = [ + new Uint8Array(payload.subarray(0, 1000)), + new Uint8Array(payload.subarray(1000)), + ]; + const transport = vi.fn( + async () => + new Response( + new ReadableStream({ + start(controller) { + for (const part of parts) controller.enqueue(part); + controller.close(); + }, + }), + { headers: { 'content-type': 'application/json', 'cache-control': 'no-store' } }, + ), + ); + // The transport's assembled body is the array its own reads are copied into. + const assembled: Uint8Array[] = []; + const set = Uint8Array.prototype.set; + vi.spyOn(Uint8Array.prototype, 'set').mockImplementation(function ( + this: Uint8Array, + source: ArrayLike, + offset?: number, + ) { + if (parts.includes(source as Uint8Array)) assembled.push(this); + return set.call(this, source, offset); + }); + const caller = createNativeAdministrationCaller(configuration, transport); + const result = await caller( + 'owned-token', + { ...binding, tenantId: tenant, organizationId: null }, + { kind: 'readOwnDataExportChunk', id, ticket: 'T'.repeat(42) + 'A', index: 0 }, + signal(), + ); + expect(result).toMatchObject({ + kind: 'success', + data: { index: 0, count: 2, bytes: plain.toString('base64') }, + }); + for (const part of parts) expect(part.every((byte) => byte === 0)).toBe(true); + expect(assembled).toHaveLength(2); + expect(assembled[1]).toBe(assembled[0]); + expect(assembled[0]!.byteLength).toBe(payload.byteLength); + expect(assembled[0]!.every((byte) => byte === 0)).toBe(true); + }); + + it("performs the administrator's group operations in the session's exact scope only", async () => { + const organization = '019a154b-0000-7000-8000-0000000000ee'; + const receipt = { + id, + kind: 'export', + origin: 'administrator', + status: 'requested', + createdAt: '2026-11-23T10:00:00Z', + updatedAt: null, + completedAt: null, + lastRefusal: null, + failureReason: null, + retained: [], + artifact: null, + version: '0', + executeAt: null, + requestedByYou: true, + membershipIds: [tenant.slice(0, -2) + '12'], + }; + const transport = vi.fn(async (input) => + String(input).endsWith('/data-requests?limit=20') + ? json({ + items: [receipt], + pageInfo: { + nextCursor: null, + previousCursor: null, + hasNext: false, + hasPrevious: false, + }, + }) + : json(receipt, 200, { etag: '"0"' }), + ); + const caller = createNativeAdministrationCaller(configuration, transport); + const scoped = { ...binding, tenantId: tenant, organizationId: organization }; + expect( + (await caller('owned-token', scoped, { kind: 'listDataRequests', limit: 20 }, signal())).kind, + ).toBe('success'); + expect( + (await caller('owned-token', scoped, { kind: 'getDataRequest', id }, signal())).kind, + ).toBe('success'); + expect(transport.mock.calls.map(([url]) => url)).toEqual([ + 'https://api.example.test/api/v1/identity/data-requests?limit=20', + 'https://api.example.test/api/v1/identity/data-requests/' + id, + ]); + for (const [, init] of transport.mock.calls) { + const headers = new Headers(init!.headers); + expect(headers.get('X-LearnStack-Native-Tenant-Id')).toBe(tenant); + expect(headers.get('X-LearnStack-Native-Organization-Id')).toBe(organization); + } + // The retained entry never performs an administrator operation. + const retained = createNativeRetainedDataRequestCaller(configuration, transport); + for (const operation of [ + { kind: 'listDataRequests', limit: 20 }, + { kind: 'createDataExportForSubject', membershipId: id, idempotencyKey: 'k'.repeat(43) }, + ]) + expect( + await retained( + 'owned-token', + binding, + operation as unknown as RetainedDataRequestOperation, + signal(), + ), + ).toEqual({ kind: 'invalid-request' }); + expect(transport).toHaveBeenCalledTimes(2); + }); +}); diff --git a/frontend/apps/web/src/server/auth/native-data-request-http.test.ts b/frontend/apps/web/src/server/auth/native-data-request-http.test.ts new file mode 100644 index 000000000..6e0861c64 --- /dev/null +++ b/frontend/apps/web/src/server/auth/native-data-request-http.test.ts @@ -0,0 +1,936 @@ +// @vitest-environment node +import { execFileSync } from 'node:child_process'; +import type { IncomingMessage } from 'node:http'; +import { runInNewContext } from 'node:vm'; + +import type { OwnDataRequest } from '@learnstack/sdk/administration-server'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { DATA_REQUEST_HISTORY_SOURCE } from './data-request-html'; +import { DATA_REQUEST_REFUSALS, dataRequestRefusal } from './native-data-request-http'; +import type { NativeOperationResult } from './native-operation-contract'; +import { dataRequestProofView } from '../../../scripts/data-request-proof-view.mjs'; +import en from '../../i18n/messages/en/data.json'; +import tr from '../../i18n/messages/tr/data.json'; +import { + DownloadWire, + artifact, + chunkBytes, + closeDataRequestFixtures, + count, + fixture, + formKey, + id, + ok, + organization, + pageInfo, + refused, + request, + second, + shown, + ticket, +} from '../../test/data-request-person-fixture'; + +afterEach(closeDataRequestFixtures); + +describe('the person’s own data-request page in a live session', () => { + it('lists every closed state with its next step, dates and only the permitted actions', async () => { + const items: OwnDataRequest[] = [ + request({ id: '019a154b-0000-7000-8000-000000000001' }), + request({ + id: '019a154b-0000-7000-8000-000000000002', + status: 'completed', + completedAt: '2026-11-22T10:00:00Z', + updatedAt: '2026-11-22T10:00:00Z', + artifact: artifact({ + truncations: [{ collection: 'audit.entries', included: 5, total: 9 }], + }), + }), + request({ + id: '019a154b-0000-7000-8000-000000000003', + status: 'completed', + completedAt: '2026-11-01T10:00:00Z', + updatedAt: '2026-11-01T10:00:00Z', + artifact: artifact({ status: 'expired', readable: false }), + }), + request({ + id: '019a154b-0000-7000-8000-000000000004', + kind: 'erasure', + status: 'scheduled', + executeAt: '2026-11-24T10:00:00Z', + }), + request({ + id: '019a154b-0000-7000-8000-000000000005', + kind: 'erasure', + status: 'scheduled', + executeAt: '2026-11-23T11:00:00Z', + }), + request({ + id: '019a154b-0000-7000-8000-000000000006', + kind: 'erasure', + status: 'awaiting_privileged_step', + origin: 'administrator', + executeAt: '2026-11-20T10:00:00Z', + retained: [{ kind: 'consent_evidence', count: 2 }], + }), + request({ + id: '019a154b-0000-7000-8000-000000000007', + kind: 'erasure', + status: 'completed', + completedAt: '2026-11-21T10:00:00Z', + retained: [{ kind: 'audit_actor_reference', count: 12 }], + }), + request({ + id: '019a154b-0000-7000-8000-000000000008', + kind: 'erasure', + status: 'blocked', + lastRefusal: 'blocked_hold', + updatedAt: '2026-11-19T10:00:00Z', + }), + request({ + id: '019a154b-0000-7000-8000-000000000009', + status: 'failed', + failureReason: 'execution_failed', + updatedAt: '2026-11-18T10:00:00Z', + }), + request({ + id: '019a154b-0000-7000-8000-000000000010', + status: 'cancelled', + updatedAt: '2026-11-17T10:00:00Z', + }), + request({ + id: '019a154b-0000-7000-8000-000000000011', + kind: 'closure', + status: 'scheduled', + executeAt: '2026-11-23T11:00:00Z', + lastRefusal: 'blocked_last_administrator', + }), + request({ + id: '019a154b-0000-7000-8000-000000000012', + kind: 'erasure', + origin: 'closure_fanout', + status: 'fulfilling', + }), + ]; + const f = await fixture('session', items); + const wire = await f.run('GET', '/account/data'); + expect(wire.statusCode).toBe(200); + const html = wire.html; + expect(count(html, /

/g)).toBe(1); + expect(html).toContain('data-data-request-view="session"'); + for (const sentence of [ + en.next.export_requested, + en.next.export_ready, + en.next.export_gone, + en.next.erasure_scheduled, + en.next.erasure_due, + en.next.erasure_awaiting, + en.next.erasure_completed, + en.next.blocked, + en.blocked_reason.blocked_hold, + en.next.failed, + en.next.cancelled, + en.next.closure_scheduled, + en.next.erasure_fulfilling, + en.failure.execution_failed, + en.last_refusal.blocked_last_administrator, + en.list.by_administrator, + en.list.by_closure, + en.retained.partial, + en.retained.pending, + en.artifact.collection_audit_entries, + ]) + expect(html).toContain(shown(sentence)); + expect(html).toContain('Status: ' + en.status.due); + expect(html).toContain('Status: ' + en.status.awaiting_privileged_step); + // Cancellable: the requested export, the erasure still in its window, the scheduled closure. + expect(count(html, /action="\/api\/account\/data-requests\/cancel"/g)).toBe(3); + expect(count(html, /action="\/api\/account\/data-requests\/download"/g)).toBe(1); + expect(count(html, /action="\/api\/account\/data-requests\/revoke"/g)).toBe(1); + expect(html).toContain('name="version" value="9007199254740993"'); + // An active export, erasure and closure each hide their filing control. + expect(html).not.toContain('action="/api/account/data-requests/export"'); + expect(html).toContain(shown(en.export.active)); + expect(html).toContain(shown(en.erasure.active)); + expect(html).toContain(shown(en.closure.active)); + expect(html).not.toContain(' operation)).toEqual([ + { kind: 'listOwnDataRequests', limit: 20 }, + ]); + // The live session's own context selects the group; the page never names one. + expect(f.administration.mock.calls[0]![1]).toMatchObject({ tenantId: f.scope.tenantId }); + expect(f.requestRuntime.snapshotCounts()).toEqual({ active: 0, owners: 0, bytes: 0 }); + }); + + it('offers every filing on an empty page and serves Turkish for a Turkish browser', async () => { + const f = await fixture('session'); + const english = (await f.run('GET', '/account/data')).html; + expect(english).toContain(shown(en.list.empty)); + expect(english).toContain('action="/api/account/data-requests/export"'); + expect(english).toContain('href="/account/data?step=erasure"'); + expect(english).toContain('href="/account/data?step=closure"'); + const turkish = await f.run('GET', '/account/data', undefined, { + headers: { 'accept-language': 'tr-TR,tr;q=0.9' }, + }); + expect(turkish.html).toContain(' { + const f = await fixture('session'); + const key = formKey((await f.run('GET', '/account/data')).html); + const wire = await f.run('POST', '/api/account/data-requests/export', { + csrfToken: f.csrf, + idempotencyKey: key, + }); + expect(wire.statusCode).toBe(303); + expect(wire.headers.get('location')).toBe('/account/data?result=export'); + expect(f.own).toHaveBeenLastCalledWith({ kind: 'createOwnDataExport', idempotencyKey: key }); + const done = await f.run('GET', '/account/data?result=export'); + expect(done.html).toContain('
'); + expect(done.html).toContain('' + en.result.title + ' – ' + en.common.title); + }); + + it('renders the erasure and closure confirmations and refuses a filing without them', async () => { + const f = await fixture('session'); + const erasure = (await f.run('GET', '/account/data?step=erasure')).html; + expect(erasure).toContain('<fieldset><legend>' + en.erasure.legend + '</legend>'); + expect(erasure).toContain('name="confirm" value="erase" required'); + for (const text of [en.erasure.kept_uncounted, en.erasure.kept_partial, en.erasure.timing]) + expect(erasure).toContain(shown(text)); + const closure = (await f.run('GET', '/account/data?step=closure')).html; + for (const text of [ + en.closure.warning_everywhere, + en.closure.warning_email, + en.closure.warning_stops, + en.closure.warning_no_status, + ]) + expect(closure).toContain(shown(text)); + expect(count(closure, /type="checkbox"[^>]*required/g)).toBe(2); + const key = formKey(closure); + for (const [path, fields] of [ + ['/api/account/data-requests/erasure', {}], + ['/api/account/data-requests/erasure', { confirm: 'yes' }], + ['/api/account/data-requests/closure', { confirm: 'close' }], + ['/api/account/data-requests/closure', { acknowledge: 'no_status' }], + ] as const) { + const wire = await f.run('POST', path, { csrfToken: f.csrf, idempotencyKey: key, ...fields }); + expect(wire.statusCode).toBe(400); + expect(wire.html).toContain(shown(en.error.confirmation)); + } + expect(f.own).not.toHaveBeenCalledWith( + expect.objectContaining({ kind: 'createOwnDataErasure' }), + ); + const filed = await f.run('POST', '/api/account/data-requests/closure', { + csrfToken: f.csrf, + idempotencyKey: key, + confirm: 'close', + acknowledge: 'no_status', + }); + expect(filed.headers.get('location')).toBe('/account/data?result=closure'); + expect(f.own).toHaveBeenLastCalledWith({ + kind: 'createOwnAccountClosure', + idempotencyKey: key, + }); + }); + + it('refuses hostile forms before any operation', async () => { + const f = await fixture('session'); + const key = 'k'.repeat(43); + const valid = { csrfToken: f.csrf, idempotencyKey: key, requestId: id, version: '3' }; + const cases: [Record<string, string> | URLSearchParams, number, string?][] = [ + [{ ...valid, csrfToken: 'x'.repeat(43) }, 403], + [{ ...valid, requestId: 'not-a-uuid' }, 400], + [{ ...valid, requestId: '019a154b-0000-4000-8000-000000000041' }, 400], + [{ ...valid, version: '03' }, 400], + [{ ...valid, version: '9223372036854775808' }, 400], + [{ ...valid, idempotencyKey: 'short' }, 400], + [{ ...valid, group: 'tenant' }, 400], + [{ ...valid, tenantId: id }, 400], + [new URLSearchParams([...Object.entries(valid), ['requestId', second]]), 400], + ]; + for (const [form, status] of cases) + expect((await f.run('POST', '/api/account/data-requests/cancel', form)).statusCode).toBe( + status, + ); + expect( + ( + await f.run('POST', '/api/account/data-requests/cancel', valid, { + origin: 'https://evil.test', + }) + ).statusCode, + ).toBe(400); + expect((await f.run('GET', '/account/data?group=tenant')).statusCode).toBe(400); + expect((await f.run('GET', '/account/data?step=everything')).statusCode).toBe(400); + expect((await f.run('GET', '/account/data?result=export&result=export')).statusCode).toBe(400); + expect((await f.run('GET', '/api/account/data-requests/cancel')).statusCode).toBe(404); + expect(f.own).not.toHaveBeenCalled(); + const cancelled = await f.run('POST', '/api/account/data-requests/cancel', valid); + expect(cancelled.headers.get('location')).toBe('/account/data?result=cancelled'); + expect(f.own).toHaveBeenCalledExactlyOnceWith({ + kind: 'cancelOwnDataRequest', + id, + version: '3', + idempotencyKey: key, + }); + }); + + it('maps every refusal to one plain sentence and keeps an unknown reason generic', async () => { + const f = await fixture('session'); + const form = { csrfToken: f.csrf, idempotencyKey: 'k'.repeat(43) }; + for (const [reason, key] of Object.entries(DATA_REQUEST_REFUSALS)) { + f.own.mockReturnValueOnce(refused(409, 'business_rule_violation', { $: [{ key: reason }] })); + const wire = await f.run('POST', '/api/account/data-requests/export', form); + expect(wire.statusCode).toBe(409); + const [group, name] = key.split('.') as ['refusal', keyof typeof en.refusal]; + expect(group).toBe('refusal'); + expect(wire.html).toContain(shown(en.refusal[name])); + expect(wire.html).toContain('role="alert"'); + expect(wire.html).not.toContain(reason); + } + f.own.mockReturnValueOnce( + refused(409, 'business_rule_violation', { $: [{ key: 'lockey_future_reason' }] }), + ); + expect((await f.run('POST', '/api/account/data-requests/export', form)).html).toContain( + en.error.conflict, + ); + f.own.mockReturnValueOnce({ kind: 'transport-error' }); + const unknown = await f.run('POST', '/api/account/data-requests/export', form); + expect(unknown.statusCode).toBe(503); + expect(unknown.html).toContain(shown(en.error.unconfirmed)); + }); + + it('seals the API continuation to the owner and refuses a forged one before any read', async () => { + const f = await fixture('session'); + f.own.mockReturnValueOnce( + ok({ items: [], pageInfo: { ...pageInfo, nextCursor: 'raw-api-cursor', hasNext: true } }), + ); + const html = (await f.run('GET', '/account/data')).html; + const next = /href="\/account\/data\?cursor=([A-Za-z0-9_-]+)"/.exec(html)![1]!; + expect(html).not.toContain('raw-api-cursor'); + await f.run('GET', '/account/data?cursor=' + next); + expect(f.own).toHaveBeenLastCalledWith({ + kind: 'listOwnDataRequests', + limit: 20, + cursor: 'raw-api-cursor', + }); + f.own.mockClear(); + // One bit of the first ciphertext byte (after the version and the 12-byte nonce) flipped: never the genuine + // value, whatever the random nonce and tag are. + const bytes = Buffer.from(next, 'base64url'); + bytes[13] = bytes[13]! ^ 1; + const forged = bytes.toString('base64url'); + expect(forged).not.toBe(next); + expect((await f.run('GET', '/account/data?cursor=' + forged)).statusCode).toBe(400); + expect(f.own).not.toHaveBeenCalled(); + }); + + it('keeps HEAD and prefetch passive, refuses a bearer and shows sign-in without an owner', async () => { + const f = await fixture('session'); + expect((await f.run('HEAD', '/account/data')).chunks).toEqual([]); + expect( + (await f.run('GET', '/account/data', undefined, { headers: { 'sec-purpose': 'prefetch' } })) + .html, + ).toBe(''); + expect( + (await f.run('GET', '/account/data', undefined, { headers: { authorization: 'Bearer x' } })) + .statusCode, + ).toBe(400); + expect(f.own).not.toHaveBeenCalled(); + const anonymous = await f.run('GET', '/account/data', undefined, { + headers: { cookie: '' }, + }); + expect(anonymous.statusCode).toBe(200); + expect(anonymous.html).toContain('href="/api/auth/signin"'); + const anonymousPost = await f.run( + 'POST', + '/api/account/data-requests/export', + { csrfToken: f.csrf, idempotencyKey: 'k'.repeat(43) }, + { headers: { cookie: '' } }, + ); + expect(anonymousPost.statusCode).toBe(401); + expect(f.own).not.toHaveBeenCalled(); + }); +}); + +describe('the retained own-scope entry', () => { + it('lists the retained groups, views one by POST and files there without a live session', async () => { + const f = await fixture('entry', [request()]); + const chooser = await f.run('GET', '/account/data'); + expect(chooser.html).toContain('data-data-request-view="entry_scopes"'); + expect(count(chooser.html, /action="\/api\/auth\/entry\/data-requests"/g)).toBe(2); + expect(chooser.html).toContain(shown(en.scope.entry_tenant)); + expect(chooser.html).toContain(en.scope.entry_organization + ' 1'); + expect(chooser.html).toContain(shown(en.scope.entry_names)); + const view = await f.run('POST', '/api/auth/entry/data-requests', { + csrfToken: f.csrf, + group: organization, + }); + expect(view.statusCode).toBe(200); + expect(view.html).toContain('data-data-request-view="entry"'); + expect(view.html).toContain('name="group" value="' + organization + '"'); + expect(view.html).toContain('action="/api/auth/entry/data-requests/cancel"'); + const filed = await f.run('POST', '/api/auth/entry/data-requests/erasure', { + csrfToken: f.csrf, + idempotencyKey: 'k'.repeat(43), + group: 'tenant', + confirm: 'erase', + }); + expect(filed.headers.get('location')).toBe('/account/data?group=tenant&result=erasure'); + expect(f.retained.mock.calls.map(([, , operation]) => operation)).toEqual([ + { kind: 'listRetainedDataRequestScopes', limit: 20 }, + { kind: 'listRetainedDataRequests', group: organization, limit: 20 }, + { kind: 'createRetainedDataErasure', group: 'tenant', idempotencyKey: 'k'.repeat(43) }, + ]); + // The retained path never performs a scoped live-session operation. + expect(f.administration).not.toHaveBeenCalled(); + expect(f.native.self).not.toHaveBeenCalled(); + }); + + it('states when the entry ends, restores the same group and leads a refused confirmation to the chooser', async () => { + const f = await fixture('entry', [request()]); + const ends = f.entry!.finished.entry.expiresAt; + const chooser = await f.run('GET', '/account/data'); + const view = await f.run('POST', '/api/auth/entry/data-requests', { + csrfToken: f.csrf, + group: organization, + }); + // The page states the very bound its response is pinned to: the entry's own expiry. + for (const html of [chooser.html, view.html]) + expect(html).toContain( + '<dt>' + + en.scope.entry_time_until + + '</dt><dd><time datetime="' + + new Date(ends).toISOString(), + ); + expect(chooser.html).toContain("history.replaceState(null,'','/account/data')"); + expect(view.html).toContain( + "history.replaceState(null,'','/account/data?group=" + organization + "')", + ); + const refused = await f.run('POST', '/api/auth/entry/data-requests/erasure', { + csrfToken: f.csrf, + idempotencyKey: 'k'.repeat(43), + group: organization, + }); + expect(refused.statusCode).toBe(400); + // A retained step needs its group, and a refusal never repeats a submitted one: the way back is the chooser. + expect([...refused.html.matchAll(/class="action" href="([^"]*)"/g)].map((m) => m[1])).toEqual([ + '/account/data', + '/api/auth/entry', + ]); + expect(refused.html).not.toContain('group='); + expect(f.retained).not.toHaveBeenCalledWith( + expect.anything(), + expect.anything(), + expect.objectContaining({ kind: 'createRetainedDataErasure' }), + expect.anything(), + ); + }); + + it('states the entry’s end once per page and warns beside the download and the confirmation', async () => { + const ready = request({ + status: 'completed', + completedAt: '2026-11-23T11:00:00Z', + artifact: artifact(), + }); + const f = await fixture('entry', [ready]); + const ends = f.entry!.finished.entry.expiresAt; + const instant = '<time datetime="' + new Date(ends).toISOString() + '">'; + const times = (html: string) => html.split(instant).length - 1; + const list = (await f.run('GET', '/account/data?group=tenant')).html; + const download = list.indexOf('action="/api/auth/entry/data-requests/download"'); + expect(download).toBeGreaterThan(0); + const form = list.slice(download, list.indexOf('</form>', download)); + // The page-level notice states when, above; the download form says what that means for a download. + expect(times(list)).toBe(1); + expect(list.indexOf(instant)).toBeLessThan(download); + expect(form).toContain(shown(en.entry.download_deadline)); + expect(form).not.toContain('<time'); + for (const step of ['erasure', 'closure']) { + const html = (await f.run('GET', '/account/data?group=tenant&step=' + step)).html; + const action = html.indexOf('action="/api/auth/entry/data-requests/' + step + '"'); + expect(times(html)).toBe(1); + expect(html.indexOf(instant)).toBeLessThan(html.indexOf(shown(en.entry.step_deadline))); + expect(html.indexOf(shown(en.entry.step_deadline))).toBeLessThan(action); + } + const chooser = (await f.run('GET', '/account/data')).html; + expect(times(chooser)).toBe(1); + expect(chooser).not.toContain(shown(en.entry.download_deadline)); + expect(chooser).not.toContain(shown(en.entry.step_deadline)); + const session = await fixture('session', [ready]); + for (const target of ['/account/data', '/account/data?step=erasure']) { + const html = (await session.run('GET', target)).html; + expect(html).not.toContain(shown(en.scope.entry_time_until)); + expect(html).not.toContain(shown(en.entry.download_deadline)); + expect(html).not.toContain(shown(en.entry.step_deadline)); + } + }); + + it('links a refusal back by the owner’s mode, never by the submitted group', async () => { + const f = await fixture('entry'); + f.retained.mockImplementationOnce(async () => refused(404, 'not_found')); + const refusedList = await f.run('GET', '/account/data?group=' + organization); + expect(refusedList.statusCode).toBe(404); + const links = (html: string) => + [...html.matchAll(/class="action" href="([^"]*)"/g)].map((m) => m[1]); + expect(links(refusedList.html)).toEqual(['/account/data', '/api/auth/entry']); + f.retained.mockImplementationOnce(async () => + refused(409, 'business_rule_violation', { $: [{ key: 'lockey_request_already_active' }] }), + ); + const refusedFiling = await f.run('POST', '/api/auth/entry/data-requests/export', { + csrfToken: f.csrf, + idempotencyKey: 'k'.repeat(43), + group: organization, + }); + expect(refusedFiling.statusCode).toBe(409); + expect(links(refusedFiling.html)).toEqual(['/account/data', '/api/auth/entry']); + const session = await fixture('session'); + session.own.mockReturnValueOnce(refused(409, 'business_rule_violation')); + const refusedOwn = await session.run('POST', '/api/account/data-requests/export', { + csrfToken: session.csrf, + idempotencyKey: 'k'.repeat(43), + }); + expect(links(refusedOwn.html)).toEqual(['/account/data', '/portal']); + // A refused session confirmation returns to its own step; that address names no group. + const refusedStep = await session.run('POST', '/api/account/data-requests/closure', { + csrfToken: session.csrf, + idempotencyKey: 'k'.repeat(43), + confirm: 'close', + }); + expect(refusedStep.statusCode).toBe(400); + expect(links(refusedStep.html)).toEqual(['/account/data?step=closure', '/portal']); + // Refused before any owner is chosen: only the fixed page. + const unread = await session.run('GET', '/account/data?result=export&result=export'); + expect(unread.statusCode).toBe(400); + expect(links(unread.html)).toEqual(['/account/data']); + }); + + it('refuses an invalid group, a session-only route and a missing CSRF proof', async () => { + const f = await fixture('entry'); + for (const [form, status] of [ + [{ csrfToken: f.csrf, group: 'Tenant' }, 400], + [{ csrfToken: f.csrf }, 400], + [{ csrfToken: 'x'.repeat(43), group: 'tenant' }, 403], + ] as const) + expect((await f.run('POST', '/api/auth/entry/data-requests', form)).statusCode).toBe(status); + // The entry owner is not a live session: the session's routes refuse it as signed out. + expect( + ( + await f.run('POST', '/api/account/data-requests/export', { + csrfToken: f.csrf, + idempotencyKey: 'k'.repeat(43), + }) + ).statusCode, + ).toBe(401); + expect((await f.run('GET', '/account/data?step=erasure')).statusCode).toBe(400); + expect(f.retained).not.toHaveBeenCalled(); + }); +}); + +/** Every console method and the error stream: a ticket, an identifier or a byte of the file must reach none. */ +const watchOutput = () => [ + ...(['log', 'info', 'warn', 'error', 'debug'] as const).map((name) => vi.spyOn(console, name)), + vi.spyOn(process.stderr, 'write'), +]; + +describe('the export download relay', () => { + it('streams the chunks in order as one no-store attachment and never shows the ticket', async () => { + const f = await fixture('session'); + const output = watchOutput(); + const wire = new DownloadWire(); + await f.run( + 'POST', + '/api/account/data-requests/download', + { csrfToken: f.csrf, requestId: id }, + { wire }, + ); + expect(wire.statusCode).toBe(200); + expect(Object.fromEntries(wire.headers)).toMatchObject({ + 'content-type': 'application/json; charset=utf-8', + 'content-disposition': 'attachment; filename="data-export.json"', + 'content-length': '131073', + 'cache-control': 'no-store', + 'x-content-type-options': 'nosniff', + }); + const body = Buffer.concat(wire.bytes); + expect(body.equals(Buffer.concat([chunkBytes(0), chunkBytes(1)]))).toBe(true); + expect(wire.destroyed).toBe(false); + expect(wire.writableEnded).toBe(true); + expect(JSON.stringify([...wire.headers])).not.toContain(ticket); + expect(f.own.mock.calls.map(([operation]) => operation.kind)).toEqual([ + 'mintOwnDataExportTicket', + 'readOwnDataExportChunk', + 'readOwnDataExportChunk', + ]); + for (const spy of output) expect(spy).not.toHaveBeenCalled(); + }); + + it('destroys the connection on a failed chunk after the headers, with no completed body', async () => { + const f = await fixture('session'); + const output = watchOutput(); + f.own.mockImplementation((operation) => + operation.kind === 'mintOwnDataExportTicket' + ? ok({ ticket, expiresAt: '2026-11-23T12:15:00Z', chunkCount: 2, byteCount: 131073 }) + : operation.kind === 'readOwnDataExportChunk' && operation.index === 0 + ? ok({ index: 0, count: 2, bytes: chunkBytes(0).toString('base64') }) + : { kind: 'transport-error' }, + ); + const wire = await f.run( + 'POST', + '/api/account/data-requests/download', + { csrfToken: f.csrf, requestId: id }, + { wire: new DownloadWire() }, + ); + expect(wire.headersSent).toBe(true); + expect(wire.destroyed).toBe(true); + expect(wire.writableEnded).toBe(false); + // A failure leaves no trace either: no ticket, identifier or byte of the file in any output. + for (const spy of output) expect(spy).not.toHaveBeenCalled(); + }); + + it('answers the ticket limit and a gone file with their sentences before any byte', async () => { + const f = await fixture('session'); + for (const [reason, sentence] of [ + ['lockey_data_export_ticket_limit', en.refusal.data_export_ticket_limit], + ['lockey_data_export_unavailable', en.refusal.data_export_unavailable], + ] as const) { + f.own.mockReturnValueOnce( + refused(409, 'business_rule_violation', { artifact: [{ key: reason }] }), + ); + const wire = await f.run('POST', '/api/account/data-requests/download', { + csrfToken: f.csrf, + requestId: id, + }); + expect(wire.statusCode).toBe(409); + expect(wire.headers.get('content-type')).toBe('text/html; charset=utf-8'); + expect(wire.html).toContain(sentence); + } + }); + + /** A three-chunk bundle, so a failure after the second chunk still leaves a read to refuse. */ + const threeChunks = (f: Awaited<ReturnType<typeof fixture>>, during: (index: number) => void) => + f.own.mockImplementation((operation) => { + if (operation.kind === 'mintOwnDataExportTicket') + return ok({ ticket, expiresAt: '2026-11-23T12:15:00Z', chunkCount: 3, byteCount: 262145 }); + if (operation.kind !== 'readOwnDataExportChunk') return ok({ version: '4' }); + during(operation.index); + return ok({ + index: operation.index, + count: 3, + bytes: Buffer.alloc(operation.index < 2 ? 131072 : 1, 0x61).toString('base64'), + }); + }); + + it('destroys a streaming download when the owner signs out between chunks', async () => { + const f = await fixture('session'); + const owner = f.session!; + threeChunks(f, (index) => { + if (index === 1) f.store.signout(owner.binding, f.csrf); + }); + const wire = new DownloadWire(); + await f.run( + 'POST', + '/api/account/data-requests/download', + { csrfToken: f.csrf, requestId: id }, + { wire }, + ); + expect(wire.statusCode).toBe(200); + expect(wire.destroyed).toBe(true); + expect(wire.writableEnded).toBe(false); + // The answer to a read the owner signed out during is not relayed, and no further read is made. + expect(Buffer.concat(wire.bytes).length).toBe(131072); + expect( + f.own.mock.calls.filter(([operation]) => operation.kind === 'readOwnDataExportChunk'), + ).toHaveLength(2); + }); + + it('destroys a streaming download when the browser goes away between chunks', async () => { + const f = await fixture('session'); + let incoming: IncomingMessage | undefined; + threeChunks(f, (index) => { + if (index === 1) { + incoming!.aborted = true; + incoming!.emit('aborted'); + } + }); + const wire = new DownloadWire(); + await f.run( + 'POST', + '/api/account/data-requests/download', + { csrfToken: f.csrf, requestId: id }, + { + wire, + request: (value) => { + incoming = value; + }, + }, + ); + expect(wire.headersSent).toBe(true); + expect(wire.destroyed).toBe(true); + expect(wire.writableEnded).toBe(false); + expect(Buffer.concat(wire.bytes).length).toBe(131072); + expect(f.requestRuntime.snapshotCounts()).toEqual({ active: 0, owners: 0, bytes: 0 }); + }); + + it('answers a first chunk the API admits too late with the busy refusal, never an attachment', async () => { + const f = await fixture('session'); + f.own.mockImplementation((operation) => + operation.kind === 'mintOwnDataExportTicket' + ? ok({ ticket, expiresAt: '2026-11-23T12:15:00Z', chunkCount: 2, byteCount: 131073 }) + : ({ + ...refused(429, 'rate_limited'), + error: { code: 'rate_limited', retryAfter: 60 }, + } as NativeOperationResult), + ); + const wire = await f.run('POST', '/api/account/data-requests/download', { + csrfToken: f.csrf, + requestId: id, + }); + expect(wire.statusCode).toBe(429); + expect(wire.headers.get('retry-after')).toBe('60'); + expect(wire.headers.get('content-type')).toBe('text/html; charset=utf-8'); + expect(wire.headers.has('content-disposition')).toBe(false); + expect(wire.html).toContain(shown(en.error.busy)); + expect(wire.html).not.toContain(ticket); + expect(f.own.mock.calls.map(([operation]) => operation.kind)).toEqual([ + 'mintOwnDataExportTicket', + 'readOwnDataExportChunk', + ]); + }); + + it('takes no pause the retained entry cannot outlast: the person is told to wait instead', async () => { + const f = await fixture('entry'); + f.retained.mockImplementation(async (_token, _binding, operation) => + operation.kind === 'mintRetainedDataExportTicket' + ? ok({ ticket, expiresAt: '2026-11-23T12:15:00Z', chunkCount: 2, byteCount: 131073 }) + : ({ + ...refused(429, 'rate_limited'), + error: { code: 'rate_limited', retryAfter: 20 }, + } as NativeOperationResult), + ); + // Ten seconds of the entry remain: a twenty-second pause would outlive the response's owner. + f.advance(290_000); + const wire = await f.run('POST', '/api/auth/entry/data-requests/download', { + csrfToken: f.csrf, + requestId: id, + group: 'tenant', + }); + expect(wire.statusCode).toBe(429); + expect(wire.headers.has('content-disposition')).toBe(false); + expect(f.retained.mock.calls.map(([, , operation]) => operation.kind)).toEqual([ + 'mintRetainedDataExportTicket', + 'readRetainedDataExportChunk', + ]); + }); + + it('downloads through the retained chunks for an entry owner', async () => { + const f = await fixture('entry'); + const wire = new DownloadWire(); + await f.run( + 'POST', + '/api/auth/entry/data-requests/download', + { csrfToken: f.csrf, requestId: id, group: 'tenant' }, + { wire }, + ); + expect(Buffer.concat(wire.bytes).length).toBe(131073); + expect(f.retained.mock.calls.map(([, , operation]) => operation)).toEqual([ + { kind: 'mintRetainedDataExportTicket', group: 'tenant', id }, + { kind: 'readRetainedDataExportChunk', group: 'tenant', id, ticket, index: 0 }, + { kind: 'readRetainedDataExportChunk', group: 'tenant', id, ticket, index: 1 }, + ]); + }); +}); + +describe('refusal mapping', () => { + it('keeps statuses and the generic envelope closed', () => { + expect(dataRequestRefusal(refused(404, 'not_found'), true)).toMatchObject({ + status: 404, + message: 'error.not_found', + }); + expect(dataRequestRefusal(refused(401, 'unauthorized'), false).message).toBe( + 'error.unauthorized', + ); + expect(dataRequestRefusal(refused(403, 'forbidden'), false).message).toBe('error.forbidden'); + expect(dataRequestRefusal(refused(429, 'rate_limited'), false)).toMatchObject({ + message: 'error.busy', + retryAfter: 30, + }); + expect(dataRequestRefusal(refused(503, 'dependency_unavailable'), true)).toMatchObject({ + message: 'error.unavailable', + retryAfter: 30, + }); + expect(dataRequestRefusal(refused(500, 'unknown'), true).message).toBe('error.unconfirmed'); + expect(dataRequestRefusal(refused(409, 'concurrency_conflict'), true).message).toBe( + 'error.stale', + ); + expect(dataRequestRefusal(refused(409, 'request_in_progress'), true).message).toBe( + 'error.in_progress', + ); + expect(dataRequestRefusal(refused(409, 'idempotency_key_reuse'), true).message).toBe( + 'error.key_reuse', + ); + expect(dataRequestRefusal(refused(409, 'idempotency_outcome_unavailable'), true).message).toBe( + 'error.outcome_unavailable', + ); + expect(dataRequestRefusal({ kind: 'invalid-request' }, true).status).toBe(400); + expect(dataRequestRefusal({ kind: 'cancelled' }, false).message).toBe('error.unavailable'); + }); +}); + +describe('data-request private history guard', () => { + const install = () => { + const listeners = new Map<string, (event?: { persisted?: boolean }) => void>(); + const style = { visibility: '' }; + const replace = vi.fn(); + const reload = vi.fn(); + const replaceState = vi.fn(); + runInNewContext(DATA_REQUEST_HISTORY_SOURCE, { + addEventListener: (name: string, callback: (event?: { persisted?: boolean }) => void) => + listeners.set(name, callback), + document: { documentElement: { style } }, + history: { replaceState }, + location: { replace, reload }, + }); + return { listeners, style, replace, reload, replaceState }; + }; + it.each([false, true])( + 'veils a departing page and restores by a fixed GET (persisted=%s)', + (persisted) => { + const page = install(); + expect(page.replaceState).toHaveBeenCalledExactlyOnceWith(null, '', '/account/data'); + page.listeners.get('pagehide')!(); + expect(page.style.visibility).toBe('hidden'); + page.listeners.get('pageshow')!({ persisted }); + expect(page.replace).toHaveBeenCalledExactlyOnceWith('/account/data'); + expect(page.reload).not.toHaveBeenCalled(); + }, + ); + it('permits only the request nonce and installs the guard before private markup', async () => { + const f = await fixture('session'); + const response = await f.run('GET', '/account/data'); + const nonce = /<script nonce="([A-Za-z0-9+/]{22}==)">/.exec(response.html)?.[1]; + expect(nonce).toBeDefined(); + expect(response.headers.get('content-security-policy')).toContain( + "script-src 'nonce-" + nonce + "'", + ); + expect(response.headers.get('cache-control')).toBe('no-store'); + expect(response.html.indexOf(DATA_REQUEST_HISTORY_SOURCE)).toBeLessThan( + response.html.indexOf('<body>'), + ); + }); +}); + +describe('the closed observation controls read the documents the handler really serves', () => { + const items = [ + request({ + id: '019a154b-0000-7000-8000-000000000002', + status: 'completed', + completedAt: '2026-11-22T10:00:00Z', + artifact: artifact(), + }), + request({ + id: '019a154b-0000-7000-8000-000000000004', + kind: 'erasure', + status: 'scheduled', + executeAt: '2026-11-24T10:00:00Z', + }), + ]; + const observe = async ( + f: Awaited<ReturnType<typeof fixture>>, + target: string, + policy?: string, + ) => { + const wire = await f.run('GET', target); + expect(wire.statusCode, target).toBe(200); + return dataRequestProofView( + wire.html, + policy ?? String(wire.headers.get('content-security-policy')), + ); + }; + const base = { kind: 'data_request_document', confirmationProtected: true } as const; + + it('observes the session page and both confirmation steps with the real CSP header', async () => { + const f = await fixture('session', items); + expect(await observe(f, '/account/data')).toEqual({ + ...base, + view: 'session', + // The export filing, the revocation and the cancellation; one download. + filingForms: 1, + actionForms: 2, + downloadForms: 1, + historyProtected: true, + }); + const idle = await fixture('session'); + expect(await observe(idle, '/account/data?step=erasure')).toEqual({ + ...base, + view: 'session_erasure', + // The one confirmation form, with its fieldset and its required box. + filingForms: 1, + actionForms: 0, + downloadForms: 0, + historyProtected: true, + }); + expect(await observe(idle, '/account/data?step=closure')).toMatchObject({ + view: 'session_closure', + confirmationProtected: true, + historyProtected: true, + }); + // The observation is of the header the page was really served with: another policy is not a protected history. + expect((await observe(f, '/account/data', "script-src 'self'")).historyProtected).toBe(false); + }); + + it('observes the retained chooser, a group and its confirmation steps', async () => { + const f = await fixture('entry', items); + expect(await observe(f, '/account/data')).toEqual({ + ...base, + view: 'entry_scopes', + filingForms: 0, + actionForms: 2, + downloadForms: 0, + historyProtected: true, + }); + expect(await observe(f, '/account/data?group=' + organization)).toEqual({ + ...base, + view: 'entry', + filingForms: 1, + actionForms: 2, + downloadForms: 1, + historyProtected: true, + }); + const idle = await fixture('entry'); + for (const [step, view] of [ + ['erasure', 'entry_erasure'], + ['closure', 'entry_closure'], + ] as const) + expect(await observe(idle, '/account/data?group=tenant&step=' + step)).toMatchObject({ + view, + confirmationProtected: true, + historyProtected: true, + }); + }); +}); + +it('executes all independent closed native data-request HTML observation controls', () => { + const script = new URL('../../../scripts/test-data-request-proof-view.mjs', import.meta.url); + const output = execFileSync(process.execPath, ['--test', script.pathname], { + encoding: 'utf8', + timeout: 10_000, + maxBuffer: 65536, + env: { + PATH: process.env.PATH, + NODE_ENV: 'production', + NODE_TLS_REJECT_UNAUTHORIZED: '1', + NEXT_TELEMETRY_DISABLED: '1', + }, + }); + for (const [field, value] of [ + ['tests', 4], + ['pass', 4], + ['fail', 0], + ['cancelled', 0], + ['skipped', 0], + ['todo', 0], + ] as const) + expect(output).toMatch(new RegExp('^# ' + field + ' ' + value + '$', 'm')); +}); diff --git a/frontend/apps/web/src/server/auth/native-data-request-http.ts b/frontend/apps/web/src/server/auth/native-data-request-http.ts new file mode 100644 index 000000000..5c2d6f6eb --- /dev/null +++ b/frontend/apps/web/src/server/auth/native-data-request-http.ts @@ -0,0 +1,625 @@ +import { randomBytes } from 'node:crypto'; +import type { IncomingMessage, ServerResponse } from 'node:http'; +import { Readable } from 'node:stream'; + +import type { + OwnDataRequestPage, + RetainedDataRequestScopePage, +} from '@learnstack/sdk/administration-server'; + +import type { IngressContext } from '../ingress.js'; +import type { NativeDataRequestResponseLease } from './consent-response-contract.js'; +import { BFF_COOKIES, bffCookies } from './cookies.js'; +import { relayDataExport } from './data-export-download.js'; +import type { DataExportSink } from './data-export-download.js'; +import { prepareDataRequestCatalogues } from './data-request-copy.js'; +import type { DataRequestCatalogues, DataRequestKey } from './data-request-copy.js'; +import { renderDataRequestDocument } from './data-request-html.js'; +import type { DataRequestDocument } from './data-request-html.js'; +import { bffForm, bffQuery, exactBffOrigin } from './http-input.js'; +import type { BffHttpRequest } from './http-input.js'; +import { DATA_REQUEST_DOCUMENT_PATHS } from './http-paths.js'; +import { BffInputError } from './input-error.js'; +import type { + NativeOperationResult, + OwnDataRequestOperation, + RetainedDataRequestOperation, +} from './native-operation-contract.js'; +import type { DataRequestResult, NativeDataRequestSnapshot } from './page-contract.js'; +import { SnapshotAdmissionError } from './page-snapshot-pool.js'; +import type { BffSessionStore, SessionBinding } from './session-contract.js'; +import { BffSessionError } from './session-contract.js'; +import { bffSecretEquals } from './session-store.js'; + +export function nativeDataRequestTarget(target: string): boolean { + return DATA_REQUEST_DOCUMENT_PATHS.includes(target.split('?', 1)[0]!); +} + +/** + * The person's refusal sentences, one for every `errors.*` reason the data-request API emits on the person's + * routes (ADR-0106 § 7, ADR-0107 §§ 4 and 7). A reason missing here falls back to `error.conflict`; the catalogue + * test fails when the API documents or emits a reason this map lacks. + */ +export const DATA_REQUEST_REFUSALS: Readonly<Record<string, DataRequestKey>> = Object.freeze({ + lockey_request_already_active: 'refusal.request_already_active', + lockey_blocked_hold: 'refusal.blocked_hold', + lockey_blocked_last_administrator: 'refusal.blocked_last_administrator', + lockey_subject_export_available: 'refusal.subject_export_available', + lockey_subject_membership_current: 'refusal.subject_membership_current', + lockey_data_export_unavailable: 'refusal.data_export_unavailable', + lockey_data_request_window_ended: 'refusal.data_request_window_ended', + lockey_data_request_not_cancellable: 'refusal.data_request_not_cancellable', + lockey_subject_is_requester: 'refusal.subject_is_requester', + lockey_snapshot_too_large: 'refusal.snapshot_too_large', + lockey_data_export_ticket_limit: 'refusal.data_export_ticket_limit', + lockey_subject_not_admitted: 'refusal.subject_not_admitted', +}); +const RESULTS = new Set<DataRequestResult>([ + 'export', + 'erasure', + 'closure', + 'cancelled', + 'revoked', +]); +const uuid = (value: string | null): value is string => + value !== null && + /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value); +const groupValue = (value: string | null): value is string => value === 'tenant' || uuid(value); +const opaque = (value: string | null): value is string => + value !== null && /^[A-Za-z0-9_-]{43}$/.test(value); +const sealed = (value: string | null): value is string => + value !== null && value.length <= 1024 && /^[A-Za-z0-9_-]+$/.test(value); +const versionValue = (value: string | null): value is string => + value !== null && + /^(0|[1-9][0-9]{0,18})$/.test(value) && + (value.length < 19 || value <= '9223372036854775807'); + +type Action = 'view' | 'export' | 'erasure' | 'closure' | 'cancel' | 'revoke' | 'download'; +const ACTION_FIELDS: Readonly<Record<Action, readonly string[]>> = { + view: ['csrfToken', 'group'], + export: ['csrfToken', 'idempotencyKey', 'group'], + erasure: ['csrfToken', 'idempotencyKey', 'group', 'confirm'], + closure: ['csrfToken', 'idempotencyKey', 'group', 'confirm', 'acknowledge'], + cancel: ['csrfToken', 'idempotencyKey', 'group', 'requestId', 'version'], + revoke: ['csrfToken', 'idempotencyKey', 'group', 'requestId', 'version'], + download: ['csrfToken', 'group', 'requestId'], +}; +/** The fixed actions and their mode; nothing else reaches an operation. */ +function route(path: string): Readonly<{ mode: 'session' | 'entry'; action: Action }> | null { + if (path === '/api/auth/entry/data-requests') return { mode: 'entry', action: 'view' }; + for (const [prefix, mode] of [ + ['/api/auth/entry/data-requests/', 'entry'], + ['/api/account/data-requests/', 'session'], + ] as const) { + const action = path.startsWith(prefix) ? path.slice(prefix.length) : null; + if ( + action !== null && + ['export', 'erasure', 'closure', 'cancel', 'revoke', 'download'].includes(action) + ) + return { mode, action: action as Action }; + } + return null; +} + +/** One API outcome to the closed status and sentence a person sees; no API text is ever shown. */ +export function dataRequestRefusal( + result: NativeOperationResult | null, + mutation: boolean, +): Readonly<{ status: number; message: DataRequestKey; retryAfter: number | null }> { + if (!result || result.kind !== 'api-error') { + if (result?.kind === 'invalid-request') + return { status: 400, message: 'error.input', retryAfter: null }; + return { + status: 503, + message: mutation ? 'error.unconfirmed' : 'error.unavailable', + retryAfter: 30, + }; + } + const status = result.status >= 400 && result.status <= 599 ? result.status : 503; + const hint = + 'retryAfter' in result.error && typeof result.error.retryAfter === 'number' + ? Math.min(result.error.retryAfter, 3600) + : null; + if (status === 409) { + const code = result.problem.code; + if (code === 'concurrency_conflict') + return { status, message: 'error.stale', retryAfter: null }; + if (code === 'request_in_progress') + return { status, message: 'error.in_progress', retryAfter: null }; + if (code === 'idempotency_key_reuse') + return { status, message: 'error.key_reuse', retryAfter: null }; + if (code === 'idempotency_outcome_unavailable') + return { status, message: 'error.outcome_unavailable', retryAfter: null }; + const reasons = [ + ...(result.problem.errors?.['$'] ?? []), + ...(result.problem.errors?.['artifact'] ?? []), + ]; + const known = reasons + .map((reason) => DATA_REQUEST_REFUSALS[reason.key]) + .find((key) => key !== undefined); + return { status, message: known ?? 'error.conflict', retryAfter: null }; + } + const message: DataRequestKey = + status === 400 + ? 'error.input' + : status === 401 + ? 'error.unauthorized' + : status === 403 + ? 'error.forbidden' + : status === 404 + ? 'error.not_found' + : status === 429 + ? 'error.busy' + : status >= 500 + ? mutation && status !== 503 + ? 'error.unconfirmed' + : 'error.unavailable' + : 'error.conflict'; + return { + status, + message, + retryAfter: status === 429 || status === 503 ? (hint ?? 30) : null, + }; +} + +/** + * The person's own data-request document and its fixed native actions (ADR-0106 §§ 9–11, ADR-0107 §§ 4, 6, 7). + * Like the consent entry it needs no public-site bootstrap; unlike it, a live session's owner also serves it, for + * the session's own group. The browser chooses no tenant, organization, credential or owner. + */ +export function createNativeDataRequestHandler( + input: Readonly<{ + store: BffSessionStore; + catalogues: DataRequestCatalogues; + responseLease: (binding: IngressContext) => NativeDataRequestResponseLease; + /** Wall clock for "due" and the download deadline; tests inject one, production uses Date.now. */ + now?: () => number; + }>, +) { + const select = prepareDataRequestCatalogues(input.catalogues); + const now = input.now ?? Date.now; + return async ( + binding: IngressContext, + request: IncomingMessage, + response: ServerResponse, + ): Promise<void> => { + const nonce = randomBytes(16).toString('base64'); + const headers = new Headers(); + for (const [name, value] of Object.entries(request.headers)) + if (value !== undefined) headers.set(name, Array.isArray(value) ? value.join(',') : value); + const { locale, phrase } = select(headers.get('accept-language')); + let lease: NativeDataRequestResponseLease | undefined; + let published = false; + const write = ( + status: number, + body = '', + location?: string, + retryAfter: number | null = null, + ) => { + if (lease && !published) { + lease.publish({ kind: 'data_request_result', status }); + published = true; + } + if (Buffer.byteLength(body) > 256 * 1024) throw new BffSessionError('response'); + response.writeHead(status, { + 'content-type': 'text/html; charset=utf-8', + 'cache-control': 'no-store', + 'referrer-policy': 'same-origin', + 'x-content-type-options': 'nosniff', + 'x-frame-options': 'DENY', + 'content-security-policy': + "default-src 'none'; script-src 'nonce-" + + nonce + + "'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'", + ...(retryAfter !== null ? { 'retry-after': String(retryAfter) } : {}), + ...(location ? { location } : {}), + }); + response.end(binding.method === 'HEAD' ? undefined : body); + }; + const render = (document: DataRequestDocument) => + renderDataRequestDocument(document, { locale, phrase, nonce }); + let group: string | null = null; + let mutation = false; + // The owner's mode once one is selected; a refusal links back by it, never by a submitted group. + let selected: 'session' | 'entry' | null = null; + const refuse = ( + outcome: Readonly<{ status: number; message: DataRequestKey; retryAfter: number | null }>, + ) => + write( + outcome.status, + render({ + kind: 'error', + message: outcome.message, + back: outcome.status === 401 ? { kind: 'signin' } : { kind: 'page', mode: selected }, + }), + undefined, + outcome.retryAfter, + ); + const path = binding.target.split('?', 1)[0]!; + const posted = binding.method === 'POST' ? route(path) : null; + if ( + !( + (path === '/account/data' && ['GET', 'HEAD'].includes(binding.method)) || + (binding.method === 'POST' && posted !== null) + ) + ) { + write(404); + return; + } + try { + const query = bffQuery( + binding.target, + posted ? [] : ['cursor', 'group', 'scopeCursor', 'step', 'result'], + ); + if ( + headers.has('authorization') || + (binding.method !== 'POST' && + (Number(headers.get('content-length') ?? '0') !== 0 || headers.has('transfer-encoding'))) + ) + throw new BffInputError(); + if ( + binding.method === 'HEAD' || + headers.has('rsc') || + headers.has('next-router-prefetch') || + /prefetch/i.test(headers.get('purpose') ?? '') || + /prefetch/i.test(headers.get('sec-purpose') ?? '') + ) { + write(200); + return; + } + const cookies = bffCookies(headers.get('cookie')); + const browser = cookies.get(BFF_COOKIES.browser); + const owned = (family: string): SessionBinding | null => { + const handle = cookies.get(family); + return handle && browser + ? { + host: binding.host, + handle, + browser, + traceparent: headers.get('traceparent') ?? undefined, + } + : null; + }; + const entryOwner = owned(BFF_COOKIES.entry); + const sessionOwner = owned(BFF_COOKIES.session); + // A posted action names its mode by path; a page prefers the entry owner, which exists only during entry. + const candidates: readonly (readonly ['session' | 'entry', SessionBinding | null])[] = posted + ? [[posted.mode, posted.mode === 'entry' ? entryOwner : sessionOwner]] + : [ + ['entry', entryOwner], + ['session', sessionOwner], + ]; + if (!candidates.some(([, owner]) => owner !== null)) { + if (posted) refuse({ status: 401, message: 'error.unauthorized', retryAfter: null }); + else write(200, render({ kind: 'signin' })); + return; + } + const pinned = input.responseLease(binding); + let mode: 'session' | 'entry' | undefined; + let owner: SessionBinding | undefined; + let retention: ReturnType<BffSessionStore['retainDataRequests']> | undefined; + let refusal: unknown; + for (const [candidateMode, candidate] of candidates) { + if (!candidate) continue; + try { + retention = input.store.retainDataRequests(candidate, pinned, candidateMode); + mode = candidateMode; + owner = candidate; + break; + } catch (error) { + // A stale entry cookie gives way to a live session; any other failure is the answer. + if (!(error instanceof BffSessionError) || !['revoked', 'expired'].includes(error.reason)) + throw error; + refusal = error; + } + } + // Only a pinned lease publishes: a refusal before any owner is chosen is an unpublished output, as the sign-in + // page and the 404 are, and never touches the lease. + if (!retention || !mode || !owner) throw refusal ?? new BffSessionError('revoked'); + lease = pinned; + selected = mode; + const csrf = retention.csrfToken; + // The pin ends this response with its owner; nothing the response does is promised past it. + const ownerDeadline = now() + retention.remainingMs; + const http: BffHttpRequest = { + host: binding.host, + source: binding.peer, + method: binding.method, + target: binding.target, + headers, + body: + binding.method === 'POST' + ? (Readable.toWeb(request) as ReadableStream<Uint8Array>) + : null, + signal: lease.signal, + }; + const currentMode = mode; + const currentOwner = owner; + const own = (operation: OwnDataRequestOperation) => + input.store.ownDataRequest(currentOwner, binding.peer, operation, csrf, pinned.signal); + const retained = (operation: RetainedDataRequestOperation) => + input.store.retainedDataRequest(currentOwner, binding.peer, operation, csrf, pinned.signal); + + /** ADR-0107 § 4: mint, then relay every chunk in order as one attachment, or refuse before any byte. */ + const download = async (requestId: string) => { + const retainedGroup = group!; + let begun = false; + const sink: DataExportSink = { + begin(byteCount) { + pinned.publish({ kind: 'data_request_result', status: 200 }); + published = true; + begun = true; + response.writeHead(200, { + 'content-type': 'application/json; charset=utf-8', + 'content-disposition': 'attachment; filename="data-export.json"', + 'content-length': String(byteCount), + 'cache-control': 'no-store', + 'referrer-policy': 'no-referrer', + 'x-content-type-options': 'nosniff', + 'x-frame-options': 'DENY', + 'content-security-policy': "default-src 'none'; sandbox; frame-ancestors 'none'", + }); + }, + write: (bytes) => + new Promise<void>((resolve, reject) => { + const closed = () => reject(new Error('Data export response closed')); + response.once('close', closed); + response.write(bytes, (error) => { + response.removeListener('close', closed); + if (error) reject(error); + else resolve(); + }); + }), + end: () => + new Promise<void>((resolve, reject) => { + const closed = () => reject(new Error('Data export response closed')); + response.once('close', closed); + response.end(() => { + response.removeListener('close', closed); + resolve(); + }); + }), + abort() { + response.destroy(); + }, + }; + const outcome = await relayDataExport({ + mint: () => + currentMode === 'session' + ? own({ kind: 'mintOwnDataExportTicket', id: requestId }) + : retained({ + kind: 'mintRetainedDataExportTicket', + group: retainedGroup, + id: requestId, + }), + read: (ticket, index) => + currentMode === 'session' + ? own({ kind: 'readOwnDataExportChunk', id: requestId, ticket, index }) + : retained({ + kind: 'readRetainedDataExportChunk', + group: retainedGroup, + id: requestId, + ticket, + index, + }), + sink, + signal: pinned.signal, + now, + ownerDeadline, + }); + if (begun || outcome.kind !== 'refused') { + // Once the headers are out, anything short of a completed body ends with a destroyed connection. + if (outcome.kind !== 'completed' && !response.destroyed) response.destroy(); + return; + } + const refused = dataRequestRefusal(outcome.result, false); + // A ticket refusal has its own sentence (the limit, a gone file); a failed first chunk is "could not start". + refuse( + outcome.result === null || + (outcome.stage === 'chunk' && ![401, 429].includes(refused.status)) + ? { ...refused, message: 'error.download' } + : refused, + ); + }; + + let cursor = query.get('cursor'); + let scopeCursor = query.get('scopeCursor'); + let step = query.get('step'); + const resultParameter = query.get('result'); + group = query.get('group'); + if (posted) { + exactBffOrigin(http); + const fields = await bffForm(http, ACTION_FIELDS[posted.action]); + if (!bffSecretEquals(fields.get('csrfToken'), csrf)) throw new BffSessionError('csrf'); + group = fields.get('group'); + if (currentMode === 'entry' ? !groupValue(group) : group !== null) + throw new BffInputError(); + const action = posted.action; + if (action !== 'view') { + const key = fields.get('idempotencyKey'); + const requestId = fields.get('requestId'); + const version = fields.get('version'); + if ( + (['export', 'erasure', 'closure', 'cancel', 'revoke'].includes(action) && + !opaque(key)) || + (['cancel', 'revoke', 'download'].includes(action) && !uuid(requestId)) || + (['cancel', 'revoke'].includes(action) && !versionValue(version)) + ) + throw new BffInputError(); + if ( + (action === 'erasure' && fields.get('confirm') !== 'erase') || + (action === 'closure' && + (fields.get('confirm') !== 'close' || fields.get('acknowledge') !== 'no_status')) + ) { + // A refused confirmation names the step it came from; the document returns to it in the session mode + // only, because a retained step needs its group and a refusal never repeats a submitted group. + write( + 400, + render({ + kind: 'error', + message: 'error.confirmation', + back: { kind: 'page', mode: currentMode, step: action }, + }), + ); + return; + } + if (action === 'download') { + await download(requestId!); + return; + } + const retainedGroup = group!; + let operation: OwnDataRequestOperation | RetainedDataRequestOperation; + const idempotencyKey = key!; + if (currentMode === 'session') + operation = + action === 'export' + ? { kind: 'createOwnDataExport', idempotencyKey } + : action === 'erasure' + ? { kind: 'createOwnDataErasure', idempotencyKey } + : action === 'closure' + ? { kind: 'createOwnAccountClosure', idempotencyKey } + : { + kind: action === 'cancel' ? 'cancelOwnDataRequest' : 'revokeOwnDataExport', + id: requestId!, + version: version!, + idempotencyKey, + }; + else + operation = + action === 'export' + ? { kind: 'createRetainedDataExport', group: retainedGroup, idempotencyKey } + : action === 'erasure' + ? { kind: 'createRetainedDataErasure', group: retainedGroup, idempotencyKey } + : action === 'closure' + ? { kind: 'createRetainedAccountClosure', group: retainedGroup, idempotencyKey } + : { + kind: + action === 'cancel' + ? 'cancelRetainedDataRequest' + : 'revokeRetainedDataExport', + group: retainedGroup, + id: requestId!, + version: version!, + idempotencyKey, + }; + mutation = true; + const outcome = + currentMode === 'session' + ? await own(operation as OwnDataRequestOperation) + : await retained(operation as RetainedDataRequestOperation); + lease.signal.throwIfAborted(); + if (outcome.kind !== 'success') { + refuse(dataRequestRefusal(outcome, true)); + return; + } + const result: DataRequestResult = + action === 'cancel' ? 'cancelled' : action === 'revoke' ? 'revoked' : action; + const destination = new URLSearchParams({ + ...(currentMode === 'entry' ? { group: retainedGroup } : {}), + result, + }); + write(303, '', '/account/data?' + destination.toString()); + return; + } + // A posted view selects the group by a proved form, as the consent entry does; its history guard then records + // only that group's fixed page, so a reload reopens the group and never a cursor, step or result. + cursor = null; + scopeCursor = null; + step = null; + } else if (resultParameter !== null && !RESULTS.has(resultParameter as DataRequestResult)) + throw new BffInputError(); + if ( + (step !== null && step !== 'erasure' && step !== 'closure') || + (cursor !== null && !sealed(cursor)) || + (scopeCursor !== null && !sealed(scopeCursor)) || + (currentMode === 'session' && (group !== null || scopeCursor !== null)) || + (currentMode === 'entry' && + (group === null + ? cursor !== null || step !== null || resultParameter !== null + : !groupValue(group) || scopeCursor !== null)) + ) + throw new BffInputError(); + let scopes: RetainedDataRequestScopePage | null = null; + let requests: OwnDataRequestPage | null = null; + if (currentMode === 'entry' && group === null) { + const read = await retained({ + kind: 'listRetainedDataRequestScopes', + limit: 20, + ...(scopeCursor ? { cursor: scopeCursor } : {}), + }); + if (read.kind !== 'success') { + refuse(dataRequestRefusal(read, false)); + return; + } + scopes = read.data as RetainedDataRequestScopePage; + } else { + const read = + currentMode === 'session' + ? await own({ kind: 'listOwnDataRequests', limit: 20, ...(cursor ? { cursor } : {}) }) + : await retained({ + kind: 'listRetainedDataRequests', + group: group!, + limit: 20, + ...(cursor ? { cursor } : {}), + }); + if (read.kind !== 'success') { + refuse(dataRequestRefusal(read, false)); + return; + } + requests = read.data as OwnDataRequestPage; + } + const snapshot: NativeDataRequestSnapshot = lease.publish({ + kind: 'data_requests', + mode: currentMode, + scope: retention.scope, + group: currentMode === 'entry' ? group : null, + scopes, + requests, + step: step as 'erasure' | 'closure' | null, + result: posted ? null : (resultParameter as DataRequestResult | null), + preparedAt: new Date(now()).toISOString(), + entryExpiresAt: + retention.expiresAt === null ? null : new Date(retention.expiresAt).toISOString(), + csrfToken: csrf, + // One unused key per keyed form: the export, the confirmation step, and a revoke and cancel per request. + formKeys: Array.from({ length: 2 + 2 * (requests?.items.length ?? 0) }, () => + randomBytes(32).toString('base64url'), + ), + }); + published = true; + if (snapshot.kind !== 'data_requests') throw new BffSessionError('response'); + lease.signal.throwIfAborted(); + write(200, render({ kind: 'page', page: snapshot })); + } catch (error) { + if (response.headersSent) { + response.destroy(); + return; + } + if (error instanceof BffInputError) { + refuse({ status: 400, message: 'error.input', retryAfter: null }); + return; + } + if (error instanceof BffSessionError && error.reason === 'csrf') { + refuse({ status: 403, message: 'error.csrf', retryAfter: null }); + return; + } + if (error instanceof BffSessionError && ['revoked', 'expired'].includes(error.reason)) { + refuse({ status: 401, message: 'error.unauthorized', retryAfter: null }); + return; + } + if (error instanceof SnapshotAdmissionError) { + refuse({ + status: error.status, + message: error.status === 429 ? 'error.busy' : 'error.unavailable', + retryAfter: 30, + }); + return; + } + refuse({ + status: 503, + message: mutation ? 'error.unconfirmed' : 'error.unavailable', + retryAfter: 30, + }); + } + }; +} diff --git a/frontend/apps/web/src/server/auth/native-data-request-routes.test.ts b/frontend/apps/web/src/server/auth/native-data-request-routes.test.ts new file mode 100644 index 000000000..54e33066a --- /dev/null +++ b/frontend/apps/web/src/server/auth/native-data-request-routes.test.ts @@ -0,0 +1,913 @@ +// @vitest-environment node +import { createServer } from 'node:http'; +import { connect } from 'node:net'; + +import type { OwnDataRequest } from '@learnstack/sdk/administration-server'; +import { afterEach, describe, expect, it } from 'vitest'; + +import { DATA_REQUEST_REFUSALS } from './native-data-request-http'; +import type { NativeOperationResult } from './native-operation-contract'; +import en from '../../i18n/messages/en/data.json'; +import { + DownloadWire, + artifact, + chunkBytes, + closeDataRequestFixtures, + fixture, + formKeys, + id, + ok, + organization, + pageInfo, + refused, + request, + second, + shown, + ticket, +} from '../../test/data-request-person-fixture'; + +afterEach(closeDataRequestFixtures); + +/** A form key as the page issues them: 43 URL-safe characters, distinct for each label. */ +const keyFor = (label: string) => label.replaceAll(/[^A-Za-z0-9]/g, '').padEnd(43, 'k'); +const links = (html: string) => + [...html.matchAll(/class="action" href="([^"]*)"/g)].map((match) => match[1]); +const view = (html: string) => /data-data-request-view="([a-z_]+)"/.exec(html)?.[1]; +/** The hidden `group` values of every retained form on a page. */ +const groups = (html: string) => + [...html.matchAll(/name="group" value="([^"]*)"/g)].map((match) => match[1]); +/** The operations a caller mock was asked to perform, in order. */ +const operations = (f: Awaited<ReturnType<typeof fixture>>) => + f.own.mock.calls.map(([operation]) => operation); +const retainedOperations = (f: Awaited<ReturnType<typeof fixture>>) => + f.retained.mock.calls.map(([, , operation]) => operation); + +type Write = Readonly<{ + action: 'export' | 'erasure' | 'closure' | 'cancel' | 'revoke'; + fields: Record<string, string>; + result: string; + session: (key: string) => object; + entry: (key: string, group: string) => object; +}>; +/** Each filing and action route with the exact operation it files in each mode. */ +const WRITES: readonly Write[] = [ + { + action: 'export', + fields: {}, + result: 'export', + session: (idempotencyKey) => ({ kind: 'createOwnDataExport', idempotencyKey }), + entry: (idempotencyKey, group) => ({ kind: 'createRetainedDataExport', group, idempotencyKey }), + }, + { + action: 'erasure', + fields: { confirm: 'erase' }, + result: 'erasure', + session: (idempotencyKey) => ({ kind: 'createOwnDataErasure', idempotencyKey }), + entry: (idempotencyKey, group) => ({ + kind: 'createRetainedDataErasure', + group, + idempotencyKey, + }), + }, + { + action: 'closure', + fields: { confirm: 'close', acknowledge: 'no_status' }, + result: 'closure', + session: (idempotencyKey) => ({ kind: 'createOwnAccountClosure', idempotencyKey }), + entry: (idempotencyKey, group) => ({ + kind: 'createRetainedAccountClosure', + group, + idempotencyKey, + }), + }, + { + action: 'cancel', + fields: { requestId: id, version: '3' }, + result: 'cancelled', + session: (idempotencyKey) => ({ + kind: 'cancelOwnDataRequest', + id, + version: '3', + idempotencyKey, + }), + entry: (idempotencyKey, group) => ({ + kind: 'cancelRetainedDataRequest', + group, + id, + version: '3', + idempotencyKey, + }), + }, + { + action: 'revoke', + fields: { requestId: second, version: '9007199254740993' }, + result: 'revoked', + session: (idempotencyKey) => ({ + kind: 'revokeOwnDataExport', + id: second, + version: '9007199254740993', + idempotencyKey, + }), + entry: (idempotencyKey, group) => ({ + kind: 'revokeRetainedDataExport', + group, + id: second, + version: '9007199254740993', + idempotencyKey, + }), + }, +]; +const GROUPS = ['tenant', organization] as const; + +describe('every filing and action route files exactly its own operation (ADR-0106 §§ 9-11)', () => { + it.each(WRITES.map((write) => [write.action, write] as const))( + 'session %s files the own operation and answers the fixed page', + async (_action, write) => { + const f = await fixture('session'); + const key = keyFor('session-' + write.action); + const wire = await f.run('POST', '/api/account/data-requests/' + write.action, { + csrfToken: f.csrf, + idempotencyKey: key, + ...write.fields, + }); + expect(wire.statusCode).toBe(303); + expect(wire.headers.get('location')).toBe('/account/data?result=' + write.result); + expect(wire.html).toBe(''); + expect(operations(f)).toEqual([write.session(key)]); + // A live session never reaches the retained caller. + expect(f.retained).not.toHaveBeenCalled(); + }, + ); + + it.each(GROUPS.flatMap((group) => WRITES.map((write) => [write.action, group, write] as const)))( + 'retained %s in group %s files the retained operation and answers that group', + async (_action, group, write) => { + const f = await fixture('entry'); + const key = keyFor('entry-' + write.action); + const wire = await f.run('POST', '/api/auth/entry/data-requests/' + write.action, { + csrfToken: f.csrf, + idempotencyKey: key, + group, + ...write.fields, + }); + expect(wire.statusCode).toBe(303); + expect(wire.headers.get('location')).toBe( + '/account/data?group=' + group + '&result=' + write.result, + ); + expect(wire.html).toBe(''); + expect(retainedOperations(f)).toEqual([write.entry(key, group)]); + // The retained entry never performs a live-session operation. + expect(f.own).not.toHaveBeenCalled(); + expect(f.administration).not.toHaveBeenCalled(); + }, + ); + + it.each([ + ['session', undefined], + ['entry', 'tenant'], + ['entry', organization], + ] as const)( + 'the %s download mints one ticket, reads each chunk in order and answers the attachment (group %s)', + async (mode, group) => { + const f = await fixture(mode); + const wire = new DownloadWire(); + await f.run( + 'POST', + mode === 'session' + ? '/api/account/data-requests/download' + : '/api/auth/entry/data-requests/download', + { csrfToken: f.csrf, requestId: id, ...(group ? { group } : {}) }, + { wire }, + ); + expect(wire.statusCode).toBe(200); + expect(wire.headers.get('content-disposition')).toBe( + 'attachment; filename="data-export.json"', + ); + expect(Buffer.concat(wire.bytes).equals(Buffer.concat([chunkBytes(0), chunkBytes(1)]))).toBe( + true, + ); + if (mode === 'session') { + expect(operations(f)).toEqual([ + { kind: 'mintOwnDataExportTicket', id }, + { kind: 'readOwnDataExportChunk', id, ticket, index: 0 }, + { kind: 'readOwnDataExportChunk', id, ticket, index: 1 }, + ]); + expect(f.retained).not.toHaveBeenCalled(); + } else { + expect(retainedOperations(f)).toEqual([ + { kind: 'mintRetainedDataExportTicket', group, id }, + { kind: 'readRetainedDataExportChunk', group, id, ticket, index: 0 }, + { kind: 'readRetainedDataExportChunk', group, id, ticket, index: 1 }, + ]); + expect(f.own).not.toHaveBeenCalled(); + } + }, + ); +}); + +describe('one refusal sentence per route and mode, never an API text', () => { + const ROUTES = [ + [ + 'export', + 'request_already_active', + '$', + { csrfToken: '', idempotencyKey: keyFor('r-export') }, + ], + [ + 'erasure', + 'blocked_hold', + '$', + { csrfToken: '', idempotencyKey: keyFor('r-erasure'), confirm: 'erase' }, + ], + [ + 'closure', + 'blocked_last_administrator', + '$', + { + csrfToken: '', + idempotencyKey: keyFor('r-closure'), + confirm: 'close', + acknowledge: 'no_status', + }, + ], + [ + 'cancel', + 'data_request_window_ended', + '$', + { csrfToken: '', idempotencyKey: keyFor('r-cancel'), requestId: id, version: '3' }, + ], + [ + 'revoke', + 'data_export_unavailable', + 'artifact', + { csrfToken: '', idempotencyKey: keyFor('r-revoke'), requestId: id, version: '4' }, + ], + ['download', 'data_export_ticket_limit', 'artifact', { csrfToken: '', requestId: id }], + ] as const; + it.each( + (['session', 'entry'] as const).flatMap((mode) => + ROUTES.map(([action, reason, where, form]) => [mode, action, reason, where, form] as const), + ), + )('%s %s answers the %s sentence in a 409', async (mode, action, reason, where, form) => { + const f = await fixture(mode); + const api = refused(409, 'business_rule_violation', { + [where]: [{ key: 'lockey_' + reason }], + }); + if (mode === 'session') f.own.mockReturnValueOnce(api); + else f.retained.mockImplementationOnce(async () => api); + const wire = await f.run( + 'POST', + (mode === 'session' ? '/api/account/data-requests/' : '/api/auth/entry/data-requests/') + + action, + { ...form, csrfToken: f.csrf, ...(mode === 'entry' ? { group: 'tenant' } : {}) }, + ); + expect(wire.statusCode).toBe(409); + expect(wire.headers.get('content-type')).toBe('text/html; charset=utf-8'); + expect(wire.headers.has('content-disposition')).toBe(false); + expect(wire.html).toContain('role="alert"'); + expect(wire.html).toContain(shown(en.refusal[reason])); + for (const other of Object.values(en.refusal).filter( + (sentence) => sentence !== en.refusal[reason], + )) + expect(wire.html).not.toContain(shown(other)); + expect(wire.html).not.toContain('lockey_'); + // The refusal leads back by the owner's mode, never by a submitted group. + expect(links(wire.html)).toEqual( + mode === 'session' ? ['/account/data', '/portal'] : ['/account/data', '/api/auth/entry'], + ); + expect(wire.html).not.toContain('group='); + }); + + it('pairs every reason the person can meet with the sentence of its own name', async () => { + for (const [reason, key] of Object.entries(DATA_REQUEST_REFUSALS)) { + expect(key, reason).toBe('refusal.' + reason.slice('lockey_'.length)); + expect(Object.hasOwn(en.refusal, key.slice('refusal.'.length)), key).toBe(true); + } + const f = await fixture('session'); + for (const [reason, key] of Object.entries(DATA_REQUEST_REFUSALS)) { + f.own.mockReturnValueOnce(refused(409, 'business_rule_violation', { $: [{ key: reason }] })); + const wire = await f.run('POST', '/api/account/data-requests/export', { + csrfToken: f.csrf, + idempotencyKey: keyFor('pair'), + }); + expect(wire.html, reason).toContain( + shown(en.refusal[key.slice('refusal.'.length) as keyof typeof en.refusal]), + ); + } + }); +}); + +describe('the retained pages reached after a redirect (ADR-0106 § 9)', () => { + it('follows the 303 of a retained erasure to that group’s page with its notice', async () => { + const f = await fixture('entry', [request()]); + const filed = await f.run('POST', '/api/auth/entry/data-requests/erasure', { + csrfToken: f.csrf, + idempotencyKey: keyFor('follow'), + group: organization, + confirm: 'erase', + }); + const location = filed.headers.get('location') as string; + expect(location).toBe('/account/data?group=' + organization + '&result=erasure'); + f.retained.mockClear(); + const page = await f.run('GET', location); + expect(page.statusCode).toBe(200); + expect(view(page.html)).toBe('entry'); + expect(page.html).toContain( + '<div class="notice" role="status"><h2>' + + en.result.title + + '</h2><p>' + + shown(en.result.erasure) + + '</p></div>', + ); + expect(page.html).toContain('<title>' + en.result.title + ' – ' + en.common.title); + // Every retained form of the page names the group the page was opened for, and no other. + expect(new Set(groups(page.html))).toEqual(new Set([organization])); + expect(groups(page.html).length).toBeGreaterThanOrEqual(1); + // A reload or a restored page reopens the group, never the result. + expect(page.html).toContain( + "history.replaceState(null,'','/account/data?group=" + organization + "')", + ); + expect(retainedOperations(f)).toEqual([ + { kind: 'listRetainedDataRequests', group: organization, limit: 20 }, + ]); + expect(f.administration).not.toHaveBeenCalled(); + expect(f.own).not.toHaveBeenCalled(); + expect(f.native.self).not.toHaveBeenCalled(); + // A result is shown for each closed value and nothing else. + for (const result of ['export', 'closure', 'cancelled', 'revoked'] as const) + expect((await f.run('GET', '/account/data?group=tenant&result=' + result)).html).toContain( + shown(en.result[result]), + ); + }); + + it.each([ + ['erasure', 'entry_erasure', 1], + ['closure', 'entry_closure', 2], + ] as const)( + 'opens the %s confirmation of a retained group with its group and required boxes', + async (step, name, boxes) => { + const f = await fixture('entry'); + for (const group of GROUPS) { + const page = await f.run('GET', '/account/data?group=' + group + '&step=' + step); + expect(page.statusCode).toBe(200); + expect(view(page.html)).toBe(name); + const form = page.html.slice( + page.html.indexOf('action="/api/auth/entry/data-requests/' + step + '"'), + ); + const body = form.slice(0, form.indexOf('</form>')); + expect(body).toContain('name="group" value="' + group + '"'); + expect([...body.matchAll(/type="checkbox"[^>]*required/g)]).toHaveLength(boxes); + expect(body).toContain('<fieldset><legend>'); + expect(body).toMatch(/name="idempotencyKey" value="[A-Za-z0-9_-]{43}"/); + expect(page.html).toContain( + "history.replaceState(null,'','/account/data?group=" + group + "')", + ); + } + expect(f.own).not.toHaveBeenCalled(); + expect(f.administration).not.toHaveBeenCalled(); + }, + ); + + it('refuses every retained query that names no group, an unknown one or a stray parameter', async () => { + const f = await fixture('entry'); + for (const target of [ + '/account/data?result=export', + '/account/data?cursor=AAAA', + '/account/data?step=erasure', + '/account/data?group=Tenant', + '/account/data?group=019a154b-0000-4000-8000-0000000000a1', + '/account/data?group=tenant&step=everything', + '/account/data?group=tenant&result=everything', + '/account/data?group=tenant&result=export&result=export', + '/account/data?group=tenant&scopeCursor=AAAA', + '/account/data?group=tenant&cursor=not%20sealed', + '/account/data?group=tenant&group=tenant', + '/account/data?scopeCursor=' + 'A'.repeat(1025), + ]) + expect((await f.run('GET', target)).statusCode, target).toBe(400); + expect(f.retained).not.toHaveBeenCalled(); + }); + + it('pages a retained group and the chooser through cursors sealed to the owner', async () => { + const f = await fixture('entry', [request()]); + f.retained.mockImplementationOnce(async () => + ok({ items: [], pageInfo: { ...pageInfo, nextCursor: 'raw-group-cursor', hasNext: true } }), + ); + const list = (await f.run('GET', '/account/data?group=' + organization)).html; + expect(list).not.toContain('raw-group-cursor'); + const next = new RegExp( + 'href="/account/data\\?group=' + organization + '&cursor=([A-Za-z0-9_-]+)"', + ).exec(list)![1]!; + f.retained.mockClear(); + const second = await f.run('GET', '/account/data?group=' + organization + '&cursor=' + next); + expect(second.statusCode).toBe(200); + expect(retainedOperations(f)).toEqual([ + { + kind: 'listRetainedDataRequests', + group: organization, + limit: 20, + cursor: 'raw-group-cursor', + }, + ]); + // The same sealed value in another group is still this owner's and purpose's, and the API sees only the group + // the request names: the group is part of the query, never of the cursor. + f.retained.mockImplementationOnce(async () => + ok({ items: [], pageInfo: { ...pageInfo, nextCursor: 'raw-scope-cursor', hasNext: true } }), + ); + f.retained.mockClear(); + const chooser = (await f.run('GET', '/account/data')).html; + expect(chooser).not.toContain('raw-scope-cursor'); + expect(view(chooser)).toBe('entry_scopes'); + const scopeNext = /href="\/account\/data\?scopeCursor=([A-Za-z0-9_-]+)"/.exec(chooser)![1]!; + f.retained.mockClear(); + expect((await f.run('GET', '/account/data?scopeCursor=' + scopeNext)).statusCode).toBe(200); + expect(retainedOperations(f)).toEqual([ + { kind: 'listRetainedDataRequestScopes', limit: 20, cursor: 'raw-scope-cursor' }, + ]); + }); +}); + +describe('one browser holding both an entry and a session (ADR-0106 § 9)', () => { + const dead = (browser: string) => + '__Host-ls-entry=' + + 'x'.repeat(43) + + '; __Host-ls-session=' + + 'y'.repeat(43) + + '; __Host-ls-browser=' + + browser; + + it('shows the retained entry while it lives, and calls no live-session operation', async () => { + const f = await fixture('both', [request()]); + const wire = await f.run('GET', '/account/data'); + expect(wire.statusCode).toBe(200); + expect(view(wire.html)).toBe('entry_scopes'); + expect(retainedOperations(f)).toEqual([{ kind: 'listRetainedDataRequestScopes', limit: 20 }]); + expect(f.own).not.toHaveBeenCalled(); + expect(f.administration).not.toHaveBeenCalled(); + const group = await f.run('GET', '/account/data?group=tenant'); + expect(view(group.html)).toBe('entry'); + expect(f.own).not.toHaveBeenCalled(); + expect(f.administration).not.toHaveBeenCalled(); + }); + + it('falls back to the live session when the entry has expired', async () => { + const f = await fixture('both', [request()]); + // The entry lives five minutes; the session outlasts it. + f.advance(301_000); + const wire = await f.run('GET', '/account/data'); + expect(wire.statusCode).toBe(200); + expect(view(wire.html)).toBe('session'); + expect(operations(f)).toEqual([{ kind: 'listOwnDataRequests', limit: 20 }]); + expect(f.retained).not.toHaveBeenCalled(); + // Only the session's own addresses remain; a retained group is no longer the person's to open. + expect((await f.run('GET', '/account/data?group=tenant')).statusCode).toBe(400); + }); + + it('falls back to the live session when the entry cookie names a revoked entry', async () => { + // The session this person selected came from an entry: the browser still carries that entry's cookie. + const f = await fixture('session', [request()]); + const spent = '__Host-ls-entry=' + f.owner.finished.handle + '; ' + f.owner.cookie; + const wire = await f.run('GET', '/account/data', undefined, { headers: { cookie: spent } }); + expect(wire.statusCode).toBe(200); + expect(view(wire.html)).toBe('session'); + expect(operations(f)).toEqual([{ kind: 'listOwnDataRequests', limit: 20 }]); + expect(f.retained).not.toHaveBeenCalled(); + // A bare unknown entry handle is the same refusal of the entry, and the session still answers. + const unknown = await f.run('GET', '/account/data', undefined, { + headers: { cookie: '__Host-ls-entry=' + 'x'.repeat(43) + '; ' + f.owner.cookie }, + }); + expect(view(unknown.html)).toBe('session'); + }); + + it('answers 401 with the sign-in way back when neither owner lives, calling nothing', async () => { + const f = await fixture('both', [request()]); + const browser = f.session!.finished.browser; + const answers = async (cookie: string) => { + const wire = await f.run('GET', '/account/data', undefined, { headers: { cookie } }); + expect(wire.statusCode, cookie).toBe(401); + expect(wire.html, cookie).toContain(shown(en.error.unauthorized)); + expect(links(wire.html), cookie).toEqual(['/api/auth/signin']); + }; + // Handles that name no owner at all, then the real ones once both owners have ended. + await answers(dead(browser)); + f.advance(2_000_000); + await answers(f.cookie); + await answers('__Host-ls-entry=' + f.entry!.finished.handle + '; __Host-ls-browser=' + browser); + await answers(f.session!.cookie); + expect(f.own).not.toHaveBeenCalled(); + expect(f.retained).not.toHaveBeenCalled(); + expect(f.administration).not.toHaveBeenCalled(); + }); + + it('names the owner of a posted action by its path and checks that owner’s proof', async () => { + const f = await fixture('both'); + const key = keyFor('both-export'); + // The session's route files in the session with the session's proof… + const own = await f.run('POST', '/api/account/data-requests/export', { + csrfToken: f.sessionCsrf!, + idempotencyKey: key, + }); + expect(own.headers.get('location')).toBe('/account/data?result=export'); + expect(operations(f)).toEqual([{ kind: 'createOwnDataExport', idempotencyKey: key }]); + expect(f.retained).not.toHaveBeenCalled(); + // …the entry's route files in the entry with the entry's proof… + f.own.mockClear(); + const retained = await f.run('POST', '/api/auth/entry/data-requests/export', { + csrfToken: f.entryCsrf!, + idempotencyKey: key, + group: 'tenant', + }); + expect(retained.headers.get('location')).toBe('/account/data?group=tenant&result=export'); + expect(retainedOperations(f)).toEqual([ + { kind: 'createRetainedDataExport', group: 'tenant', idempotencyKey: key }, + ]); + expect(f.own).not.toHaveBeenCalled(); + // …and the other owner's proof is a refused proof, with nothing filed. + f.retained.mockClear(); + const crossed = [ + ['/api/account/data-requests/export', f.entryCsrf!, {}], + ['/api/auth/entry/data-requests/export', f.sessionCsrf!, { group: 'tenant' }], + ] as const; + for (const [path, csrfToken, extra] of crossed) + expect( + (await f.run('POST', path, { csrfToken, idempotencyKey: key, ...extra })).statusCode, + path, + ).toBe(403); + expect(f.own).not.toHaveBeenCalled(); + expect(f.retained).not.toHaveBeenCalled(); + }); +}); + +describe('a continuation is the owner’s and the purpose’s alone (ADR-0106 § 9)', () => { + /** Flips one bit of the first ciphertext byte of a sealed cursor: it can never equal the genuine value. */ + const tampered = (cursor: string, offset = 13) => { + const bytes = Buffer.from(cursor, 'base64url'); + bytes[offset] = bytes[offset]! ^ 1; + const value = bytes.toString('base64url'); + expect(value).not.toBe(cursor); + return value; + }; + const withNext = (raw: string): NativeOperationResult => + ok({ items: [], pageInfo: { ...pageInfo, nextCursor: raw, hasNext: true } }); + const sealed = /href="\/account\/data\?(?:group=[^&"]+&)?cursor=([A-Za-z0-9_-]+)"/; + + it('refuses a tampered cursor in either mode before any read, whichever byte is changed', async () => { + const session = await fixture('session'); + session.own.mockReturnValueOnce(withNext('raw-api-cursor')); + const cursor = sealed.exec((await session.run('GET', '/account/data')).html)![1]!; + const bytes = Buffer.from(cursor, 'base64url'); + // 1 version + 12 nonce + 14 ciphertext + 16 tag: change one bit of each region in turn. + expect(bytes.length).toBe(43); + session.own.mockClear(); + for (const offset of [0, 1, 13, 26, 27, 42]) + expect( + (await session.run('GET', '/account/data?cursor=' + tampered(cursor, offset))).statusCode, + 'offset ' + offset, + ).toBe(400); + expect(session.own).not.toHaveBeenCalled(); + // The untouched value still opens, so the refusals above are the tampering and nothing else. + expect((await session.run('GET', '/account/data?cursor=' + cursor)).statusCode).toBe(200); + expect(operations(session)).toEqual([ + { kind: 'listOwnDataRequests', limit: 20, cursor: 'raw-api-cursor' }, + ]); + + const entry = await fixture('entry'); + entry.retained.mockImplementationOnce(async () => withNext('raw-group-cursor')); + const group = sealed.exec((await entry.run('GET', '/account/data?group=tenant')).html)![1]!; + entry.retained.mockClear(); + for (const offset of [0, 13, 42]) + expect( + (await entry.run('GET', '/account/data?group=tenant&cursor=' + tampered(group, offset))) + .statusCode, + 'offset ' + offset, + ).toBe(400); + expect(entry.retained).not.toHaveBeenCalled(); + }); + + it('refuses another owner’s cursor in the live session and in the retained entry', async () => { + const f = await fixture('session'); + const other = await f.login(); + const asOther = { headers: { cookie: other.cookie } }; + f.own.mockReturnValueOnce(withNext('raw-first')); + const first = sealed.exec((await f.run('GET', '/account/data')).html)![1]!; + f.own.mockReturnValueOnce(withNext('raw-other')); + const foreign = sealed.exec( + (await f.run('GET', '/account/data', undefined, asOther)).html, + )![1]!; + f.own.mockClear(); + // Each owner's own cursor opens; the other's is refused before any read. + expect((await f.run('GET', '/account/data?cursor=' + first)).statusCode).toBe(200); + expect( + (await f.run('GET', '/account/data?cursor=' + foreign, undefined, asOther)).statusCode, + ).toBe(200); + expect(operations(f).map((operation) => (operation as { cursor?: string }).cursor)).toEqual([ + 'raw-first', + 'raw-other', + ]); + f.own.mockClear(); + expect((await f.run('GET', '/account/data?cursor=' + foreign)).statusCode).toBe(400); + expect( + (await f.run('GET', '/account/data?cursor=' + first, undefined, asOther)).statusCode, + ).toBe(400); + expect(f.own).not.toHaveBeenCalled(); + + // The same holds between two retained entries. + const entry = await fixture('entry'); + const stranger = await entry.enter(); + const asStranger = { headers: { cookie: stranger.cookie } }; + entry.retained.mockImplementationOnce(async () => withNext('raw-entry-a')); + entry.retained.mockImplementationOnce(async () => withNext('raw-entry-b')); + const a = sealed.exec((await entry.run('GET', '/account/data?group=tenant')).html)![1]!; + const b = sealed.exec( + (await entry.run('GET', '/account/data?group=tenant', undefined, asStranger)).html, + )![1]!; + entry.retained.mockClear(); + expect((await entry.run('GET', '/account/data?group=tenant&cursor=' + b)).statusCode).toBe(400); + expect( + (await entry.run('GET', '/account/data?group=tenant&cursor=' + a, undefined, asStranger)) + .statusCode, + ).toBe(400); + expect(entry.retained).not.toHaveBeenCalled(); + }); + + it('refuses a cursor of another purpose: a chooser cursor in a group and the reverse', async () => { + const f = await fixture('entry'); + f.retained.mockImplementationOnce(async () => withNext('raw-group-cursor')); + const group = sealed.exec((await f.run('GET', '/account/data?group=tenant')).html)![1]!; + f.retained.mockImplementationOnce(async () => withNext('raw-scope-cursor')); + const scopes = /scopeCursor=([A-Za-z0-9_-]+)"/.exec( + (await f.run('GET', '/account/data')).html, + )![1]!; + f.retained.mockClear(); + expect((await f.run('GET', '/account/data?group=tenant&cursor=' + scopes)).statusCode).toBe( + 400, + ); + expect((await f.run('GET', '/account/data?scopeCursor=' + group)).statusCode).toBe(400); + expect(f.retained).not.toHaveBeenCalled(); + // Each opens for its own purpose. + expect((await f.run('GET', '/account/data?group=tenant&cursor=' + group)).statusCode).toBe(200); + expect((await f.run('GET', '/account/data?scopeCursor=' + scopes)).statusCode).toBe(200); + }); + + it('refuses an entry’s cursor in a session and a session’s cursor in an entry', async () => { + const f = await fixture('both'); + const sessionOnly = f.session!.cookie; + const entryOnly = + '__Host-ls-entry=' + + f.entry!.finished.handle + + '; __Host-ls-browser=' + + f.session!.finished.browser; + f.own.mockReturnValueOnce(withNext('raw-session-cursor')); + f.retained.mockImplementationOnce(async () => withNext('raw-entry-cursor')); + const fromSession = sealed.exec( + (await f.run('GET', '/account/data', undefined, { headers: { cookie: sessionOnly } })).html, + )![1]!; + const fromEntry = sealed.exec( + ( + await f.run('GET', '/account/data?group=tenant', undefined, { + headers: { cookie: entryOnly }, + }) + ).html, + )![1]!; + f.own.mockClear(); + f.retained.mockClear(); + expect( + ( + await f.run('GET', '/account/data?cursor=' + fromEntry, undefined, { + headers: { cookie: sessionOnly }, + }) + ).statusCode, + ).toBe(400); + expect( + ( + await f.run('GET', '/account/data?group=tenant&cursor=' + fromSession, undefined, { + headers: { cookie: entryOnly }, + }) + ).statusCode, + ).toBe(400); + expect(f.own).not.toHaveBeenCalled(); + expect(f.retained).not.toHaveBeenCalled(); + }); +}); + +describe('form keys are fresh, distinct and reach the API as sent (ADR-0106 § 10)', () => { + const states = (): OwnDataRequest[] => [ + request({ id: '019a154b-0000-7000-8000-000000000001' }), + request({ + id: '019a154b-0000-7000-8000-000000000002', + status: 'completed', + completedAt: '2026-11-22T10:00:00Z', + artifact: artifact(), + }), + request({ + id: '019a154b-0000-7000-8000-000000000003', + status: 'completed', + completedAt: '2026-11-22T10:00:00Z', + artifact: artifact({ id: '019a154b-0000-7000-8000-0000000000f3' }), + }), + request({ + id: '019a154b-0000-7000-8000-000000000004', + kind: 'erasure', + status: 'scheduled', + executeAt: '2026-11-24T10:00:00Z', + }), + request({ + id: '019a154b-0000-7000-8000-000000000005', + kind: 'closure', + status: 'scheduled', + executeAt: '2026-11-24T10:00:00Z', + }), + ]; + + it.each(['session', 'entry'] as const)( + 'gives every keyed form of a %s page its own key and a new page new keys', + async (mode) => { + const f = await fixture(mode, states()); + const target = mode === 'session' ? '/account/data' : '/account/data?group=tenant'; + const first = formKeys((await f.run('GET', target)).html); + // Two cancellations, two revocations, one more cancellation and the export filing. + expect(first.length).toBeGreaterThanOrEqual(5); + expect(new Set(first).size).toBe(first.length); + const again = formKeys((await f.run('GET', target)).html); + expect(again).toHaveLength(first.length); + expect(new Set(again).size).toBe(again.length); + expect(again.filter((key) => first.includes(key))).toEqual([]); + // The confirmation steps (open only where nothing of that kind is active) hold keys of their own. + const idle = await fixture(mode); + const steps: string[] = []; + for (const step of ['erasure', 'closure']) + steps.push( + ...formKeys( + (await idle.run('GET', target + (target.includes('?') ? '&' : '?') + 'step=' + step)) + .html, + ), + ); + expect(steps).toHaveLength(2); + expect(new Set([...first, ...again, ...steps]).size).toBe(first.length * 2 + 2); + }, + ); + + it('sends the same key to the operation again on a double submit and answers the same redirect', async () => { + const f = await fixture('session'); + const key = keyFor('twice'); + const form = { csrfToken: f.csrf, idempotencyKey: key }; + // The API replays the first outcome for the same key; the page adds nothing of its own to the replay. + f.own.mockReturnValueOnce(ok({ id, kind: 'export', status: 'requested', version: '0' })); + f.own.mockReturnValueOnce({ + ...ok({ id, kind: 'export', status: 'requested', version: '0' }), + replayed: true, + } as NativeOperationResult); + const first = await f.run('POST', '/api/account/data-requests/export', form); + const again = await f.run('POST', '/api/account/data-requests/export', form); + for (const wire of [first, again]) { + expect(wire.statusCode).toBe(303); + expect(wire.headers.get('location')).toBe('/account/data?result=export'); + expect(wire.html).toBe(''); + } + expect(operations(f)).toEqual([ + { kind: 'createOwnDataExport', idempotencyKey: key }, + { kind: 'createOwnDataExport', idempotencyKey: key }, + ]); + // A different key is a different filing. + const next = await f.run('POST', '/api/account/data-requests/export', { + csrfToken: f.csrf, + idempotencyKey: keyFor('thrice'), + }); + expect(next.statusCode).toBe(303); + expect( + operations(f).map((operation) => (operation as { idempotencyKey: string }).idempotencyKey), + ).toEqual([key, key, keyFor('thrice')]); + }); + + it('refuses the same key reused for another request with the API’s own sentence', async () => { + const f = await fixture('session'); + f.own.mockReturnValueOnce(refused(409, 'idempotency_key_reuse')); + const wire = await f.run('POST', '/api/account/data-requests/export', { + csrfToken: f.csrf, + idempotencyKey: keyFor('reused'), + }); + expect(wire.statusCode).toBe(409); + expect(wire.html).toContain(shown(en.error.key_reuse)); + }); +}); + +describe('the download POST refuses every hostile form before any mint', () => { + const sessionForm = (extra: Record<string, string>, csrfToken: string) => ({ + csrfToken, + requestId: id, + ...extra, + }); + it('in a live session', async () => { + const f = await fixture('session'); + const cases: [string, Record<string, string> | URLSearchParams, number][] = [ + ['a malformed request', sessionForm({ requestId: 'not-a-uuid' }, f.csrf), 400], + [ + 'a version-4 request', + sessionForm({ requestId: '019a154b-0000-4000-8000-000000000041' }, f.csrf), + 400, + ], + ['an upper-case request', sessionForm({ requestId: id.toUpperCase() }, f.csrf), 400], + ['a missing request', { csrfToken: f.csrf }, 400], + ['an empty request', sessionForm({ requestId: '' }, f.csrf), 400], + ['a stray key', sessionForm({ idempotencyKey: keyFor('stray') }, f.csrf), 400], + ['a stray version', sessionForm({ version: '3' }, f.csrf), 400], + ['a stray group', sessionForm({ group: 'tenant' }, f.csrf), 400], + ['a stray tenant', sessionForm({ tenantId: id }, f.csrf), 400], + [ + 'a repeated request', + new URLSearchParams([ + ['csrfToken', f.csrf], + ['requestId', id], + ['requestId', second], + ]), + 400, + ], + ['a wrong proof', sessionForm({}, 'x'.repeat(43)), 403], + ['no proof', { requestId: id }, 403], + ]; + for (const [name, form, status] of cases) { + const wire = await f.run('POST', '/api/account/data-requests/download', form); + expect(wire.statusCode, name).toBe(status); + expect(wire.headers.has('content-disposition'), name).toBe(false); + } + expect(f.own).not.toHaveBeenCalled(); + expect(f.retained).not.toHaveBeenCalled(); + }); + + it('in the retained entry', async () => { + const f = await fixture('entry'); + const valid = { csrfToken: f.csrf, requestId: id, group: 'tenant' }; + const cases: [string, Record<string, string> | URLSearchParams, number][] = [ + ['a missing group', { csrfToken: f.csrf, requestId: id }, 400], + ['an empty group', { ...valid, group: '' }, 400], + ['an upper-case group', { ...valid, group: 'Tenant' }, 400], + ['a version-4 group', { ...valid, group: '019a154b-0000-4000-8000-0000000000a1' }, 400], + ['a malformed request', { ...valid, requestId: 'not-a-uuid' }, 400], + ['a missing request', { csrfToken: f.csrf, group: 'tenant' }, 400], + ['a stray key', { ...valid, idempotencyKey: keyFor('stray') }, 400], + ['a stray version', { ...valid, version: '3' }, 400], + ['a stray tenant', { ...valid, tenantId: id }, 400], + [ + 'a repeated group', + new URLSearchParams([...Object.entries(valid), ['group', organization]]), + 400, + ], + ['a wrong proof', { ...valid, csrfToken: 'x'.repeat(43) }, 403], + ]; + for (const [name, form, status] of cases) { + const wire = await f.run('POST', '/api/auth/entry/data-requests/download', form); + expect(wire.statusCode, name).toBe(status); + expect(wire.headers.has('content-disposition'), name).toBe(false); + } + expect(f.own).not.toHaveBeenCalled(); + expect(f.retained).not.toHaveBeenCalled(); + }); +}); + +describe('the Origin of a posted action is compared whole', () => { + it('refuses a duplicated Origin header, however its value was joined', async () => { + const f = await fixture('session'); + const form = { csrfToken: f.csrf, idempotencyKey: keyFor('origin') }; + const host = 'https://institution.example.test:3000'; + for (const origin of [ + host + ', https://evil.test', + 'https://evil.test, ' + host, + host + ', ' + host, + host + ',' + host, + ]) { + const wire = await f.run('POST', '/api/account/data-requests/export', form, { origin }); + expect(wire.statusCode, origin).toBe(400); + } + // The list form a header parser could also produce. + const list = await f.run('POST', '/api/account/data-requests/export', form, { + origin: [host, host], + }); + expect(list.statusCode).toBe(400); + expect(f.own).not.toHaveBeenCalled(); + // The exact Origin files. + expect( + (await f.run('POST', '/api/account/data-requests/export', form, { origin: host })).statusCode, + ).toBe(303); + }); + + it('is reached with the joined value only, because Node joins repeated Origin lines with a comma', async () => { + const received = await new Promise<string | undefined>((resolve, reject) => { + const server = createServer((incoming, response) => { + response.end(); + server.close(); + resolve(incoming.headers.origin); + }); + server.listen(0, '127.0.0.1', () => { + const { port } = server.address() as { port: number }; + const socket = connect(port, '127.0.0.1', () => + socket.end( + 'POST / HTTP/1.1\r\nHost: x\r\nOrigin: https://a.test\r\nOrigin: https://b.test\r\nContent-Length: 0\r\nConnection: close\r\n\r\n', + ), + ); + socket.on('error', reject); + socket.resume(); + }); + }); + expect(received).toBe('https://a.test, https://b.test'); + }); +}); diff --git a/frontend/apps/web/src/server/auth/native-operation-contract.ts b/frontend/apps/web/src/server/auth/native-operation-contract.ts index 6b1fab78e..58572e5aa 100644 --- a/frontend/apps/web/src/server/auth/native-operation-contract.ts +++ b/frontend/apps/web/src/server/auth/native-operation-contract.ts @@ -125,7 +125,67 @@ export type NativeOperation = | 'resumeFederationOperation'; version: string; }> - | RetainedConsentOperation; + | RetainedConsentOperation + | OwnDataRequestOperation + | GroupDataRequestOperation; +/** + * ADR-0106 §§ 3, 6, 13: an administrator's data requests in the session context's group. The subject is named only + * by a Membership of that group; no ticket or chunk operation exists, because an administrator never receives a bundle. + */ +export type GroupDataRequestOperation = + | (Readonly<{ kind: 'listDataRequests' }> & Page) + | Readonly<{ kind: 'getDataRequest'; id: string }> + | Readonly<{ + kind: 'createDataExportForSubject' | 'createDataErasureForSubject'; + membershipId: string; + idempotencyKey: string; + }> + | (Readonly<{ kind: 'cancelDataRequest' | 'revokeDataExport'; id: string }> & Write); +/** + * ADR-0106 § 9, ADR-0107 § 4: the person's own data requests in the live session's context group. The ticket of a + * chunk read is a sensitive cursor: it exists only between the download relay and this owner, never in a page or log. + */ +export type OwnDataRequestOperation = + | (Readonly<{ kind: 'listOwnDataRequests' }> & Page) + | Readonly<{ + kind: 'createOwnDataExport' | 'createOwnDataErasure' | 'createOwnAccountClosure'; + idempotencyKey: string; + }> + | (Readonly<{ kind: 'cancelOwnDataRequest' | 'revokeOwnDataExport'; id: string }> & Write) + | Readonly<{ kind: 'mintOwnDataExportTicket'; id: string }> + | Readonly<{ kind: 'readOwnDataExportChunk'; id: string; ticket: string; index: number }>; +/** The closed retained-entry set (ADR-0106 § 9): discovery and the actions in one named group. */ +export type RetainedDataRequestOperation = + | (Readonly<{ kind: 'listRetainedDataRequestScopes' }> & Page) + | (Readonly<{ kind: 'listRetainedDataRequests'; group: string }> & Page) + | Readonly<{ + kind: + | 'createRetainedDataExport' + | 'createRetainedDataErasure' + | 'createRetainedAccountClosure'; + group: string; + idempotencyKey: string; + }> + | (Readonly<{ + kind: 'cancelRetainedDataRequest' | 'revokeRetainedDataExport'; + group: string; + id: string; + }> & + Write) + | Readonly<{ kind: 'mintRetainedDataExportTicket'; group: string; id: string }> + | Readonly<{ + kind: 'readRetainedDataExportChunk'; + group: string; + id: string; + ticket: string; + index: number; + }>; +export type NativeRetainedDataRequestCaller = ( + token: string, + binding: NativeBinding, + operation: RetainedDataRequestOperation, + signal: AbortSignal, +) => Promise<NativeOperationResult>; export type RetainedConsentOperation = | (Readonly<{ kind: 'listOwnConsentScopes' }> & Page) | (Readonly<{ kind: 'listOwnConsentHistory'; membershipId: string }> & Page) diff --git a/frontend/apps/web/src/server/auth/page-contract.ts b/frontend/apps/web/src/server/auth/page-contract.ts index 53a262c40..e3d1566d1 100644 --- a/frontend/apps/web/src/server/auth/page-contract.ts +++ b/frontend/apps/web/src/server/auth/page-contract.ts @@ -7,6 +7,9 @@ import type { LocalizedText, FormLabel, FederationConnection, + OwnDataRequestPage, + RetainedDataRequestScopePage, + SubjectDataRequest, } from '@learnstack/sdk/administration-server'; import type { EntryProjection, NativeReturnPath } from './session-contract.js'; @@ -116,6 +119,48 @@ export type PageFederation = Readonly<{ provider: 'not_read' | 'matches' | 'drift' | 'unavailable'; values: Readonly<{ redirectUri: string; entityId: string; descriptorUrl: string }> | null; }>; +/** + * ADR-0106 § 6: who a request concerns, exactly as the member list shows a member; never a role or a User. The + * Membership is the one whose read named the person, so it has a member page of its own. + */ +export type PageDataRequestSubject = Readonly<{ + membershipId: string; + displayName: string | null; + status: 'Active' | 'Suspended' | 'Revoked'; + organizationScoped: boolean; +}>; +/** + * ADR-0106 §§ 3, 6, 13: an administrator's receipt of a request of the context's group, for one page: status and + * counts, never content. At most 20 of the frozen Membership identifiers are kept, with their count. The subject is + * the member-list projection of a Membership of the snapshot that could be read; `revoked` when every Membership of + * the snapshot is known to be Revoked, so none was read (no member page exists); `null` when no read named it. + */ +export type PageDataRequest = Readonly< + Omit<SubjectDataRequest, 'membershipIds'> & { + membershipIds: readonly string[]; + membershipCount: number; + subject: PageDataRequestSubject | 'revoked' | null; + } +>; +/** The closed outcome a Studio data-request action reports on its request's page after the 303. */ +export type DataRequestAdministrationResult = 'export' | 'erasure' | 'cancelled' | 'revoked'; +/** + * The closed refusals the administrator's data-request routes answer in `errors.$` or `errors.artifact` (409 + * `business_rule_violation`), without their `lockey_` prefix; `unknown` is a reason this release does not name. + */ +export type DataRequestAdministrationRefusal = + | 'request_already_active' + | 'blocked_hold' + | 'blocked_last_administrator' + | 'subject_export_available' + | 'subject_membership_current' + | 'subject_is_requester' + | 'subject_not_admitted' + | 'snapshot_too_large' + | 'data_export_unavailable' + | 'data_request_window_ended' + | 'data_request_not_cancellable' + | 'unknown'; export type PageView = | Readonly<{ kind: 'studio' | 'portal' }> | Readonly<{ kind: 'federation'; federation: PageFederation }> @@ -132,6 +177,16 @@ export type PageView = roles: readonly PageRole[] | null; customFields?: MembershipCustomFields; selectedFieldId?: string | null; + /** + * This member's requests among the newest 100 of the exact current group; present only for a membership + * administrator whose context is the member's group. `items` is null when the list could not be read, and + * `complete` is false when older requests were not read. + */ + dataRequests?: Readonly<{ + items: readonly PageDataRequest[] | null; + complete: boolean; + preparedAt: string; + }>; }> | Readonly<{ kind: 'roles'; roles: readonly PageRole[] }> | Readonly<{ @@ -159,6 +214,28 @@ export type PageView = limit: number; }> | Readonly<{ kind: 'invitation'; invitation: PageInvitation }> + | Readonly<{ + kind: 'data_requests'; + items: readonly PageDataRequest[]; + endCursor: string | null; + hasNextPage: boolean; + /** The instant the page was prepared: a scheduled erasure past `executeAt` reads as due. */ + preparedAt: string; + }> + | Readonly<{ + kind: 'data_request'; + request: PageDataRequest; + result: DataRequestAdministrationResult | null; + preparedAt: string; + }> + | Readonly<{ + /** + * ADR-0106 § 3: the erasure filing for a Revoked Membership, which has no member page. Nothing about the + * Membership is read (the API refuses a Revoked target's detail); `null` when the page was opened without one. + */ + kind: 'data_request_erasure'; + membershipId: string | null; + }> | Readonly<{ kind: 'invitation_policy'; policy: PageInvitationPolicy }> | Readonly<{ kind: 'custom_fields'; definitions: CustomFieldPage; limit: number }> | Readonly<{ @@ -231,6 +308,8 @@ export type NativeActionPage = Readonly< roleLabels?: readonly Pick<PageRole, 'roleId' | 'builtInKey' | 'capabilityScope'>[]; /** ADR-0099: the closed field names to correct, or the settled outcome; never a secret or provider text. */ federation?: Readonly<{ invalid: readonly string[]; outcome: string | null }>; + /** ADR-0106: a data-request action's closed refusal, or null for a generic outcome; never API text. */ + dataRequest?: Readonly<{ refusal: DataRequestAdministrationRefusal | null }>; } | { kind: 'account_change'; csrfToken: string } >; @@ -262,3 +341,33 @@ export type NativeConsentSnapshot = formKeys: readonly string[]; }> | Readonly<{ kind: 'consent_result'; status: number }>; + +/** The closed outcome a data-request action reports on the fixed GET after its 303 (never a replayed POST). */ +export type DataRequestResult = 'export' | 'erasure' | 'closure' | 'cancelled' | 'revoked'; +/** + * ADR-0106 § 9, ADR-0107 §§ 4, 6 and 7: the person's own data-request document. The session mode shows the live + * context's group; the retained mode first lists the groups the entry owner retains, then one named group. + */ +export type NativeDataRequestSnapshot = + | Readonly<{ + kind: 'data_requests'; + mode: 'session' | 'entry'; + /** The session's group, for the explanation only; null in the retained mode. */ + scope: 'tenant' | 'organization' | null; + /** The retained group shown (`tenant` or an organization UUIDv7); null while choosing one. */ + group: string | null; + scopes: RetainedDataRequestScopePage | null; + requests: OwnDataRequestPage | null; + step: 'erasure' | 'closure' | null; + result: DataRequestResult | null; + /** The instant the document was prepared: an erasure past `executeAt` but still scheduled is due. */ + preparedAt: string; + /** + * The retained mode's owner expiry: the instant the entry stops serving this page (at most five minutes from the + * start of sign-in, never extended). Null in the session mode. + */ + entryExpiresAt: string | null; + csrfToken: string; + formKeys: readonly string[]; + }> + | Readonly<{ kind: 'data_request_result'; status: number }>; diff --git a/frontend/apps/web/src/server/auth/page-preload.test.ts b/frontend/apps/web/src/server/auth/page-preload.test.ts index 86907a835..76db3aebd 100644 --- a/frontend/apps/web/src/server/auth/page-preload.test.ts +++ b/frontend/apps/web/src/server/auth/page-preload.test.ts @@ -160,6 +160,10 @@ function fixture(overrides: Partial<Record<NativeOperation['kind'], NativeOperat items: [{ ...member, organizationId, status: 'Active' }], pageInfo: { nextCursor: null, previousCursor: null, hasNext: false, hasPrevious: false }, }), + listDataRequests: success({ + items: [], + pageInfo: { nextCursor: null, previousCursor: null, hasNext: false, hasPrevious: false }, + }), ...overrides, }; const read = vi.fn( @@ -202,7 +206,7 @@ describe('finite native page preparation reads and safe projections', () => { [ '/studio/members/' + memberId, 'member', - ['getMembership', 'listRoles', 'getMembershipCustomFields'], + ['getMembership', 'listRoles', 'getMembershipCustomFields', 'listDataRequests'], ], ['/studio/roles', 'roles', ['listRoles']], ['/studio/invitations', 'invitations', ['listInvitations', 'listInvitableRoles']], @@ -380,6 +384,7 @@ describe('finite native page preparation reads and safe projections', () => { 'getOwnProfile', 'getMembership', 'getMembershipCustomFields', + 'listDataRequests', ]); expect(result.outcome).toMatchObject({ kind: 'ready', diff --git a/frontend/apps/web/src/server/auth/page-preload.ts b/frontend/apps/web/src/server/auth/page-preload.ts index f66c0d4d4..bd68a1453 100644 --- a/frontend/apps/web/src/server/auth/page-preload.ts +++ b/frontend/apps/web/src/server/auth/page-preload.ts @@ -15,12 +15,17 @@ import type { PermissionRegistry, RoleDetail, RoleDirectory, + SubjectDataRequest, + SubjectDataRequestPage, } from '@learnstack/sdk/administration-server'; import type { NativeOperation, NativeOperationResult } from './native-operation-contract.js'; import type { + DataRequestAdministrationResult, NativePageSnapshot, PageCapabilities, + PageDataRequest, + PageDataRequestSubject, PageFailure, PageInvitation, PageMember, @@ -48,13 +53,41 @@ export type NativeDocumentPlan = Readonly<{ | 'invitation_policy' | 'custom_fields' | 'custom_field' - | 'federation'; + | 'federation' + | 'data_requests' + | 'data_request' + | 'data_request_erasure'; id?: string; cursor?: string; limit: number; selectedFieldId?: string | null; consentCursor?: string; + /** The closed outcome a data-request action redirected with; only the request page reads it. */ + result?: DataRequestAdministrationResult | null; + /** The Revoked Membership the erasure page files for; only that page reads it. */ + membershipId?: string | null; }>; +/** ADR-0106 § 6: the data-request list resolves one subject per item, so its page size is fixed. */ +const DATA_REQUEST_PAGE = 20; +/** The member page checks this member's requests among the newest of the group, one page at most. */ +const MEMBER_DATA_REQUEST_PAGE = 100; +/** A page keeps at most this many of a request's frozen Membership identifiers (the API sends up to 256). */ +const KEPT_MEMBERSHIPS = 20; +/** Subject reads run at most this many at a time, so a list neither bursts nor serializes twenty round trips. */ +const SUBJECT_READS = 4; +/** + * ADR-0106 § 3: an administrator files an erasure only once no Membership of the person in the group is current, and + * Revoked is terminal; an erasure that has run leaves every Membership of its snapshot a Revoked tombstone. The API + * refuses a Revoked Membership's detail (and records the refusal), so such a subject is never read. + */ +function revokedSubject(item: Pick<SubjectDataRequest, 'kind' | 'origin' | 'status'>) { + return ( + item.kind === 'erasure' && + (item.origin === 'administrator' || + item.status === 'awaiting_privileged_step' || + item.status === 'completed') + ); +} export function nativeDocumentPlan(target: string, flight: boolean): NativeDocumentPlan { const parsed = bffDocumentQuery(target, flight); @@ -88,23 +121,41 @@ export function nativeDocumentPlan(target: string, flight: boolean): NativeDocum case '/studio/federation': kind = 'federation'; break; + case '/studio/data-requests': + kind = 'data_requests'; + break; + case '/studio/data-requests/erasure': + kind = 'data_request_erasure'; + break; default: if (path.startsWith('/studio/members/')) kind = 'member'; else if (path.startsWith('/studio/roles/')) kind = 'role'; else if (path.startsWith('/studio/invitations/')) kind = 'invitation'; else if (path.startsWith('/studio/custom-fields/')) kind = 'custom_field'; + else if (path.startsWith('/studio/data-requests/')) kind = 'data_request'; else throw new BffSessionError('configuration'); } return Object.freeze({ target: path, kind, - ...(kind === 'member' || kind === 'role' || kind === 'invitation' || kind === 'custom_field' + ...(kind === 'member' || + kind === 'role' || + kind === 'invitation' || + kind === 'custom_field' || + kind === 'data_request' ? { id: path.split('/')[3]! } : {}), ...(parsed.cursor ? { cursor: parsed.cursor } : {}), - limit: kind === 'custom_fields' || kind === 'custom_field' ? 20 : (parsed.limit ?? 20), + limit: + kind === 'custom_fields' || kind === 'custom_field' + ? 20 + : kind === 'data_requests' + ? DATA_REQUEST_PAGE + : (parsed.limit ?? 20), selectedFieldId: parsed.selectedFieldId, consentCursor: parsed.consentCursor, + ...(kind === 'data_request' ? { result: parsed.result } : {}), + ...(kind === 'data_request_erasure' ? { membershipId: parsed.membership } : {}), }); } @@ -195,6 +246,90 @@ export async function preloadPage( canRevoke: inCurrentScope && pending, }; }; + /** + * ADR-0106 § 6: a receipt names its subject by Membership only. Each identifier is read exactly as the member page + * reads it, and only what the member list shows is kept; a refused read leaves the subject unnamed. The names are + * optional: a session failure or cancellation still fails the page, but an overload, a server failure or a transport + * failure only stops the further reads and leaves the remaining subjects unnamed. + */ + const subjects = async ( + identifiers: readonly string[], + ): Promise<ReadonlyMap<string, PageDataRequestSubject | null>> => { + const found = new Map<string, PageDataRequestSubject | null>(); + const pending = [...new Set(identifiers)]; + let stopped = false; + const worker = async () => { + while (!stopped) { + const next = pending.shift(); + if (next === undefined) return; + let result: NativeOperationResult | null = null; + try { + result = await read({ kind: 'getMembership', id: next }); + } catch (error) { + // The first failure stops the other workers taking further identifiers. + stopped = true; + if (error instanceof BffSessionError) throw error; + } + if (result?.kind === 'cancelled') { + stopped = true; + throw new BffSessionError('cancelled'); + } + if ( + result === null || + result.kind === 'transport-error' || + (result.kind === 'api-error' && (result.status === 429 || result.status >= 500)) + ) + stopped = true; + const value = result?.kind === 'success' ? (result.data as MembershipDetail) : null; + found.set( + next, + value && value.membershipId === next + ? { + membershipId: next, + displayName: value.displayName, + status: value.status, + organizationScoped: value.organizationId !== null, + } + : null, + ); + } + }; + // Every worker settles before the page does: no read outlives the preparation that started it. + const settled = await Promise.allSettled( + Array.from({ length: Math.min(SUBJECT_READS, pending.length) }, worker), + ); + for (const outcome of settled) if (outcome.status === 'rejected') throw outcome.reason; + return found; + }; + const projectRequest = ( + item: SubjectDataRequest, + subject: PageDataRequest['subject'], + ): PageDataRequest => { + const { membershipIds, ...receipt } = item; + return { + ...receipt, + membershipIds: membershipIds.slice(0, KEPT_MEMBERSHIPS), + membershipCount: membershipIds.length, + subject, + }; + }; + /** + * One read per distinct first Membership of a request whose subject may still be current; a subject known to be + * Revoked is never read (see `revokedSubject`). Any Membership of a snapshot that another request's read already + * named names its subject too, at no further read. + */ + const named = async (items: readonly SubjectDataRequest[]) => { + const found = await subjects( + items.filter((item) => !revokedSubject(item)).map((item) => item.membershipIds[0]!), + ); + return items.map((item) => + projectRequest( + item, + item.membershipIds.map((id) => found.get(id)).find((subject) => subject) ?? + (revokedSubject(item) ? 'revoked' : null), + ), + ); + }; try { capabilities = await data<PageCapabilities>({ kind: 'getOwnCapabilities' }); const profile = await read({ kind: 'getOwnProfile' }); @@ -364,15 +499,77 @@ export async function preloadPage( kind: 'getMembershipCustomFields', id: plan.id!, }); + // ADR-0106 § 3: requests are filed in the context's group, so only an exact-scope member has them here. + let dataRequests: Extract<PageView, { kind: 'member' }>['dataRequests']; + if (capabilities.canManageMemberships && exact) { + // An unavailable list hides only this section's list; the member's own page stays usable. A session + // failure or cancellation still fails the page; a transport failure only leaves the list unread. + let listed: NativeOperationResult | null = null; + try { + listed = await read({ kind: 'listDataRequests', limit: MEMBER_DATA_REQUEST_PAGE }); + } catch (error) { + if (error instanceof BffSessionError) throw error; + } + if (listed?.kind === 'cancelled') throw new BffSessionError('cancelled'); + const page = listed?.kind === 'success' ? (listed.data as SubjectDataRequestPage) : null; + const subject: PageDataRequestSubject = { + membershipId: member.membershipId, + displayName: member.displayName, + status: member.status, + organizationScoped: member.organizationScoped, + }; + dataRequests = { + items: + page?.items + .filter((item) => item.membershipIds.includes(member.membershipId)) + .map((item) => projectRequest(item, subject)) ?? null, + complete: page !== null && !page.pageInfo.hasNext, + preparedAt: new Date().toISOString(), + }; + } view = { kind: 'member', member, roles, customFields, selectedFieldId: plan.selectedFieldId, + ...(dataRequests ? { dataRequests } : {}), + }; + break; + } + case 'data_requests': { + if (!capabilities.canManageMemberships) throw new PageReadFailure('denied', 403); + const page = await data<SubjectDataRequestPage>({ + kind: 'listDataRequests', + ...(plan.cursor ? { cursor: plan.cursor } : {}), + limit: DATA_REQUEST_PAGE, + }); + view = { + kind: 'data_requests', + items: await named(page.items), + endCursor: + page.pageInfo.nextCursor === null ? null : wrapCursor(page.pageInfo.nextCursor), + hasNextPage: page.pageInfo.hasNext, + preparedAt: new Date().toISOString(), }; break; } + case 'data_request': { + if (!capabilities.canManageMemberships) throw new PageReadFailure('denied', 403); + const item = await data<SubjectDataRequest>({ kind: 'getDataRequest', id: plan.id! }); + view = { + kind: 'data_request', + request: (await named([item]))[0]!, + result: plan.result ?? null, + preparedAt: new Date().toISOString(), + }; + break; + } + case 'data_request_erasure': + // ADR-0106 § 3: no member read; the API decides whether the Membership is Revoked and in this group. + if (!capabilities.canManageMemberships) throw new PageReadFailure('denied', 403); + view = { kind: 'data_request_erasure', membershipId: plan.membershipId ?? null }; + break; case 'custom_fields': { if (!capabilities.canManageCustomFields || organizationId !== null) throw new PageReadFailure('denied', 403); diff --git a/frontend/apps/web/src/server/auth/page-query.ts b/frontend/apps/web/src/server/auth/page-query.ts index ece8e3a7e..e7eb14667 100644 --- a/frontend/apps/web/src/server/auth/page-query.ts +++ b/frontend/apps/web/src/server/auth/page-query.ts @@ -1,4 +1,5 @@ import { BffInputError } from './input-error.js'; +import type { DataRequestAdministrationResult } from './page-contract.js'; import { isNativeReturnPath } from './session-path.js'; export const MAX_TARGET_BYTES = 8192; @@ -99,18 +100,40 @@ export function bffDocumentQuery(target: string, nativeFlight = false) { ? ['cursor', 'limit'] : path === '/portal/profile' || path.startsWith('/studio/members/') ? ['field', 'consentCursor'] - : []; + : // The data-request list resolves one subject name per item, so its page size is fixed. + path === '/studio/data-requests' + ? ['cursor'] + : // A Revoked Membership has no member page: its erasure page is named by the Membership. + path === '/studio/data-requests/erasure' + ? ['membership'] + : path.startsWith('/studio/data-requests/') + ? ['result'] + : []; const fields = bffQuery(target, nativeFlight ? [...allowed, '_rsc'] : allowed); if (fields.has('_rsc')) { if (!/^[\x21-\x7e]{1,128}$/.test(fields.get('_rsc')!)) throw new BffInputError(); fields.delete('_rsc'); } const selectedFieldId = fields.get('field'); - if ( - selectedFieldId !== null && - !/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(selectedFieldId) - ) - throw new BffInputError(); + const membership = fields.get('membership'); + for (const value of [selectedFieldId, membership]) + if ( + value !== null && + !/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value) + ) + throw new BffInputError(); + fields.delete('membership'); const consentCursor = bffCursor(fields.get('consentCursor')); - return Object.freeze({ target: path, selectedFieldId, consentCursor, ...bffPageQuery(fields) }); + const result = fields.get('result'); + if (result !== null && !['export', 'erasure', 'cancelled', 'revoked'].includes(result)) + throw new BffInputError(); + fields.delete('result'); + return Object.freeze({ + target: path, + selectedFieldId, + consentCursor, + result: result as DataRequestAdministrationResult | null, + membership, + ...bffPageQuery(fields), + }); } diff --git a/frontend/apps/web/src/server/auth/page-snapshot-contract.ts b/frontend/apps/web/src/server/auth/page-snapshot-contract.ts index 8d5913320..9dfff33dc 100644 --- a/frontend/apps/web/src/server/auth/page-snapshot-contract.ts +++ b/frontend/apps/web/src/server/auth/page-snapshot-contract.ts @@ -3,6 +3,7 @@ import type { NativeEntrySnapshot, NativePageSnapshot, NativeConsentSnapshot, + NativeDataRequestSnapshot, PageSite, } from './page-contract.js'; @@ -26,6 +27,7 @@ export type NativePageLease = Readonly<{ publish: (page: NativePageSnapshot) => NativePageSnapshot; publishEntry: (entry: NativeEntrySnapshot) => NativeEntrySnapshot; publishConsent: (value: NativeConsentSnapshot) => NativeConsentSnapshot; + publishDataRequest: (value: NativeDataRequestSnapshot) => NativeDataRequestSnapshot; abort: () => void; }>; diff --git a/frontend/apps/web/src/server/auth/page-snapshot-pool.ts b/frontend/apps/web/src/server/auth/page-snapshot-pool.ts index f81d82354..a74af8287 100644 --- a/frontend/apps/web/src/server/auth/page-snapshot-pool.ts +++ b/frontend/apps/web/src/server/auth/page-snapshot-pool.ts @@ -2,6 +2,7 @@ import type { NativeEntrySnapshot, NativePageSnapshot, NativeConsentSnapshot, + NativeDataRequestSnapshot, } from './page-contract.js'; import type { NativePageLease } from './page-snapshot-contract.js'; @@ -178,7 +179,13 @@ export function createPageSnapshotPool() { return unavailable(); } }; - const publish = <T extends NativePageSnapshot | NativeEntrySnapshot | NativeConsentSnapshot>( + const publish = < + T extends + | NativePageSnapshot + | NativeEntrySnapshot + | NativeConsentSnapshot + | NativeDataRequestSnapshot, + >( value: T, ): T => { response.assertCurrent(); @@ -245,6 +252,9 @@ export function createPageSnapshotPool() { publishConsent(value: NativeConsentSnapshot) { return publish(value); }, + publishDataRequest(value: NativeDataRequestSnapshot) { + return publish(value); + }, abort, }); active.add(lease); diff --git a/frontend/apps/web/src/server/auth/request-runtime.ts b/frontend/apps/web/src/server/auth/request-runtime.ts index 51e2f8a47..d195e2780 100644 --- a/frontend/apps/web/src/server/auth/request-runtime.ts +++ b/frontend/apps/web/src/server/auth/request-runtime.ts @@ -2,14 +2,22 @@ import { AsyncLocalStorage } from 'node:async_hooks'; import type { EventEmitter } from 'node:events'; import type { IncomingHttpHeaders, ServerResponse } from 'node:http'; -import type { NativeConsentResponseLease } from './consent-response-contract.js'; +import type { + NativeConsentResponseLease, + NativeDataRequestResponseLease, +} from './consent-response-contract.js'; import { canonicalAddress, normalizeHost, validTarget } from '../ingress.js'; import type { IngressContext } from '../ingress.js'; import type { PublicAdmissionHolder, PublicAdmissionRead } from '../public-admission-runtime.js'; import { BFF_POST_PATHS, bffActivity } from './http-input.js'; -import { bffActionDocumentTarget } from './http-paths.js'; +import { bffActionDocumentTarget, DATA_REQUEST_DOCUMENT_PATHS } from './http-paths.js'; import type { InvitationResponseLease } from './invitation-session.js'; -import type { NativePageSnapshot, NativeConsentSnapshot, PageSite } from './page-contract.js'; +import type { + NativePageSnapshot, + NativeConsentSnapshot, + NativeDataRequestSnapshot, + PageSite, +} from './page-contract.js'; import { protectPageResponse } from './page-response.js'; import type { NativePagePreparation, NativeSnapshotTicket } from './page-snapshot-contract.js'; import { createPageSnapshotPool, SnapshotAdmissionError } from './page-snapshot-pool.js'; @@ -460,6 +468,48 @@ export function createBffRequestRuntime(admission?: Pick<PublicAdmissionHolder, }, }); }, + /** ADR-0106 § 9: one snapshot credit for the data-request document, download or action. */ + nativeDataRequestResponse(binding: IngressContext): NativeDataRequestResponseLease { + const frame = current(binding, 'pending'); + const path = binding.target.split('?', 1)[0]!; + if ( + !DATA_REQUEST_DOCUMENT_PATHS.includes(path) || + !frame.guarded || + frame.outputStarted || + frame.lease + ) + return unavailable(); + return Object.freeze({ + signal: frame.controller.signal, + cleaned: frame.cleaned, + pin(assert: () => void, owner: object, expiresInMs: number) { + frame.assertCurrent(); + if (frame.outputStarted || frame.lease) return unavailable(); + const result = pool.reserve(owner, { + signal: frame.controller.signal, + cleaned: frame.cleaned, + assertCurrent: frame.assertCurrent, + invalidate: frame.invalidate, + publishPage() { + return unavailable(); + }, + }); + frame.lease = result; + result.lease.pin(() => { + try { + assert(); + return true; + } catch { + return false; + } + }, expiresInMs); + }, + publish(value: NativeDataRequestSnapshot) { + if (!frame.lease) return unavailable(); + return frame.lease.lease.publishDataRequest(value); + }, + }); + }, nativeResponse(binding: IngressContext): InvitationResponseLease { const frame = current(binding, 'pending'); if (!admission || !frame.guarded || frame.outputStarted || frame.lease) return unavailable(); diff --git a/frontend/apps/web/src/server/auth/session-contract.ts b/frontend/apps/web/src/server/auth/session-contract.ts index cee492a3f..917b57245 100644 --- a/frontend/apps/web/src/server/auth/session-contract.ts +++ b/frontend/apps/web/src/server/auth/session-contract.ts @@ -1,4 +1,7 @@ -import type { NativeConsentResponseLease } from './consent-response-contract.js'; +import type { + NativeConsentResponseLease, + NativeDataRequestResponseLease, +} from './consent-response-contract.js'; import type { InvitationCommand, InvitationContinuation, @@ -15,7 +18,10 @@ import type { NativeInvitationApi } from './native-invitation-contract.js'; import type { NativeAdministrationCaller, NativeRetainedConsentCaller, + NativeRetainedDataRequestCaller, + OwnDataRequestOperation, RetainedConsentOperation, + RetainedDataRequestOperation, NativeOperation, NativeOperationResult, } from './native-operation-contract.js'; @@ -100,6 +106,8 @@ export type NativeReturnPath = | `/studio/invitations/${string}` | '/studio/invitation-policy' | '/studio/federation' + | '/studio/data-requests' + | `/studio/data-requests/${string}` | '/studio/custom-fields' | `/studio/custom-fields/${string}` | '/studio/roles' @@ -192,6 +200,17 @@ export class BffSessionError extends Error { } } +/** + * The pinned owner's proof, for a live session whether its group is tenant-wide, for the retained entry the wall + * clock instant (epoch milliseconds) at which the entry ends, and in both modes how long the pinned response may + * live (the owner's remaining lifetime, exactly the bound the pin enforces); never an identifier. + */ +export type DataRequestRetention = Readonly<{ + csrfToken: string; + scope: 'tenant' | 'organization' | null; + expiresAt: number | null; + remainingMs: number; +}>; export type SessionDependencies = Readonly<{ provider: SessionProvider; account: ( @@ -203,6 +222,8 @@ export type SessionDependencies = Readonly<{ administration: NativeAdministrationCaller; invitations?: NativeInvitationApi; retainedConsent?: NativeRetainedConsentCaller; + /** ADR-0106 § 9: the retained data-request entry's own caller; absent means that entry is unavailable. */ + retainedDataRequest?: NativeRetainedDataRequestCaller; /** ADR-0099: the server-side sign-in option read and the BFF-only test owner; absent means federation is off. */ publicSignIn?: ( binding: NativeBinding, @@ -332,6 +353,25 @@ export interface BffSessionStore { csrf: string, signal?: AbortSignal, ): Promise<NativeOperationResult>; + retainDataRequests( + binding: SessionBinding, + lease: NativeDataRequestResponseLease, + mode: 'session' | 'entry', + ): DataRequestRetention; + ownDataRequest( + binding: SessionBinding, + source: string, + operation: OwnDataRequestOperation, + csrf: string, + signal?: AbortSignal, + ): Promise<NativeOperationResult>; + retainedDataRequest( + binding: SessionBinding, + source: string, + operation: RetainedDataRequestOperation, + csrf: string, + signal?: AbortSignal, + ): Promise<NativeOperationResult>; peek(binding: SessionBinding): SessionProjection | null; admit( binding: SessionBinding, diff --git a/frontend/apps/web/src/server/auth/session-path.ts b/frontend/apps/web/src/server/auth/session-path.ts index 0722e8fdb..8233140c5 100644 --- a/frontend/apps/web/src/server/auth/session-path.ts +++ b/frontend/apps/web/src/server/auth/session-path.ts @@ -1,5 +1,13 @@ import type { NativeReturnPath } from './session-contract.js'; +const UUID_V7 = '[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}'; +const DATA_REQUEST_ERASURE = new RegExp( + '^/studio/data-requests/erasure\\?membership=(' + UUID_V7 + ')$', +); +const DATA_REQUEST_RESULT = new RegExp( + '^/studio/data-requests/' + UUID_V7 + '\\?result=(?:export|erasure|cancelled|revoked)$', +); + /** Canonical local screens only; queries, fragments and arbitrary paths never return authority. */ export function isNativeReturnPath(value: unknown): value is NativeReturnPath { return ( @@ -13,11 +21,40 @@ export function isNativeReturnPath(value: unknown): value is NativeReturnPath { '/studio/invitations', '/studio/invitation-policy', '/studio/federation', + '/studio/data-requests', + '/studio/data-requests/erasure', '/portal', '/portal/profile', ].includes(value) || - /^\/studio\/(?:members|roles|invitations|custom-fields)\/[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test( + /^\/studio\/(?:members|roles|invitations|custom-fields|data-requests)\/[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test( value, )) ); } + +/** + * ADR-0106 § 3: the erasure page of one Revoked Membership. A Revoked Membership has no member page, so its identifier + * travels in the one query this page admits; the caller supplies a canonical UUIDv7. + */ +export function dataRequestErasureTarget(membershipId: string): string { + const target = '/studio/data-requests/erasure?membership=' + membershipId; + if (!DATA_REQUEST_ERASURE.test(target)) throw new Error('Erasure target unavailable'); + return target; +} + +/** + * The fixed GET a native action document recovers to: a canonical screen, or the erasure page of one Membership, + * the only protected document whose recovery needs its query. + */ +export function isBffRecoveryTarget(value: unknown): value is string { + return ( + isNativeReturnPath(value) || (typeof value === 'string' && DATA_REQUEST_ERASURE.test(value)) + ); +} + +/** A same-host 303 the native protocol may answer: a recovery target, or a data-request page with its closed result. */ +export function isBffRedirectTarget(value: unknown): value is string { + return ( + isBffRecoveryTarget(value) || (typeof value === 'string' && DATA_REQUEST_RESULT.test(value)) + ); +} diff --git a/frontend/apps/web/src/server/auth/session-runtime.test.ts b/frontend/apps/web/src/server/auth/session-runtime.test.ts index 7fb4e1740..684fb6b28 100644 --- a/frontend/apps/web/src/server/auth/session-runtime.test.ts +++ b/frontend/apps/web/src/server/auth/session-runtime.test.ts @@ -32,7 +32,7 @@ describe('native BFF owner composition', () => { 'assert.deepEqual([descriptor.enumerable, descriptor.writable, descriptor.configurable], [false, false, false]);', 'assert.ok(Object.isFrozen(descriptor.value));', 'assert.ok(Object.isFrozen(descriptor.value.store));', - 'assert.deepEqual(Object.keys(descriptor.value.store).sort(), ["openInvitation","invitation","retainInvitation","invitationEntry","retainConsent","retainedConsent","start","complete","completeCallback","signInOption","startFederationTest","entry","create","select","switchScope","discardEntry","operate","preparePage","peek","admit","signout","consumeLogout","stop"].sort());', + 'assert.deepEqual(Object.keys(descriptor.value.store).sort(), ["openInvitation","invitation","retainInvitation","invitationEntry","retainConsent","retainedConsent","retainDataRequests","ownDataRequest","retainedDataRequest","start","complete","completeCallback","signInOption","startFederationTest","entry","create","select","switchScope","discardEntry","operate","preparePage","peek","admit","signout","consumeLogout","stop"].sort());', 'assert.equal(globalThis[Symbol.for("learnstack.public-admission.v1")], undefined);', 'const login = await descriptor.value.store.start({ host: "institution.example.test:3000", source: "203.0.113.1", returnPath: "/studio" });', 'assert.equal(calls, 1);', diff --git a/frontend/apps/web/src/server/auth/session-runtime.ts b/frontend/apps/web/src/server/auth/session-runtime.ts index 91d498e3a..b7c7c7a6a 100644 --- a/frontend/apps/web/src/server/auth/session-runtime.ts +++ b/frontend/apps/web/src/server/auth/session-runtime.ts @@ -44,6 +44,9 @@ export function installBffSessionRuntime( preparePage: owner.preparePage.bind(owner), retainConsent: owner.retainConsent.bind(owner), retainedConsent: owner.retainedConsent.bind(owner), + retainDataRequests: owner.retainDataRequests.bind(owner), + ownDataRequest: owner.ownDataRequest.bind(owner), + retainedDataRequest: owner.retainedDataRequest.bind(owner), peek: owner.peek.bind(owner), admit: owner.admit.bind(owner), signout: owner.signout.bind(owner), diff --git a/frontend/apps/web/src/server/auth/session-store.ts b/frontend/apps/web/src/server/auth/session-store.ts index bac4b1a90..fa01a2d2e 100644 --- a/frontend/apps/web/src/server/auth/session-store.ts +++ b/frontend/apps/web/src/server/auth/session-store.ts @@ -5,7 +5,10 @@ import type { OwnMembershipProfile } from '@learnstack/sdk/administration-server import type { VerifiedLogoutToken } from './backchannel-contract.js'; import { BackchannelState, matchesProviderLogout } from './backchannel-state.js'; import type { ProviderLogoutTarget } from './backchannel-state.js'; -import type { NativeConsentResponseLease } from './consent-response-contract.js'; +import type { + NativeConsentResponseLease, + NativeDataRequestResponseLease, +} from './consent-response-contract.js'; import { canonicalAddress, normalizeHost } from '../ingress.js'; import { openEntryCursor, sealEntryCursor } from './entry-cursor.js'; import { FEDERATION_ALIAS } from './federation-alias.js'; @@ -18,7 +21,7 @@ import type { InvitationCommand, } from './invitation-session.js'; import { NativeApiError } from './native-contract.js'; -import type { NativeScope, NativeSelf, SelfContexts } from './native-contract.js'; +import type { NativeBinding, NativeScope, NativeSelf, SelfContexts } from './native-contract.js'; import type { NativeInvitationInspection, NativeInvitationResult, @@ -27,7 +30,9 @@ import { NativeInvitationError } from './native-invitation-contract.js'; import type { NativeOperation, NativeOperationResult, + OwnDataRequestOperation, RetainedConsentOperation, + RetainedDataRequestOperation, } from './native-operation-contract.js'; import { nativeContextPage } from './native-session-client.js'; import type { NativeEntrySnapshot, NativePageSnapshot, ScopeChoices } from './page-contract.js'; @@ -47,6 +52,7 @@ import type { FederationTestOutcome, AccountWitness, BffSessionStore, + DataRequestRetention, LoginCompletion, LoginStart, EntryProjection, @@ -359,7 +365,10 @@ export class InMemoryBffSessionStore implements BffSessionStore { | 'invitations' | 'custom_fields' | 'custom_revisions' - | 'consent_history', + | 'consent_history' + | 'data_requests' + | 'data_request_scopes' + | 'group_data_requests', ) { return { ...this.#cursorBinding(entry), purpose }; } @@ -371,7 +380,10 @@ export class InMemoryBffSessionStore implements BffSessionStore { | 'invitations' | 'custom_fields' | 'custom_revisions' - | 'consent_history', + | 'consent_history' + | 'data_requests' + | 'data_request_scopes' + | 'group_data_requests', cursor: string, ) { entry.pageCursorKey ??= randomBytes(32); @@ -385,7 +397,10 @@ export class InMemoryBffSessionStore implements BffSessionStore { | 'invitations' | 'custom_fields' | 'custom_revisions' - | 'consent_history', + | 'consent_history' + | 'data_requests' + | 'data_request_scopes' + | 'group_data_requests', cursor: string | undefined, ) { if (cursor === undefined) return undefined; @@ -514,7 +529,9 @@ export class InMemoryBffSessionStore implements BffSessionStore { ? 'custom_fields' : plan.kind === 'custom_field' ? 'custom_revisions' - : 'members', + : plan.kind === 'data_requests' + ? 'group_data_requests' + : 'members', plan.cursor, ) : undefined; @@ -720,7 +737,9 @@ export class InMemoryBffSessionStore implements BffSessionStore { ? 'custom_fields' : plan!.kind === 'custom_field' ? 'custom_revisions' - : 'members', + : plan!.kind === 'data_requests' + ? 'group_data_requests' + : 'members', cursor, ), this.#dependencies.federationIssuer, @@ -2383,6 +2402,7 @@ export class InMemoryBffSessionStore implements BffSessionStore { 'getOwnFieldConsent', 'listOwnConsentScopes', 'listOwnConsentHistory', + 'listOwnDataRequests', ].includes(captured.kind); if (!read && !bffSecretEquals(csrf, entry.csrf)) throw new BffSessionError('csrf'); return this.#bounded(entry, signal, async (current) => { @@ -2431,7 +2451,8 @@ export class InMemoryBffSessionStore implements BffSessionStore { this.#checkSource(binding.host, source); const owner = this.#findEntry(binding); this.#entryProof(owner, csrf); - if (!this.#dependencies.retainedConsent) throw new BffSessionError('configuration'); + const retained = this.#dependencies.retainedConsent; + if (!retained) throw new BffSessionError('configuration'); let captured: RetainedConsentOperation; try { const raw = JSON.stringify(operation); @@ -2447,6 +2468,26 @@ export class InMemoryBffSessionStore implements BffSessionStore { } catch { throw new BffSessionError('configuration'); } + return this.#retained(owner, binding, source, signal, (token, native, current) => + retained(token, native, captured, current), + ); + } + + /** + * ADR-0106 § 9: the retained entry's one shared call. The entry owner's credential, refreshed under ADR-0099's + * host binding when it nears expiry, performs exactly one closed operation and must still be the owner's after it. + */ + async #retained( + owner: Owner, + binding: SessionBinding, + source: string, + signal: AbortSignal | undefined, + call: ( + token: string, + native: NativeBinding, + signal: AbortSignal, + ) => Promise<NativeOperationResult>, + ): Promise<NativeOperationResult> { let refreshed: ProviderCredentials | undefined; try { return await this.#bounded(owner, signal, async (current) => { @@ -2482,12 +2523,7 @@ export class InMemoryBffSessionStore implements BffSessionStore { await this.#wait(owner.refresh, current); } const credentials = owner.credentials!; - const result = await this.#dependencies.retainedConsent!( - credentials.accessToken, - this.#binding(binding, source), - captured, - current, - ); + const result = await call(credentials.accessToken, this.#binding(binding, source), current); this.#assertSignal(current); this.#assert(owner, 'entry'); if (owner.credentials !== credentials) throw new BffSessionError('response'); @@ -2499,6 +2535,157 @@ export class InMemoryBffSessionStore implements BffSessionStore { } } + /** + * ADR-0106 § 9 and ADR-0107 § 4: pins one data-request response to its owner. The live session mode holds the + * active owner (its context's group); the retained mode holds the entry owner, exactly as the consent entry does. + */ + retainDataRequests( + binding: SessionBinding, + lease: NativeDataRequestResponseLease, + mode: 'session' | 'entry', + ): DataRequestRetention { + if (mode === 'entry') { + const owner = this.#findEntry(binding); + // The entry's deadline is fixed at sign-in and never extended: the response ends with it. + const ends = Math.min(owner.deadline, owner.credentials!.refreshExpiresAt); + const remainingMs = Math.max(1, ends - this.#now()); + lease.pin( + () => { + this.#assert(owner, 'entry'); + if (lease.signal.aborted) throw new BffSessionError('revoked'); + }, + owner, + remainingMs, + ); + void this.#tracked(owner, () => lease.cleaned); + // The same bound on the wall clock, as the entry projection states it: the page tells the person when it ends. + return Object.freeze({ + csrfToken: owner.csrf, + scope: null, + expiresAt: Math.round(owner.utcOffset + ends), + remainingMs, + }); + } + const owner = this.#find(binding); + if (!owner?.identity) throw new BffSessionError('revoked'); + const remainingMs = Math.max(1, this.#effective(owner) - this.#now()); + lease.pin( + () => { + this.#assert(owner, 'active'); + if (!this.#live(owner) || lease.signal.aborted) throw new BffSessionError('revoked'); + }, + owner, + remainingMs, + ); + void this.#tracked(owner, () => lease.cleaned); + return Object.freeze({ + csrfToken: owner.csrf, + scope: owner.identity.organizationId === null ? 'tenant' : 'organization', + expiresAt: null, + remainingMs, + }); + } + /** The live session's own data requests; a list cursor is sealed to this owner and purpose. */ + async ownDataRequest( + binding: SessionBinding, + source: string, + operation: OwnDataRequestOperation, + csrf: string, + signal?: AbortSignal, + ): Promise<NativeOperationResult> { + this.#checkSource(binding.host, source); + const owner = this.#find(binding); + if (!owner) throw new BffSessionError('revoked'); + if (!bffSecretEquals(csrf, owner.csrf)) throw new BffSessionError('csrf'); + const listing = operation.kind === 'listOwnDataRequests'; + const captured: OwnDataRequestOperation = + listing && operation.cursor !== undefined + ? { + ...operation, + cursor: this.#openPageCursor(owner, 'data_requests', operation.cursor), + } + : operation; + const result = await this.operate(binding, source, captured, csrf, signal); + return listing ? this.#sealedPage(owner, 'data_requests', result) : result; + } + /** The retained entry's closed data-request set (ADR-0106 § 9), on the entry owner's credential. */ + async retainedDataRequest( + binding: SessionBinding, + source: string, + operation: RetainedDataRequestOperation, + csrf: string, + signal?: AbortSignal, + ): Promise<NativeOperationResult> { + this.#checkSource(binding.host, source); + const owner = this.#findEntry(binding); + this.#entryProof(owner, csrf); + const retained = this.#dependencies.retainedDataRequest; + if (!retained) throw new BffSessionError('configuration'); + let captured: RetainedDataRequestOperation; + try { + const raw = JSON.stringify(operation); + if (Buffer.byteLength(raw) > 16 * 1024) throw new Error(); + captured = JSON.parse(raw) as RetainedDataRequestOperation; + if ( + !captured || + ![ + 'listRetainedDataRequestScopes', + 'listRetainedDataRequests', + 'createRetainedDataExport', + 'createRetainedDataErasure', + 'createRetainedAccountClosure', + 'cancelRetainedDataRequest', + 'revokeRetainedDataExport', + 'mintRetainedDataExportTicket', + 'readRetainedDataExportChunk', + ].includes(captured.kind) + ) + throw new Error(); + } catch { + throw new BffSessionError('configuration'); + } + const purpose = + captured.kind === 'listRetainedDataRequestScopes' + ? 'data_request_scopes' + : captured.kind === 'listRetainedDataRequests' + ? 'data_requests' + : undefined; + if ( + purpose && + (captured.kind === 'listRetainedDataRequestScopes' || + captured.kind === 'listRetainedDataRequests') && + captured.cursor !== undefined + ) + captured = { ...captured, cursor: this.#openPageCursor(owner, purpose, captured.cursor) }; + const call = captured; + const result = await this.#retained(owner, binding, source, signal, (token, native, current) => + retained(token, native, call, current), + ); + return purpose ? this.#sealedPage(owner, purpose, result) : result; + } + /** Replaces a page's raw API continuation with one sealed to the owner and purpose. */ + #sealedPage( + owner: Owner, + purpose: 'data_requests' | 'data_request_scopes', + result: NativeOperationResult, + ): NativeOperationResult { + if (result.kind !== 'success') return result; + const data = result.data as Readonly<{ + pageInfo: Readonly<{ nextCursor: string | null }> & Record<string, unknown>; + }>; + const next = data.pageInfo.nextCursor; + return { + ...result, + data: { + ...data, + pageInfo: { + ...data.pageInfo, + nextCursor: next === null ? null : this.#wrapPageCursor(owner, purpose, next), + }, + }, + } as NativeOperationResult; + } + peek(binding: SessionBinding): SessionProjection | null { const entry = this.#find(binding); return entry ? this.#project(entry) : null; diff --git a/frontend/apps/web/src/server/auth/store-page-preload.test.ts b/frontend/apps/web/src/server/auth/store-page-preload.test.ts index 588b18017..e373ad967 100644 --- a/frontend/apps/web/src/server/auth/store-page-preload.test.ts +++ b/frontend/apps/web/src/server/auth/store-page-preload.test.ts @@ -432,4 +432,84 @@ describe('Store page preparation through the actual private native port', () => expect(f.requestRuntime.snapshotCounts().active).toBe(4); expect(f.store.peek(active.binding)?.state).toBe('authenticated'); }); + + it('seals the data-request list cursor under its own purpose and refuses the member purpose (ADR-0106)', async () => { + const f = fixture(); + const active = await f.login(); + const raw = Buffer.from('data-requests:' + 'b'.repeat(64)).toString('base64url'); + const rawMembers = Buffer.from('members:' + 'c'.repeat(64)).toString('base64url'); + const original = f.administration.getMockImplementation()!; + const listed = (nextCursor: string) => ({ + kind: 'success' as const, + status: 200 as const, + etag: null, + location: null, + replayed: false, + data: { + items: [], + pageInfo: { nextCursor, previousCursor: null, hasNext: true, hasPrevious: false }, + }, + }); + f.administration.mockImplementation(async (...args) => + args[2].kind === 'listDataRequests' + ? listed(raw) + : args[2].kind === 'listMemberships' + ? listed(rawMembers) + : original(...args), + ); + const first = page(await document(f, active.binding, { target: '/studio/data-requests' }).work); + if (first.outcome.kind !== 'ready' || first.outcome.view.kind !== 'data_requests') + throw new Error('Expected data-request page'); + const cursor = first.outcome.view.endCursor!; + expect(cursor).toMatch(/^[A-Za-z0-9_-]+$/); + expect(JSON.stringify(first)).not.toContain(raw); + const members = page(await document(f, active.binding, { target: '/studio/members' }).work); + if (members.outcome.kind !== 'ready' || members.outcome.view.kind !== 'members') + throw new Error('Expected member page'); + await document(f, active.binding, { target: '/studio/data-requests?cursor=' + cursor }).work; + expect(f.administration).toHaveBeenLastCalledWith( + expect.any(String), + expect.any(Object), + { kind: 'listDataRequests', limit: 20, cursor: raw }, + expect.any(AbortSignal), + ); + const calls = f.administration.mock.calls.length; + await expect( + document(f, active.binding, { + target: '/studio/data-requests?cursor=' + members.outcome.view.endCursor!, + }).work, + ).rejects.toThrow(); + await expect( + document(f, active.binding, { target: '/studio/members?cursor=' + cursor }).work, + ).rejects.toThrow(); + expect(f.administration).toHaveBeenCalledTimes(calls); + }); + + it("prepares a Revoked Membership's erasure page with its one query and no member read (ADR-0106 § 3)", async () => { + const f = fixture(); + const active = await f.login(); + const membershipId = '019a154b-0000-7000-8000-000000000011'; + const prepared = page( + await document(f, active.binding, { + target: '/studio/data-requests/erasure?membership=' + membershipId, + }).work, + ); + expect(prepared.target).toBe('/studio/data-requests/erasure'); + expect(prepared.outcome).toEqual({ + kind: 'ready', + view: { kind: 'data_request_erasure', membershipId }, + }); + expect(prepared.formKeys).toHaveLength(32); + expect(f.administration.mock.calls.map((call) => call[2].kind)).toEqual([ + 'getOwnCapabilities', + 'getOwnProfile', + ]); + const calls = f.administration.mock.calls.length; + for (const target of [ + '/studio/data-requests/erasure?membership=' + membershipId.toUpperCase(), + '/studio/data-requests/erasure?membership=' + membershipId + '&cursor=YWJj', + ]) + await expect(document(f, active.binding, { target }).work).rejects.toThrow(); + expect(f.administration).toHaveBeenCalledTimes(calls); + }); }); diff --git a/frontend/apps/web/src/server/ingress.test.ts b/frontend/apps/web/src/server/ingress.test.ts index f85cccf07..3ba622b7d 100644 --- a/frontend/apps/web/src/server/ingress.test.ts +++ b/frontend/apps/web/src/server/ingress.test.ts @@ -27,6 +27,14 @@ import { } from './ingress'; const secret = randomBytes(32).toString('base64url'); +/** The person's data-request actions, as POST targets of the native handler. */ +const PERSON_DATA_REQUEST_POSTS = [ + ...['export', 'erasure', 'closure', 'cancel', 'revoke', 'download'].flatMap((action) => [ + '/api/account/data-requests/' + action, + '/api/auth/entry/data-requests/' + action, + ]), + '/api/auth/entry/data-requests', +]; const context = { host: 'tenant.example:3000', peer: '127.0.0.1', @@ -57,6 +65,9 @@ describe('captured ingress provenance', () => { '/studio/roles/019a154b-0000-7000-8000-000000000022', '/portal/profile', '/api/auth/entry', + // The person's own data-request page is credentialed: it is served on the native authority only. + '/account/data', + '/account/data?group=tenant&result=export', ]) { const request = make(target); expect(admitIncomingRequest(request, secret, true)).toBe(false); @@ -73,6 +84,7 @@ describe('captured ingress provenance', () => { '/api/studio/role-grants', '/api/studio/role-manifest-adoption', '/api/account/profile', + ...PERSON_DATA_REQUEST_POSTS, ]) expect(admitIncomingRequest(make(target, 'POST'), secret, true)).toBe(false); const publicRead = make('/en/courses'); @@ -97,6 +109,22 @@ describe('captured ingress provenance', () => { expect(verifyProvenance(String(request.headers[INGRESS_HEADER]), secret)?.host).toBe( normalizeHost(host), ); + // The person's data-request page and its fixed actions are admitted on that authority, with the same proof. + for (const [method, target] of [ + ['GET', '/account/data'], + ['GET', '/account/data?group=tenant&result=export'], + ...PERSON_DATA_REQUEST_POSTS.map((path) => ['POST', path] as const), + ] as const) { + const document = new IncomingMessage(socket); + document.rawHeaders = ['Host', host]; + document.headers = { host, 'content-length': '12' }; + document.method = method; + document.url = target; + expect(admitIncomingRequest(document, secret, true), method + ' ' + target).toBe(true); + expect( + verifyProvenance(String(document.headers[INGRESS_HEADER]), secret, { method, target }), + ).toMatchObject({ host: normalizeHost(host), peer: '127.0.0.1', method, target }); + } }, ); it.each([ diff --git a/frontend/apps/web/src/server/ingress.ts b/frontend/apps/web/src/server/ingress.ts index 4ea195b1e..d7796b3eb 100644 --- a/frontend/apps/web/src/server/ingress.ts +++ b/frontend/apps/web/src/server/ingress.ts @@ -202,6 +202,7 @@ export function admitIncomingRequest( path?.startsWith('/api/auth/') || (path !== undefined && BFF_POST_PATHS.includes(path)) || path === '/account/consents' || + path === '/account/data' || path === '/invitations' || path === '/invitations/confirm' || path === '/studio' || @@ -437,6 +438,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/administration-ui-fixture.ts b/frontend/apps/web/src/test/administration-ui-fixture.ts index c8aca2132..cc5deede0 100644 --- a/frontend/apps/web/src/test/administration-ui-fixture.ts +++ b/frontend/apps/web/src/test/administration-ui-fixture.ts @@ -40,25 +40,32 @@ export function administrationSnapshot( ): NativePageSnapshot { return { target: - view.kind === 'invitation' - ? `/studio/invitations/${view.invitation.invitationId}` - : view.kind === 'invitations' - ? '/studio/invitations' - : view.kind === 'invitation_policy' - ? '/studio/invitation-policy' - : view.kind === 'federation' - ? '/studio/federation' - : view.kind === 'member' - ? (('/studio/members/' + view.member.membershipId) as `/studio/members/${string}`) - : view.kind === 'role' - ? (('/studio/roles/' + view.role.roleId) as `/studio/roles/${string}`) - : view.kind === 'profile' - ? '/portal/profile' - : view.kind === 'members' - ? '/studio/members' - : view.kind === 'roles' - ? '/studio/roles' - : (('/' + view.kind) as '/studio' | '/portal'), + view.kind === 'data_request' + ? `/studio/data-requests/${view.request.id}` + : view.kind === 'data_requests' + ? '/studio/data-requests' + : view.kind === 'invitation' + ? `/studio/invitations/${view.invitation.invitationId}` + : view.kind === 'invitations' + ? '/studio/invitations' + : view.kind === 'invitation_policy' + ? '/studio/invitation-policy' + : view.kind === 'federation' + ? '/studio/federation' + : view.kind === 'member' + ? (('/studio/members/' + + view.member.membershipId) as `/studio/members/${string}`) + : view.kind === 'role' + ? (('/studio/roles/' + view.role.roleId) as `/studio/roles/${string}`) + : view.kind === 'profile' + ? '/portal/profile' + : view.kind === 'members' + ? '/studio/members' + : view.kind === 'roles' + ? '/studio/roles' + : view.kind === 'data_request_erasure' + ? '/studio/data-requests/erasure' + : (('/' + view.kind) as '/studio' | '/portal'), site: { displayName: 'Institution', defaultLocale: 'en', diff --git a/frontend/apps/web/src/test/bff-administration-routes.test.ts b/frontend/apps/web/src/test/bff-administration-routes.test.ts index 7ce323802..13a1451d0 100644 --- a/frontend/apps/web/src/test/bff-administration-routes.test.ts +++ b/frontend/apps/web/src/test/bff-administration-routes.test.ts @@ -155,6 +155,13 @@ const cases = [ { kind: 'changeMembershipStatus', id: member, status: 'Suspended' }, '/studio/members/' + member, ], + // ADR-0106 § 3: a Revoked Membership has no member page; the revocation leads to its erasure page. + [ + '/api/studio/membership-status', + { membershipId: member, status: 'Revoked' }, + { kind: 'changeMembershipStatus', id: member, status: 'Revoked' }, + '/studio/data-requests/erasure?membership=' + member, + ], [ '/api/studio/role-grants', { roleId: role, grants: '[{"scope":"Tenant","key":"identity.role.admin"}]' }, @@ -214,13 +221,20 @@ describe('exact native administration forms', () => { expect(await response!.text()).not.toContain('private-'); }, ); - it('a terminal status returns to the fixed member directory', () => { - expect( - bffAdministrationForm( - '/api/studio/membership-status', - new URLSearchParams({ ...write, membershipId: member, status: 'Revoked' }), - ).destination, - ).toBe('/studio/members'); + it('a terminal status settles on the erasure page and recovers to the fixed member directory', () => { + const form = bffAdministrationForm( + '/api/studio/membership-status', + new URLSearchParams({ ...write, membershipId: member, status: 'Revoked' }), + ); + expect(form.destination).toBe('/studio/members'); + expect(form.settledDestination).toBe('/studio/data-requests/erasure?membership=' + member); + for (const status of ['Active', 'Suspended']) + expect( + bffAdministrationForm( + '/api/studio/membership-status', + new URLSearchParams({ ...write, membershipId: member, status }), + ).settledDestination, + ).toBeUndefined(); }); it.each(cases)( '%s refuses missing, duplicate and unknown fields without API work', diff --git a/frontend/apps/web/src/test/bff-auth-admission.test.ts b/frontend/apps/web/src/test/bff-auth-admission.test.ts index b1a9f8157..c543b9316 100644 --- a/frontend/apps/web/src/test/bff-auth-admission.test.ts +++ b/frontend/apps/web/src/test/bff-auth-admission.test.ts @@ -16,6 +16,7 @@ import { bffQuery, bffRoute, } from '../server/auth/http-input'; +import { DATA_REQUEST_DOCUMENT_PATHS } from '../server/auth/http-paths'; const postPaths = [ '/api/auth/invitation/capture', @@ -26,6 +27,19 @@ const postPaths = [ '/api/auth/invitation/cancel', '/api/auth/entry/consents', '/api/auth/entry/consents/withdraw', + '/api/auth/entry/data-requests', + '/api/auth/entry/data-requests/export', + '/api/auth/entry/data-requests/erasure', + '/api/auth/entry/data-requests/closure', + '/api/auth/entry/data-requests/cancel', + '/api/auth/entry/data-requests/revoke', + '/api/auth/entry/data-requests/download', + '/api/account/data-requests/export', + '/api/account/data-requests/erasure', + '/api/account/data-requests/closure', + '/api/account/data-requests/cancel', + '/api/account/data-requests/revoke', + '/api/account/data-requests/download', '/api/studio/custom-field-create', '/api/studio/custom-field-revise', '/api/studio/custom-field-publish', @@ -39,6 +53,10 @@ const postPaths = [ '/api/studio/invitation-revoke', '/api/studio/invitation-reissue', '/api/studio/invitation-policy', + '/api/studio/data-request-export', + '/api/studio/data-request-erasure', + '/api/studio/data-request-cancel', + '/api/studio/data-request-revoke', '/api/studio/federation-test', '/api/studio/federation-configure', '/api/studio/federation-rotate-secret', @@ -62,6 +80,10 @@ const postPaths = [ '/api/account/profile', ]; const readPaths = ['/api/auth/signin', '/api/auth/csrf', '/api/auth/session', '/api/auth/error']; +const dataRequestDocumentPaths = [ + '/account/data', + ...postPaths.filter((path) => path.includes('/data-requests')), +]; const methods = [ 'GET', 'HEAD', @@ -89,6 +111,8 @@ afterEach(async () => { describe('Bff_Auth_Admission_And_Csrf_Are_Closed', () => { it('admits only the exact method/route set', () => { expect(BFF_POST_PATHS).toEqual(postPaths); + expect(DATA_REQUEST_DOCUMENT_PATHS).toEqual(dataRequestDocumentPaths); + expect(Object.isFrozen(DATA_REQUEST_DOCUMENT_PATHS)).toBe(true); const paths = [ ...readPaths, ...postPaths, @@ -97,6 +121,10 @@ describe('Bff_Auth_Admission_And_Csrf_Are_Closed', () => { '/api/auth/refresh', '/api/auth/entry/consents/scopes', '/api/auth/entry/consents/withdraw/extra', + '/api/auth/entry/data-requests/view', + '/api/account/data-requests', + '/api/account/data-requests/export/extra', + '/account/data', '/api/studio/custom-field-create/extra', '/api/account/consent-grant/extra', '/api/auth/providers', @@ -254,7 +282,12 @@ describe('Bff_Auth_Admission_And_Csrf_Are_Closed', () => { if (origin === null) request.headers.delete('origin'); else request.headers.set('origin', origin); const response = await f.http.handle(request); - expect(response!.status).toBe(path.startsWith('/api/auth/invitation/') ? 404 : 400); + // Recipient and data-request actions belong only to their pre-Next native handlers. + expect(response!.status).toBe( + path.startsWith('/api/auth/invitation/') || DATA_REQUEST_DOCUMENT_PATHS.includes(path) + ? 404 + : 400, + ); expect(response!.headers.getSetCookie()).toEqual([]); expect(f.store.counts()).toEqual(counts); if (current) expect(f.store.peek(current.binding)).toEqual(before); diff --git a/frontend/apps/web/src/test/bff-data-request-administration-routes.test.ts b/frontend/apps/web/src/test/bff-data-request-administration-routes.test.ts new file mode 100644 index 000000000..d50eaca1a --- /dev/null +++ b/frontend/apps/web/src/test/bff-data-request-administration-routes.test.ts @@ -0,0 +1,393 @@ +// @vitest-environment node +import { createRequire } from 'node:module'; +import { runInNewContext } from 'node:vm'; + +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { bffFixture, bffHost, bffRequest } from './bff-fixture'; +import { BFF_HISTORY_SOURCE } from '../components/auth/history'; +import { renderBffDocument } from '../server/auth/html'; +import type { BffHttpRequest } from '../server/auth/http-input'; +import type { BffPage } from '../server/auth/http-protocol'; +import { createNativeAdministrationCaller } from '../server/auth/native-administration-client'; + +const { JSDOM } = createRequire(import.meta.url)('jsdom') as { + JSDOM: new (html: string) => { window: { document: Document; close(): void } }; +}; +const requestId = '019a154b-0000-7000-8000-000000000041'; +const membershipId = '019a154b-0000-7000-8000-000000000012'; +const version = '9223372036854775807'; +const key = 'deliberate-data-request-key'; +const exportPath = '/api/studio/data-request-export'; +const erasurePath = '/api/studio/data-request-erasure'; +const cancelPath = '/api/studio/data-request-cancel'; +const revokePath = '/api/studio/data-request-revoke'; +const memberPage = '/studio/members/' + membershipId; +const requestPage = '/studio/data-requests/' + requestId; +const erasurePage = '/studio/data-requests/erasure?membership=' + membershipId; +const location = '/api/v1/identity/data-requests/' + requestId; +const configuration = { + apiOrigin: 'http://127.0.0.1:5100', + secret: 'synthetic-data-request-hop-'.padEnd(48, 'x'), + nativeSourceSecret: Buffer.from(Array.from({ length: 32 }, (_, index) => index + 41)).toString( + 'base64url', + ), +}; +const site = { + displayName: 'Institution', + defaultLocale: 'en', + enabledLocales: ['en', 'tr'], + theme: null, + showPlatformAttribution: true, +}; +const fixtures: ReturnType<typeof bffFixture>[] = []; +const documents: InstanceType<typeof JSDOM>[] = []; +function json(body: unknown, status = 200, headers: Record<string, string> = {}) { + return new Response(JSON.stringify(body), { + status, + headers: { + 'content-type': status < 400 ? 'application/json' : 'application/problem+json', + 'cache-control': 'no-store', + ...headers, + }, + }); +} +const accepted = (kind: 'export' | 'erasure', where = location) => + json( + { id: requestId, kind, status: kind === 'export' ? 'requested' : 'scheduled', version: '0' }, + 202, + { + ETag: '"0"', + Location: where, + }, + ); +const receipt = () => json({ version: '4' }, 200, { ETag: '"4"' }); +function problem(status: number, code: string, errors?: Record<string, { key: string }[]>) { + return json( + { + type: 'about:blank', + status, + title: 'private-upstream-title', + instance: location, + code, + messageKey: 'lockey_' + code, + correlationId: 'request-data-request-proof', + ...(errors ? { errors } : {}), + }, + status, + ); +} +async function fixture() { + const f = bffFixture(); + fixtures.push(f); + const active = await f.login(); + const original = f.administration.getMockImplementation()!; + const transport = vi.fn<typeof fetch>(async () => accepted('export')); + const caller = createNativeAdministrationCaller(configuration, transport); + f.administration.mockImplementation((...args) => + args[2].kind === 'getOwnProfile' ? original(...args) : caller(...args), + ); + const csrfToken = active.finished.session.csrfToken; + const create = { csrfToken, idempotencyKey: key, membershipId }; + const write = { csrfToken, idempotencyKey: key, version, requestId }; + // The protocol's own recovery decision, independently of how the renderer then shows it. + const pages: BffPage[] = []; + const post = async (path: string, fields: Record<string, string>) => { + const response = await f.http.handle( + bffRequest(path, { + method: 'POST', + cookie: active.cookie, + form: new URLSearchParams(fields).toString(), + }), + (page) => { + pages.push(page); + return renderBffDocument(site, page); + }, + ); + expect(response).not.toBeNull(); + return response!; + }; + return { ...f, active, transport, create, write, post, pages }; +} +async function document(response: Response) { + expect(response.headers.get('cache-control')).toBe('no-store'); + expect(response.headers.get('content-type')).toBe('text/html; charset=utf-8'); + const html = await response.text(); + for (const canary of ['private-upstream-title', 'private-transport-canary', 'lockey_']) + expect(html).not.toContain(canary); + const dom = new JSDOM(html); + documents.push(dom); + expect(dom.window.document.querySelectorAll('script')).toHaveLength(1); + expect(dom.window.document.querySelector('#bff-history')?.textContent).toBe(BFF_HISTORY_SOURCE); + return dom.window.document; +} +const sent = (f: Awaited<ReturnType<typeof fixture>>, call = 0) => { + const [url, init] = f.transport.mock.calls[call]!; + const headers = new Headers(init?.headers); + return { url: String(url), method: init?.method, body: String(init?.body), headers }; +}; +afterEach(async () => { + for (const dom of documents.splice(0)) dom.window.close(); + await Promise.all(fixtures.splice(0).flatMap((f) => [f.store.stop(), f.requestRuntime.stop()])); + vi.restoreAllMocks(); +}); + +describe('native administrator data-request HTTP and actual SDK dispatch (ADR-0106 §§ 3, 10, 11)', () => { + it.each([ + [exportPath, 'export', '/exports', {}], + [erasurePath, 'erasure', '/erasures', { confirm: 'erase' }], + ] as const)( + 'files %s for one Membership with its key and lands on the request page', + async (path, kind, suffix, extra) => { + const f = await fixture(); + f.transport.mockImplementationOnce(async () => accepted(kind)); + const response = await f.post(path, { ...f.create, ...extra }); + expect(response.status).toBe(303); + expect(response.headers.get('location')).toBe(requestPage + '?result=' + kind); + expect(response.headers.getSetCookie()).toEqual([]); + const call = sent(f); + expect(call.url).toBe(configuration.apiOrigin + '/api/v1/identity/data-requests' + suffix); + expect(call.method).toBe('POST'); + expect(JSON.parse(call.body)).toEqual({ membershipId }); + expect(call.headers.get('Idempotency-Key')).toBe(key); + expect(call.headers.has('If-Match')).toBe(false); + expect(call.headers.get('X-LearnStack-Native-Tenant-Id')).toBe(f.scope.tenantId); + expect(call.headers.get('X-LearnStack-Host')).toBe(bffHost); + expect(call.headers.has('Cookie')).toBe(false); + }, + ); + + it.each([ + [cancelPath, '/cancellations', 'cancelled'], + [revokePath, '/artifact/revocations', 'revoked'], + ] as const)( + 'posts %s once at the exact version with empty JSON', + async (path, suffix, result) => { + const f = await fixture(); + f.transport.mockImplementationOnce(async () => receipt()); + const response = await f.post(path, f.write); + expect(response.status).toBe(303); + expect(response.headers.get('location')).toBe(requestPage + '?result=' + result); + const call = sent(f); + expect(call.url).toBe(configuration.apiOrigin + location + suffix); + expect(call.body).toBe('{}'); + expect(call.headers.get('If-Match')).toBe('"' + version + '"'); + expect(call.headers.get('Idempotency-Key')).toBe(key); + }, + ); + + it('treats a creation answered with another Location as unconfirmed, keeping the exact request for a deliberate retry', async () => { + const f = await fixture(); + f.transport.mockImplementationOnce(async () => + accepted('export', '/api/v1/identity/me/data-requests/' + requestId), + ); + const response = await f.post(exportPath, f.create); + expect(response.status).toBe(503); + expect(response.headers.get('location')).toBeNull(); + const rendered = await document(response); + expect(rendered.querySelector('[role="alert"]')?.textContent).toContain( + 'The result could not be confirmed.', + ); + const retry = rendered.querySelector<HTMLFormElement>('form[action="' + exportPath + '"]')!; + expect( + Object.fromEntries( + [...retry.querySelectorAll<HTMLInputElement>('input')].map((input) => [ + input.name, + input.value, + ]), + ), + ).toEqual(f.create); + expect(rendered.querySelector('a[href="' + memberPage + '"]')).not.toBeNull(); + f.transport.mockImplementationOnce(async () => accepted('export')); + expect((await f.post(exportPath, f.create)).status).toBe(303); + expect(sent(f, 1).body).toBe(sent(f, 0).body); + expect(sent(f, 1).headers.get('Idempotency-Key')).toBe(key); + }); + + it.each([ + [ + exportPath, + '$', + 'lockey_subject_export_available', + 'A copy of the data is already available to download.', + ], + [ + exportPath, + '$', + 'lockey_request_already_active', + 'A request of this kind is already in progress for this member', + ], + [ + erasurePath, + '$', + 'lockey_subject_membership_current', + 'This person still has an active or suspended membership in this scope.', + ], + [ + erasurePath, + '$', + 'lockey_blocked_last_administrator', + "This member is the institution's only administrator.", + ], + [ + erasurePath, + '$', + 'lockey_blocked_hold', + "the institution has to keep this member's data for the moment", + ], + [ + exportPath, + '$', + 'lockey_snapshot_too_large', + 'This person has more membership records in this scope than one request can hold.', + ], + [ + exportPath, + '$', + 'lockey_subject_is_requester', + 'Requests about your own data are made on your own data page.', + ], + [exportPath, '$', 'lockey_subject_not_admitted', "This person's account is being closed"], + [cancelPath, '$', 'lockey_data_request_window_ended', 'so it can no longer be cancelled'], + [ + cancelPath, + '$', + 'lockey_data_request_not_cancellable', + 'This request can no longer be cancelled', + ], + [revokePath, 'artifact', 'lockey_data_export_unavailable', 'so there is nothing to delete'], + [exportPath, '$', 'lockey_reason_from_the_future', 'This request was refused.'], + ] as const)( + 'explains %s refused with %s %s in plain language and offers no retry', + async (path, field, reason, sentence) => { + const f = await fixture(); + f.transport.mockImplementationOnce(async () => + problem(409, 'business_rule_violation', { [field]: [{ key: reason }] }), + ); + const response = await f.post( + path, + path === erasurePath + ? { ...f.create, confirm: 'erase' } + : path === exportPath + ? f.create + : f.write, + ); + expect(response.status).toBe(409); + expect(f.pages).toEqual([ + expect.objectContaining({ + kind: 'mutation_error', + reason: 'denied', + retryable: false, + dataRequest: { refusal: expect.any(String) }, + }), + ]); + const rendered = await document(response); + expect(rendered.querySelector('[role="alert"]')?.textContent).toContain(sentence); + expect(rendered.querySelector('form')).toBeNull(); + // A Revoked Membership has no member page: an erasure recovers to the page it was filed from. + const back = + path === cancelPath || path === revokePath + ? requestPage + : path === erasurePath + ? erasurePage + : memberPage; + expect(rendered.querySelector('a[href="' + back + '"]')).not.toBeNull(); + expect(rendered.documentElement.getAttribute('data-bff-history-recovery')).toBe(back); + expect(f.transport).toHaveBeenCalledTimes(1); + expect(f.store.peek(f.active.binding)).not.toBeNull(); + }, + ); + + it.each([ + ['concurrency_conflict', 'This item changed.'], + ['request_in_progress', 'This request is still in progress.'], + ['idempotency_key_reuse', 'This form was already used for a different change.'], + ] as const)('keeps the template sentence for the generic %s outcome', async (code, sentence) => { + const f = await fixture(); + f.transport.mockImplementationOnce(async () => problem(409, code)); + const rendered = await document(await f.post(cancelPath, f.write)); + expect(rendered.querySelector('[role="alert"]')?.textContent).toContain(sentence); + expect(rendered.querySelector('form') !== null).toBe(code === 'request_in_progress'); + }); + + it('asks again for an erasure confirmation the form did not carry, before any API work', async () => { + const f = await fixture(); + for (const fields of [f.create, { ...f.create, confirm: 'yes' }]) { + const response = await f.post(erasurePath, fields); + expect(response.status).toBe(400); + const rendered = await document(response); + expect(rendered.querySelector('[role="alert"]')?.textContent).toBe( + 'Tick every confirmation box to go ahead.', + ); + expect(rendered.querySelector('form')).toBeNull(); + expect(rendered.querySelector('a[href="' + erasurePage + '"]')).not.toBeNull(); + expect(rendered.documentElement.getAttribute('data-bff-history-recovery')).toBe(erasurePage); + } + expect(f.transport).not.toHaveBeenCalled(); + }); + + it.each([ + 'absent-origin', + 'foreign-origin', + 'stale-csrf', + 'duplicate-membership', + 'foreign-selector', + 'noncanonical-membership', + ] as const)('refuses %s before administrator transport', async (kind) => { + const f = await fixture(); + const fields = new URLSearchParams(f.create); + if (kind === 'stale-csrf') fields.set('csrfToken', 'B'.repeat(43)); + if (kind === 'duplicate-membership') fields.append('membershipId', requestId); + if (kind === 'foreign-selector') fields.set('organizationId', requestId); + if (kind === 'noncanonical-membership') fields.set('membershipId', membershipId.toUpperCase()); + const request: BffHttpRequest = bffRequest(exportPath, { + method: 'POST', + cookie: f.active.cookie, + form: fields.toString(), + }); + if (kind === 'absent-origin') request.headers.delete('origin'); + if (kind === 'foreign-origin') request.headers.set('origin', 'https://foreign.example'); + const response = await f.http.handle(request, (page) => renderBffDocument(site, page)); + expect([400, 403]).toContain(response?.status); + expect(f.transport).not.toHaveBeenCalled(); + expect(f.store.peek(f.active.binding)).not.toBeNull(); + }); + + it.each([ + [revokePath, requestPage], + [erasurePath, erasurePage], + ] as const)( + 'restores a refusal of %s by its fixed GET %s without replaying the POST', + async (path, page) => { + const f = await fixture(); + f.transport.mockImplementationOnce(async () => + path === erasurePath + ? problem(409, 'business_rule_violation', { + $: [{ key: 'lockey_subject_membership_current' }], + }) + : problem(409, 'concurrency_conflict'), + ); + const rendered = await document( + await f.post(path, path === erasurePath ? { ...f.create, confirm: 'erase' } : f.write), + ); + const handlers = new Map<string, (event: { persisted?: boolean }) => void>(); + const replace = vi.fn(); + const style = { visibility: '' }; + runInNewContext(BFF_HISTORY_SOURCE, { + document: { + documentElement: { + style, + getAttribute: (name: string) => rendered.documentElement.getAttribute(name), + }, + }, + addEventListener: (name: string, handler: (event: { persisted?: boolean }) => void) => + handlers.set(name, handler), + location: { replace, reload: vi.fn() }, + }); + handlers.get('pagehide')!({}); + handlers.get('pageshow')!({ persisted: true }); + expect(replace).toHaveBeenCalledWith(page); + expect(f.transport).toHaveBeenCalledTimes(1); + }, + ); +}); diff --git a/frontend/apps/web/src/test/bff-data-request-person-routes.test.ts b/frontend/apps/web/src/test/bff-data-request-person-routes.test.ts new file mode 100644 index 000000000..593cba6cc --- /dev/null +++ b/frontend/apps/web/src/test/bff-data-request-person-routes.test.ts @@ -0,0 +1,462 @@ +// @vitest-environment node +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { + DownloadWire, + artifact, + chunkBytes, + closeDataRequestFixtures, + configuration, + fixture, + id, + organization, + pageInfo, + request, + second, + shown, + ticket, +} from './data-request-person-fixture'; +import en from '../i18n/messages/en/data.json'; + +/** + * The person's own data-request routes through the real session store, the real native callers, the real SDK and the + * real native transport, with only `fetch` faked: every request the API would receive, and every response it could + * send, crosses the SDK's validators and the BFF's Location, ETag and no-store rules (ADR-0106 §§ 9-11, ADR-0107 § 4). + */ +afterEach(closeDataRequestFixtures); + +const own = '/api/v1/identity/me/data-requests'; +const entry = '/api/v1/identity/data-request-entry'; +const key = 'person-route-key'.padEnd(43, 'k'); +const json = (body: unknown, status = 200, headers: Record<string, string> = {}) => + new Response(JSON.stringify(body), { + status, + headers: { + 'content-type': status < 400 ? 'application/json' : 'application/problem+json', + 'cache-control': 'no-store', + ...headers, + }, + }); +const accepted = (kind: 'export' | 'erasure' | 'closure', headers: Record<string, string> = {}) => + json({ id, kind, status: kind === 'export' ? 'requested' : 'scheduled', version: '0' }, 202, { + ETag: '"0"', + ...headers, + }); +const receipt = (version = '4') => json({ version }, 200, { ETag: '"' + version + '"' }); +const ticketBody = () => + json({ + ticket, + expiresAt: '2026-11-23T12:15:00.0000000+00:00', + chunkCount: 2, + byteCount: 131073, + }); +const chunkBody = (index: number, shown = index) => + json({ index: shown, count: 2, bytes: chunkBytes(index).toString('base64') }); + +/** A fake API: each "METHOD path" answers one response factory, and anything else is recorded and refused. */ +function api() { + const routes = new Map<string, () => Response>(); + const unexpected: string[] = []; + const transport = vi.fn<typeof fetch>(async (input, init) => { + const url = new URL(String(input)); + const label = (init?.method ?? 'GET') + ' ' + url.pathname; + const answer = routes.get(label); + if (!answer) { + unexpected.push(label); + return json({ title: 'unexpected' }, 500); + } + return answer(); + }); + return { + transport, + unexpected, + on: (method: string, path: string, answer: () => Response) => + routes.set(method + ' ' + path, answer), + }; +} +const sent = (transport: ReturnType<typeof api>['transport'], call = 0) => { + const [url, init] = transport.mock.calls[call]!; + const parsed = new URL(String(url)); + return { + origin: parsed.origin, + path: parsed.pathname + parsed.search, + method: init?.method, + body: init?.body === undefined ? undefined : (JSON.parse(String(init.body)) as unknown), + headers: new Headers(init?.headers), + init, + }; +}; +const paths = (transport: ReturnType<typeof api>['transport']) => + transport.mock.calls.map( + (_, call) => sent(transport, call).method + ' ' + sent(transport, call).path, + ); + +describe('the person’s page in a live session reads and files through the real SDK', () => { + it('lists the receipts that pass the closed validators and shows them', async () => { + const fake = api(); + fake.on('GET', own, () => + json({ + items: [ + request({ + status: 'completed', + completedAt: '2026-11-23T11:00:00.0000000+00:00', + artifact: artifact(), + }), + ], + pageInfo, + }), + ); + const f = await fixture('session', [], { transport: fake.transport }); + const wire = await f.run('GET', '/account/data'); + expect(wire.statusCode).toBe(200); + expect(wire.html).toContain('action="/api/account/data-requests/download"'); + expect(paths(fake.transport)).toEqual(['GET ' + own + '?limit=20']); + const call = sent(fake.transport); + expect(call.path).toBe(own + '?limit=20'); + // The native transport's closed request: an owned credential and scope, never a cookie or a browser value. + expect(call.headers.get('Authorization')).toBe('Bearer private-access-canary'); + expect(call.headers.get('X-LearnStack-Native-Tenant-Id')).toBe(f.scope.tenantId); + expect(call.headers.get('X-LearnStack-Host')).toBe('institution.example.test:3000'); + expect(call.headers.has('Cookie')).toBe(false); + expect(call.init).toMatchObject({ cache: 'no-store', credentials: 'omit', redirect: 'error' }); + expect(fake.unexpected).toEqual([]); + }); + + it('answers a receipt the SDK refuses with the unavailable sentence, never with its content', async () => { + for (const bad of [ + { ...request(), status: 'unknown' }, + { ...request(), extra: 'private-extra-canary' }, + request({ origin: 'someone_else' as never }), + request({ artifact: { ...artifact(), status: 'lost' } as never, kind: 'export' }), + ]) { + const fake = api(); + fake.on('GET', own, () => json({ items: [bad], pageInfo })); + const f = await fixture('session', [], { transport: fake.transport }); + const wire = await f.run('GET', '/account/data'); + expect(wire.statusCode).toBe(503); + expect(wire.html).toContain(shown(en.error.unavailable)); + expect(wire.html).not.toContain('private-extra-canary'); + expect(wire.html).not.toContain('someone_else'); + } + }); + + it.each([ + ['export', 'exports', 'export'], + ['erasure', 'erasures', 'erasure'], + ['closure', 'closures', 'closure'], + ] as const)( + 'files a %s at its own route with its key, an empty body and no precondition', + async (action, route, kind) => { + const fake = api(); + fake.on('POST', own + '/' + route, () => accepted(kind, { Location: own + '/' + id })); + const f = await fixture('session', [], { transport: fake.transport }); + const wire = await f.run('POST', '/api/account/data-requests/' + action, { + csrfToken: f.csrf, + idempotencyKey: key, + ...(action === 'erasure' ? { confirm: 'erase' } : {}), + ...(action === 'closure' ? { confirm: 'close', acknowledge: 'no_status' } : {}), + }); + expect(wire.statusCode).toBe(303); + expect(wire.headers.get('location')).toBe('/account/data?result=' + kind); + expect(paths(fake.transport)).toEqual(['POST ' + own + '/' + route]); + const call = sent(fake.transport); + expect(call.body).toEqual({}); + expect(call.headers.get('Idempotency-Key')).toBe(key); + expect(call.headers.has('If-Match')).toBe(false); + expect(call.headers.get('X-LearnStack-Native-Tenant-Id')).toBe(f.scope.tenantId); + expect(fake.unexpected).toEqual([]); + }, + ); + + it('answers a creation whose Location names another request as unconfirmed, with no redirect', async () => { + const fake = api(); + fake.on('POST', own + '/exports', () => accepted('export', { Location: own + '/' + second })); + const f = await fixture('session', [], { transport: fake.transport }); + const wire = await f.run('POST', '/api/account/data-requests/export', { + csrfToken: f.csrf, + idempotencyKey: key, + }); + expect(wire.statusCode).toBe(503); + expect(wire.headers.has('location')).toBe(false); + expect(wire.html).toContain(shown(en.error.unconfirmed)); + }); + + it.each([ + ['cancel', '/cancellations', '3', 'cancelled'], + ['revoke', '/artifact/revocations', '9007199254740993', 'revoked'], + ] as const)( + '%s posts once at the exact version with its key, never at another request’s route', + async (action, suffix, version, result) => { + const fake = api(); + fake.on('POST', own + '/' + id + suffix, () => receipt()); + const f = await fixture('session', [], { transport: fake.transport }); + const wire = await f.run('POST', '/api/account/data-requests/' + action, { + csrfToken: f.csrf, + idempotencyKey: key, + requestId: id, + version, + }); + expect(wire.statusCode).toBe(303); + expect(wire.headers.get('location')).toBe('/account/data?result=' + result); + expect(paths(fake.transport)).toEqual(['POST ' + own + '/' + id + suffix]); + const call = sent(fake.transport); + expect(call.body).toEqual({}); + expect(call.headers.get('If-Match')).toBe('"' + version + '"'); + expect(call.headers.get('Idempotency-Key')).toBe(key); + expect(fake.unexpected).toEqual([]); + }, + ); + + it('answers a stale version with the stale sentence and the same key left for a deliberate retry', async () => { + const fake = api(); + fake.on('POST', own + '/' + id + '/cancellations', () => + json( + { + type: 'https://errors.learnstack.dev/concurrency_conflict', + title: 'Refused', + status: 409, + instance: own + '/' + id + '/cancellations', + code: 'concurrency_conflict', + messageKey: 'lockey_concurrency_conflict', + correlationId: 'c', + }, + 409, + ), + ); + const f = await fixture('session', [], { transport: fake.transport }); + const wire = await f.run('POST', '/api/account/data-requests/cancel', { + csrfToken: f.csrf, + idempotencyKey: key, + requestId: id, + version: '3', + }); + expect(wire.statusCode).toBe(409); + expect(wire.html).toContain(shown(en.error.stale)); + expect(wire.headers.has('location')).toBe(false); + }); + + it('streams a two-chunk bundle: ticket, then chunk 0 and chunk 1 in order, as one attachment', async () => { + const fake = api(); + fake.on('POST', own + '/' + id + '/artifact/tickets', ticketBody); + let index = 0; + fake.on('POST', own + '/' + id + '/artifact/chunks', () => chunkBody(index++)); + const f = await fixture('session', [], { transport: fake.transport }); + const wire = new DownloadWire(); + await f.run( + 'POST', + '/api/account/data-requests/download', + { csrfToken: f.csrf, requestId: id }, + { wire }, + ); + expect(wire.statusCode).toBe(200); + expect(wire.headers.get('content-length')).toBe('131073'); + expect(wire.headers.get('content-disposition')).toBe('attachment; filename="data-export.json"'); + expect(Buffer.concat(wire.bytes).equals(Buffer.concat([chunkBytes(0), chunkBytes(1)]))).toBe( + true, + ); + expect(wire.writableEnded).toBe(true); + expect(wire.destroyed).toBe(false); + expect(JSON.stringify([...wire.headers])).not.toContain(ticket); + expect(paths(fake.transport)).toEqual([ + 'POST ' + own + '/' + id + '/artifact/tickets', + 'POST ' + own + '/' + id + '/artifact/chunks', + 'POST ' + own + '/' + id + '/artifact/chunks', + ]); + // The ticket is a body value of the chunk reads only; neither read carries a key or a precondition. + expect(sent(fake.transport, 0).body).toEqual({}); + expect(sent(fake.transport, 1).body).toEqual({ ticket, index: 0 }); + expect(sent(fake.transport, 2).body).toEqual({ ticket, index: 1 }); + for (const call of [0, 1, 2]) { + expect(sent(fake.transport, call).headers.has('Idempotency-Key')).toBe(false); + expect(sent(fake.transport, call).headers.has('If-Match')).toBe(false); + expect(sent(fake.transport, call).path).not.toContain(ticket); + } + expect(fake.unexpected).toEqual([]); + }); + + it('refuses a chunk that names another position before any byte reaches the browser', async () => { + const fake = api(); + fake.on('POST', own + '/' + id + '/artifact/tickets', ticketBody); + // The SDK takes a well-formed chunk of any position; the relay owns the order. + fake.on('POST', own + '/' + id + '/artifact/chunks', () => chunkBody(0, 1)); + const f = await fixture('session', [], { transport: fake.transport }); + const wire = new DownloadWire(); + const response = await f.run( + 'POST', + '/api/account/data-requests/download', + { csrfToken: f.csrf, requestId: id }, + { wire }, + ); + expect(wire.statusCode).toBe(503); + expect(wire.headers.has('content-disposition')).toBe(false); + expect(wire.bytes).toHaveLength(0); + expect(response.html).toContain(shown(en.error.download)); + expect(response.html).not.toContain(ticket); + }); + + it('answers a ticket the API refuses with that sentence and reads no chunk', async () => { + const fake = api(); + fake.on('POST', own + '/' + id + '/artifact/tickets', () => + json( + { + type: 'https://errors.learnstack.dev/business_rule_violation', + title: 'Refused', + status: 409, + instance: own + '/' + id + '/artifact/tickets', + code: 'business_rule_violation', + messageKey: 'lockey_business_rule_violation', + correlationId: 'c', + errors: { artifact: [{ key: 'lockey_data_export_ticket_limit' }] }, + }, + 409, + ), + ); + const f = await fixture('session', [], { transport: fake.transport }); + const wire = await f.run('POST', '/api/account/data-requests/download', { + csrfToken: f.csrf, + requestId: id, + }); + expect(wire.statusCode).toBe(409); + expect(wire.html).toContain(shown(en.refusal.data_export_ticket_limit)); + expect(paths(fake.transport)).toEqual(['POST ' + own + '/' + id + '/artifact/tickets']); + }); +}); + +describe('the retained entry reads and files through the real SDK, selector-free', () => { + const group = 'tenant'; + const tail = '?group=' + group; + it('lists the groups and a group’s requests with no tenant or organization header', async () => { + const fake = api(); + fake.on('GET', entry + '/scopes', () => + json({ + items: [ + { tenantId: id, organizationId: null }, + { tenantId: id, organizationId: organization }, + ], + pageInfo, + }), + ); + fake.on('GET', entry + '/requests', () => json({ items: [request()], pageInfo })); + const f = await fixture('entry', [], { transport: fake.transport }); + expect((await f.run('GET', '/account/data')).html).toContain( + 'data-data-request-view="entry_scopes"', + ); + expect((await f.run('GET', '/account/data?group=' + organization)).html).toContain( + 'data-data-request-view="entry"', + ); + expect( + fake.transport.mock.calls.map( + ([url]) => new URL(String(url)).pathname + new URL(String(url)).search, + ), + ).toEqual([ + entry + '/scopes?limit=20', + entry + '/requests?group=' + organization + '&limit=20', + ]); + for (const call of [0, 1]) { + const headers = sent(fake.transport, call).headers; + expect(headers.has('X-LearnStack-Native-Tenant-Id')).toBe(false); + expect(headers.has('X-LearnStack-Native-Organization-Id')).toBe(false); + expect(headers.get('X-LearnStack-Native-Session-Secret')).toBe( + configuration.nativeSourceSecret, + ); + } + // The retained path never performs a scoped session operation. + expect(f.administration).not.toHaveBeenCalled(); + expect(fake.unexpected).toEqual([]); + }); + + it.each([ + ['export', 'exports', 'export'], + ['erasure', 'erasures', 'erasure'], + ['closure', 'closures', 'closure'], + ] as const)('files a retained %s in its group, with no Location', async (action, route, kind) => { + const fake = api(); + fake.on('POST', entry + '/' + route, () => accepted(kind)); + const f = await fixture('entry', [], { transport: fake.transport }); + const wire = await f.run('POST', '/api/auth/entry/data-requests/' + action, { + csrfToken: f.csrf, + idempotencyKey: key, + group, + ...(action === 'erasure' ? { confirm: 'erase' } : {}), + ...(action === 'closure' ? { confirm: 'close', acknowledge: 'no_status' } : {}), + }); + expect(wire.statusCode).toBe(303); + expect(wire.headers.get('location')).toBe('/account/data?group=' + group + '&result=' + kind); + expect(paths(fake.transport)).toEqual(['POST ' + entry + '/' + route + tail]); + expect(sent(fake.transport).body).toEqual({}); + expect(sent(fake.transport).headers.get('Idempotency-Key')).toBe(key); + expect(fake.unexpected).toEqual([]); + }); + + it('answers a retained creation that carries a Location as unconfirmed', async () => { + const fake = api(); + fake.on('POST', entry + '/exports', () => accepted('export', { Location: own + '/' + id })); + const f = await fixture('entry', [], { transport: fake.transport }); + const wire = await f.run('POST', '/api/auth/entry/data-requests/export', { + csrfToken: f.csrf, + idempotencyKey: key, + group, + }); + expect(wire.statusCode).toBe(503); + expect(wire.headers.has('location')).toBe(false); + expect(wire.html).toContain(shown(en.error.unconfirmed)); + }); + + it.each([ + ['cancel', '/cancellations', '3', 'cancelled'], + ['revoke', '/revocations', '9007199254740993', 'revoked'], + ] as const)( + 'retained %s names its request in the body, its group in the query and its version in If-Match', + async (action, suffix, version, result) => { + const fake = api(); + fake.on('POST', entry + suffix, () => receipt()); + const f = await fixture('entry', [], { transport: fake.transport }); + const wire = await f.run('POST', '/api/auth/entry/data-requests/' + action, { + csrfToken: f.csrf, + idempotencyKey: key, + group: organization, + requestId: id, + version, + }); + expect(wire.statusCode).toBe(303); + expect(wire.headers.get('location')).toBe( + '/account/data?group=' + organization + '&result=' + result, + ); + expect(paths(fake.transport)).toEqual(['POST ' + entry + suffix + '?group=' + organization]); + const call = sent(fake.transport); + expect(call.body).toEqual({ requestId: id }); + expect(call.headers.get('If-Match')).toBe('"' + version + '"'); + expect(call.headers.get('Idempotency-Key')).toBe(key); + expect(fake.unexpected).toEqual([]); + }, + ); + + it('streams a two-chunk retained bundle with the group in every query', async () => { + const fake = api(); + fake.on('POST', entry + '/tickets', ticketBody); + let index = 0; + fake.on('POST', entry + '/chunks', () => chunkBody(index++)); + const f = await fixture('entry', [], { transport: fake.transport }); + const wire = new DownloadWire(); + await f.run( + 'POST', + '/api/auth/entry/data-requests/download', + { csrfToken: f.csrf, requestId: id, group: organization }, + { wire }, + ); + expect(wire.statusCode).toBe(200); + expect(Buffer.concat(wire.bytes).equals(Buffer.concat([chunkBytes(0), chunkBytes(1)]))).toBe( + true, + ); + expect(wire.writableEnded).toBe(true); + expect(paths(fake.transport)).toEqual([ + 'POST ' + entry + '/tickets?group=' + organization, + 'POST ' + entry + '/chunks?group=' + organization, + 'POST ' + entry + '/chunks?group=' + organization, + ]); + expect(sent(fake.transport, 0).body).toEqual({ requestId: id }); + expect(sent(fake.transport, 1).body).toEqual({ requestId: id, ticket, index: 0 }); + expect(sent(fake.transport, 2).body).toEqual({ requestId: id, ticket, index: 1 }); + expect(fake.unexpected).toEqual([]); + }); +}); diff --git a/frontend/apps/web/src/test/bff-fixture.ts b/frontend/apps/web/src/test/bff-fixture.ts index 089c6c3ff..b41b0a3e6 100644 --- a/frontend/apps/web/src/test/bff-fixture.ts +++ b/frontend/apps/web/src/test/bff-fixture.ts @@ -24,6 +24,7 @@ export function bffFixture( account?: SessionDependencies['account']; invitations?: SessionDependencies['invitations']; retainedConsent?: SessionDependencies['retainedConsent']; + retainedDataRequest?: SessionDependencies['retainedDataRequest']; federationTest?: SessionDependencies['federationTest']; publicSignIn?: SessionDependencies['publicSignIn']; unscopedProvider?: boolean; @@ -171,6 +172,7 @@ export function bffFixture( administration, invitations: options.invitations, retainedConsent: options.retainedConsent, + retainedDataRequest: options.retainedDataRequest, federationTest: options.federationTest, publicSignIn: options.publicSignIn, account: options.account ?? account, diff --git a/frontend/apps/web/src/test/data-request-person-fixture.ts b/frontend/apps/web/src/test/data-request-person-fixture.ts new file mode 100644 index 000000000..0107e5753 --- /dev/null +++ b/frontend/apps/web/src/test/data-request-person-fixture.ts @@ -0,0 +1,306 @@ +import type { IncomingMessage } from 'node:http'; + +import type { OwnDataRequest } from '@learnstack/sdk/administration-server'; +import { vi } from 'vitest'; + +import { bffFixture, bffHost, bffSource } from './bff-fixture'; +import { snapshotRequest, SnapshotWire } from './page-response-fixture'; +import en from '../i18n/messages/en/data.json'; +import tr from '../i18n/messages/tr/data.json'; +import { + createNativeAdministrationCaller, + createNativeRetainedDataRequestCaller, +} from '../server/auth/native-administration-client'; +import { createNativeDataRequestHandler } from '../server/auth/native-data-request-http'; +import type { + NativeAdministrationCaller, + NativeOperationResult, + NativeRetainedDataRequestCaller, +} from '../server/auth/native-operation-contract'; + +/** + * The person's own data-request page, driven through the real native handler, the real session store and the real + * request runtime. The API behind it is either a canned operation mock (the default) or the real native callers and + * SDK over a fake `fetch` (`transport`), as the administrator's route test does. + */ +export const id = '019a154b-0000-7000-8000-000000000041'; +export const second = '019a154b-0000-7000-8000-000000000042'; +export const organization = '019a154b-0000-7000-8000-0000000000a1'; +export const ticket = 'T'.repeat(42) + 'A'; +export const now = Date.parse('2026-11-23T12:00:00Z'); +export const pageInfo = { + nextCursor: null, + previousCursor: null, + hasNext: false, + hasPrevious: false, +}; +export const configuration = { + apiOrigin: 'http://127.0.0.1:5100', + secret: 'synthetic-person-data-request-hop-'.padEnd(48, 'x'), + nativeSourceSecret: Buffer.from(Array.from({ length: 32 }, (_, index) => index + 61)).toString( + 'base64url', + ), +}; +export const ok = (data: unknown, extra: Partial<{ etag: string; location: string }> = {}) => + ({ + kind: 'success', + status: 200, + data, + etag: extra.etag ?? null, + location: extra.location ?? null, + replayed: false, + }) as NativeOperationResult; +export const refused = (status: number, code: string, errors?: Record<string, { key: string }[]>) => + ({ + kind: 'api-error', + status, + error: { code: 'unknown', correlationId: 'c' }, + problem: { + type: 'https://errors.learnstack.dev/' + code, + title: 'Refused', + status, + instance: '/api/v1/identity/me/data-requests', + code, + messageKey: 'lockey_' + code, + correlationId: 'c', + ...(errors ? { errors } : {}), + }, + }) as NativeOperationResult; +export const artifact = (value: Partial<NonNullable<OwnDataRequest['artifact']>> = {}) => ({ + id: second, + status: 'available' as const, + expiresAt: '2026-11-30T10:00:00.0000000+00:00', + purgedAt: null, + byteCount: 131073, + chunkCount: 2, + truncations: [], + version: '9007199254740993', + readable: true, + ...value, +}); +export const request = (value: Partial<OwnDataRequest> = {}): OwnDataRequest => ({ + id, + kind: 'export', + origin: 'self', + status: 'requested', + createdAt: '2026-11-23T10:00:00.0000000+00:00', + updatedAt: null, + completedAt: null, + lastRefusal: null, + failureReason: null, + retained: [], + artifact: null, + version: '3', + executeAt: null, + ...value, +}); +export const chunkBytes = (index: number) => + Buffer.alloc(index === 0 ? 131072 : 1, index === 0 ? 0x61 : 0x62); + +/** + * A transport sink that takes each written buffer only when it acknowledges the write, a microtask later, as a socket + * does: the relay zeroes the buffer after the write settles, so one zeroed early would arrive here as zeros. + */ +export class DownloadWire extends SnapshotWire { + readonly bytes: Buffer[] = []; + override write(chunk: string, ...args: unknown[]) { + this.flushHeaders(); + const callback = args[args.length - 1]; + queueMicrotask(() => { + if (typeof chunk === 'string') this.chunks.push(chunk); + else this.bytes.push(Buffer.from(chunk as unknown as Buffer)); + if (typeof callback === 'function') Reflect.apply(callback, this, []); + }); + return true; + } + override end(...args: unknown[]) { + const callback = args[args.length - 1]; + const result = super.end(...args.filter((value) => typeof value !== 'function')); + if (typeof callback === 'function') queueMicrotask(() => Reflect.apply(callback, this, [])); + return result; + } +} + +const closes: (() => Promise<void>)[] = []; +/** Registered by each test file with `afterEach`; stops every fixture it created. */ +export async function closeDataRequestFixtures() { + for (const close of closes.splice(0).reverse()) await close(); +} + +const OWN_OPERATIONS = [ + 'listOwnDataRequests', + 'createOwnDataExport', + 'createOwnDataErasure', + 'createOwnAccountClosure', + 'cancelOwnDataRequest', + 'revokeOwnDataExport', + 'mintOwnDataExportTicket', + 'readOwnDataExportChunk', +]; + +/** + * `session` is a live session only, `entry` the retained entry only, and `both` the two cookie families a browser + * holds when it signs in again while its session is still live: an entry owner whose replacement is that session. + */ +export async function fixture( + mode: 'session' | 'entry' | 'both', + page: readonly OwnDataRequest[] = [], + options: { transport?: typeof fetch } = {}, +) { + const own = vi.fn< + (operation: Parameters<NativeAdministrationCaller>[2]) => NativeOperationResult + >((operation) => { + switch (operation.kind) { + case 'listOwnDataRequests': + return ok({ items: page, pageInfo }); + case 'mintOwnDataExportTicket': + return ok({ ticket, expiresAt: '2026-11-23T12:15:00Z', chunkCount: 2, byteCount: 131073 }); + case 'readOwnDataExportChunk': + return ok({ + index: operation.index, + count: 2, + bytes: chunkBytes(operation.index).toString('base64'), + }); + case 'createOwnDataExport': + return ok({ id, kind: 'export', status: 'requested', version: '0' }); + default: + return ok({ version: '4' }); + } + }); + const canned = vi.fn<NativeRetainedDataRequestCaller>(async (_token, _binding, operation) => { + switch (operation.kind) { + case 'listRetainedDataRequestScopes': + return ok({ + items: [ + { tenantId: id, organizationId: null }, + { tenantId: id, organizationId: organization }, + ], + pageInfo, + }); + case 'listRetainedDataRequests': + return ok({ items: page, pageInfo }); + case 'mintRetainedDataExportTicket': + return ok({ ticket, expiresAt: '2026-11-23T12:15:00Z', chunkCount: 2, byteCount: 131073 }); + case 'readRetainedDataExportChunk': + return ok({ + index: operation.index, + count: 2, + bytes: chunkBytes(operation.index).toString('base64'), + }); + default: + return ok({ version: '4' }); + } + }); + const real = options.transport; + const retained = real + ? createNativeRetainedDataRequestCaller(configuration, real) + : (canned as NativeRetainedDataRequestCaller); + const f = bffFixture({ retainedDataRequest: retained }); + const original = f.administration.getMockImplementation()!; + const session = real ? createNativeAdministrationCaller(configuration, real) : null; + f.administration.mockImplementation(async (token, binding, operation, signal) => + OWN_OPERATIONS.includes(operation.kind) + ? session + ? session(token, binding, operation, signal) + : own(operation) + : original(token, binding, operation, signal), + ); + const sessionOwner = mode === 'entry' ? null : await f.login(); + const entryOwner = + mode === 'session' + ? null + : await f.enter( + sessionOwner + ? { + browser: sessionOwner.finished.browser, + handle: sessionOwner.finished.handle, + } + : {}, + ); + const sessionCsrf = sessionOwner ? f.store.peek(sessionOwner.binding)!.csrfToken : null; + const entryCsrf = entryOwner ? entryOwner.finished.entry.csrfToken : null; + const cookie = + mode === 'both' + ? '__Host-ls-entry=' + + entryOwner!.finished.handle + + '; __Host-ls-session=' + + sessionOwner!.finished.handle + + '; __Host-ls-browser=' + + sessionOwner!.finished.browser + : (sessionOwner ?? entryOwner)!.cookie; + // The proof of the owner a bare request selects: the retained entry, else the live session. + const csrf = (entryCsrf ?? sessionCsrf)!; + f.account.mockClear(); + f.administration.mockClear(); + own.mockClear(); + const handler = createNativeDataRequestHandler({ + catalogues: { en, tr }, + store: f.store, + responseLease: f.requestRuntime.nativeDataRequestResponse, + now: () => now, + }); + closes.push(async () => { + await f.requestRuntime.stop(); + await f.store.stop(); + f.publicAdmission.shutdown(); + }); + const run = async ( + method: string, + target: string, + form?: Record<string, string> | URLSearchParams, + runOptions: { + /** Several values model a repeated `Origin` header a parser might hand over as a list. */ + origin?: string | readonly string[]; + headers?: Record<string, string>; + wire?: SnapshotWire; + request?: (incoming: IncomingMessage) => void; + } = {}, + ) => { + const incoming = snapshotRequest(); + runOptions.request?.(incoming); + incoming.method = method; + incoming.url = target; + incoming.headers.cookie = cookie; + Object.assign(incoming.headers, runOptions.headers ?? {}); + if (form) { + incoming.headers.origin = (runOptions.origin ?? 'https://' + bffHost) as string; + incoming.headers['content-type'] = 'application/x-www-form-urlencoded'; + incoming.complete = true; + incoming.push( + (form instanceof URLSearchParams ? form : new URLSearchParams(form)).toString(), + ); + incoming.push(null); + } + const binding = { host: bffHost, peer: bffSource, method, target }; + const wire = runOptions.wire ?? new SnapshotWire(); + await f.publicAdmission.run(binding, incoming, wire.native, () => + f.requestRuntime.run(binding, incoming, wire.native, () => + handler(binding, incoming, wire.native), + ), + ); + wire.drainCallbacks(); + for (let turn = 0; turn < 16; ++turn) await Promise.resolve(); + return Object.assign(wire, { html: wire.chunks.join('') }); + }; + return { + ...f, + own, + retained: canned, + run, + csrf, + sessionCsrf, + entryCsrf, + session: sessionOwner, + entry: entryOwner, + owner: (sessionOwner ?? entryOwner)!, + cookie, + }; +} +export const count = (html: string, pattern: RegExp) => [...html.matchAll(pattern)].length; +/** The renderer escapes every printed value; authored copy is compared as it appears in the document. */ +export const shown = (text: string) => text.replaceAll('&', '&').replaceAll("'", '''); +export const formKey = (html: string) => + /name="idempotencyKey" value="([A-Za-z0-9_-]{43})"/.exec(html)![1]!; +/** Every unused form key a page carries, in document order. */ +export const formKeys = (html: string) => + [...html.matchAll(/name="idempotencyKey" value="([A-Za-z0-9_-]{43})"/g)].map((m) => m[1]!); diff --git a/frontend/apps/web/src/test/data-request-reasons.test.ts b/frontend/apps/web/src/test/data-request-reasons.test.ts new file mode 100644 index 000000000..f256270d2 --- /dev/null +++ b/frontend/apps/web/src/test/data-request-reasons.test.ts @@ -0,0 +1,65 @@ +// @vitest-environment node +import { describe, expect, it } from 'vitest'; + +import { + ADMINISTRATOR_ROUTES, + PERSON_ROUTES, + dataRequestSources, + documentedReasons, + documentedRouteReasons, + identityDataRequestReasons, + lockeyReasons, + spelledReasons, +} from './data-request-reasons'; + +/** The catalogue tests trust this scanner to see every reason, so it is tested on what it must and must not see. */ +describe('the data-request reason scanner', () => { + it('sees a reason whatever characters it is spelled with, digits included', () => { + expect( + lockeyReasons( + 'Refuse("lockey_blocked_hold"); Refuse("lockey_limit_2"); Refuse("lockey_x2y");', + ), + ).toEqual(['lockey_blocked_hold', 'lockey_limit_2', 'lockey_x2y']); + expect( + documentedReasons('409 lockey_limit_2, lockey_subject_is_requester and data_export_v2.'), + ).toEqual(['lockey_limit_2', 'lockey_subject_is_requester', 'lockey_data_export_v2']); + // A key written in upper case, split by a dash, or not a literal is not a reason. + expect(lockeyReasons('"LOCKEY_x" "lockey-x" lockey_unquoted "lockey_"')).toEqual([]); + expect(documentedReasons('lockey_ and lockey_* and data_export')).toEqual([]); + }); + + it('reads every C# file of the Identity data-request code, however deep', () => { + const files = dataRequestSources(); + expect(files.length).toBeGreaterThan(10); + for (const name of [ + 'DataRequestService.cs', + 'DataExportDownloadService.cs', + 'RetainedDataRequestHandlers.cs', + 'DataRequestHandlers.cs', + ]) + expect(files).toContain(name); + expect(files.every((name) => name.endsWith('.cs'))).toBe(true); + }); + + it('reads the person’s routes and the administrator’s routes apart', () => { + const person = documentedRouteReasons(PERSON_ROUTES); + const administrator = documentedRouteReasons(ADMINISTRATOR_ROUTES); + // Only the person's download answers the ticket limit; the administrator never receives the file. + expect(person.has('lockey_data_export_ticket_limit')).toBe(true); + expect(administrator.has('lockey_data_export_ticket_limit')).toBe(false); + for (const reasons of [person, administrator]) { + expect(reasons.has('lockey_request_already_active')).toBe(true); + expect(reasons.has('lockey_data_request_not_cancellable')).toBe(true); + } + // A prefix that names no route documents nothing, and the code's reasons are in every catalogue's set. + expect(documentedRouteReasons(['/api/v1/identity/nothing']).size).toBe(0); + expect(documentedRouteReasons([]).size).toBe(0); + for (const routes of [PERSON_ROUTES, ADMINISTRATOR_ROUTES]) { + const all = identityDataRequestReasons(routes); + for (const reason of [...spelledReasons(), ...documentedRouteReasons(routes)]) + expect(all.has(reason), reason).toBe(true); + expect(all.size).toBeGreaterThan(15); + } + expect(spelledReasons().has('lockey_subject_not_admitted')).toBe(true); + }); +}); diff --git a/frontend/apps/web/src/test/data-request-reasons.ts b/frontend/apps/web/src/test/data-request-reasons.ts new file mode 100644 index 000000000..d0d7e3dd7 --- /dev/null +++ b/frontend/apps/web/src/test/data-request-reasons.ts @@ -0,0 +1,80 @@ +import { readdirSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; + +import snapshot from '../../../../../backend/openapi/v1.json'; + +const repository = join(process.cwd(), '../../..'); +const DATA_REQUESTS = join( + repository, + 'backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/DataRequests', +); + +/** The `lockey_*` reasons a C# source spells as a string literal, digits included. */ +export function lockeyReasons(source: string): string[] { + return [...source.matchAll(/"(lockey_[a-z0-9_]+)"/g)].map((match) => match[1]!); +} +/** + * The reasons a response description names: with the wire prefix, or an artifact reason the document names without + * it. Digits are part of a reason, so a key such as `lockey_limit_2` is never invisible. + */ +export function documentedReasons(description: string): string[] { + return [...description.matchAll(/\b(?:lockey_([a-z0-9_]+)|(data_export_[a-z0-9_]+))\b/g)].map( + (match) => 'lockey_' + (match[1] ?? match[2]), + ); +} +/** Every C# file of the Identity data-request code, however deep, relative to its directory. */ +export function dataRequestSources(): string[] { + return readdirSync(DATA_REQUESTS, { recursive: true, encoding: 'utf8' }) + .filter((name) => name.endsWith('.cs')) + .sort(); +} +/** Every `lockey_*` reason the committed OpenAPI document names in a response of a route under `routePrefixes`. */ +export function documentedRouteReasons(routePrefixes: readonly string[]): Set<string> { + const reasons = new Set<string>(); + for (const [path, item] of Object.entries( + snapshot.paths as Record< + string, + Record<string, { responses?: Record<string, { description?: string }> }> + >, + )) { + if (!routePrefixes.some((prefix) => path.startsWith(prefix))) continue; + for (const operation of Object.values(item)) + for (const response of Object.values(operation.responses ?? {})) + for (const reason of documentedReasons(response.description ?? '')) reasons.add(reason); + } + return reasons; +} +/** Every `lockey_*` reason the Identity data-request code spells, whatever file it is in. */ +export function spelledReasons(): Set<string> { + const reasons = new Set<string>(); + for (const file of dataRequestSources()) + for (const reason of lockeyReasons(readFileSync(join(DATA_REQUESTS, file), 'utf8'))) + reasons.add(reason); + return reasons; +} +/** + * What a catalogue must answer: the reasons the routes under `routePrefixes` document, and every one the Identity + * data-request code spells. One scanner, read by the person's and the administrator's catalogue tests, each with its + * own route prefixes. + */ +export function identityDataRequestReasons(routePrefixes: readonly string[]): Set<string> { + return new Set([...documentedRouteReasons(routePrefixes), ...spelledReasons()]); +} +/** The routes a person reaches: the own routes and the retained entry's. */ +export const PERSON_ROUTES = [ + '/api/v1/identity/me/data-requests', + '/api/v1/identity/data-request-entry', +] as const; +/** The routes of an administrator of the context's group. */ +export const ADMINISTRATOR_ROUTES = ['/api/v1/identity/data-requests'] as const; +/** The generic envelope a refusal maps by HTTP status and code, never by a reason sentence. */ +export const ENVELOPE_REASONS: ReadonlySet<string> = new Set([ + 'lockey_business_rule_violation', + 'lockey_not_found', + 'lockey_forbidden', + 'lockey_dependency_unavailable', + 'lockey_validation_failed', + 'lockey_invalid_value', + 'lockey_concurrency_conflict', + 'lockey_identifier_required', +]); diff --git a/frontend/apps/web/src/test/demo-genericity-sources.ts b/frontend/apps/web/src/test/demo-genericity-sources.ts index 794991405..5c2149476 100644 --- a/frontend/apps/web/src/test/demo-genericity-sources.ts +++ b/frontend/apps/web/src/test/demo-genericity-sources.ts @@ -606,6 +606,7 @@ export function productionDemoSources( 'src/server/auth/logout-response.ts', 'src/server/auth/native-administration-client.ts', 'src/server/auth/native-consent-http.ts', + 'src/server/auth/native-data-request-http.ts', 'src/server/auth/native-federation-client.ts', 'src/server/auth/native-invitation-client.ts', 'src/server/auth/native-invitation-http.ts', @@ -840,7 +841,7 @@ export function productionDemoSources( [path, 'd217cc042e967a01a245ed4d1915a068baa697498d4e2cf397032b195ec432eb'], [ 'frontend/apps/web/scripts/bff-proof-host.mjs', - '0eeda0c30c4bc4fe0b83be4d005a888131fe601a70a08cc4829db82a83603d13', + 'dfb7dc1b56b30698d1b1d8b53b5f979e64c79ddbc2e28c38f7250c1116a1cb01', ], [ 'frontend/apps/web/scripts/bff-custom-fields-fixture.mjs', @@ -940,6 +941,8 @@ export function productionDemoSources( '../src/i18n/messages/tr/invitation.json', '../src/i18n/messages/en/auth.json', '../src/i18n/messages/tr/auth.json', + '../src/i18n/messages/en/data.json', + '../src/i18n/messages/tr/data.json', ].includes(value.text) || node.arguments.length !== 2 || !options || diff --git a/frontend/apps/web/src/test/demo-genericity.test.ts b/frontend/apps/web/src/test/demo-genericity.test.ts index fd5bc7d87..dfe21c1b1 100644 --- a/frontend/apps/web/src/test/demo-genericity.test.ts +++ b/frontend/apps/web/src/test/demo-genericity.test.ts @@ -99,6 +99,8 @@ describe('P02d-7 exact demo identity boundary', () => { 'frontend/apps/web/src/server/auth/native-invitation-client.ts', 'frontend/apps/web/src/server/auth/native-invitation-http.ts', 'frontend/apps/web/src/server/auth/native-consent-http.ts', + 'frontend/apps/web/src/server/auth/native-data-request-http.ts', + 'frontend/apps/web/src/server/auth/data-request-html.ts', 'frontend/apps/web/src/server/auth/invitation-html.ts', 'frontend/apps/web/src/server/configured-public-client.ts', 'frontend/apps/web/src/components/public/lesson.tsx', @@ -1245,6 +1247,7 @@ describe('P02d-7 exact demo identity boundary', () => { 'src/server/auth/logout-response.ts', 'src/server/auth/native-administration-client.ts', 'src/server/auth/native-consent-http.ts', + 'src/server/auth/native-data-request-http.ts', 'src/server/auth/native-federation-client.ts', 'src/server/auth/native-invitation-client.ts', 'src/server/auth/native-invitation-http.ts', 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 564ae2820..118f271c8 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/frontend/apps/web/src/test/public-boundaries.test.ts b/frontend/apps/web/src/test/public-boundaries.test.ts index 3b2ef7337..90c664477 100644 --- a/frontend/apps/web/src/test/public-boundaries.test.ts +++ b/frontend/apps/web/src/test/public-boundaries.test.ts @@ -613,6 +613,9 @@ describe('ADR-0053 production public boundaries', () => { 'apps/web/src/app/(studio)/studio/invitations/[invitationId]/page.tsx', 'apps/web/src/app/(studio)/studio/invitation-policy/page.tsx', 'apps/web/src/app/(studio)/studio/federation/page.tsx', + 'apps/web/src/app/(studio)/studio/data-requests/page.tsx', + 'apps/web/src/app/(studio)/studio/data-requests/[requestId]/page.tsx', + 'apps/web/src/app/(studio)/studio/data-requests/erasure/page.tsx', 'apps/web/src/app/(portal)/layout.tsx', 'apps/web/src/app/(portal)/portal/page.tsx', 'apps/web/src/app/(portal)/portal/profile/page.tsx', @@ -873,6 +876,11 @@ describe('ADR-0053 production public boundaries', () => { 'native-invitation-http', 'invitation-html', 'invitation-copy', + 'native-consent-http', + 'native-data-request-http', + 'data-request-html', + 'data-request-copy', + 'data-export-download', 'native-contract', 'configuration', 'session-runtime', diff --git a/frontend/apps/web/src/test/public-boundary-analysis.ts b/frontend/apps/web/src/test/public-boundary-analysis.ts index dfbf48f5d..45d03d871 100644 --- a/frontend/apps/web/src/test/public-boundary-analysis.ts +++ b/frontend/apps/web/src/test/public-boundary-analysis.ts @@ -144,6 +144,9 @@ function evaluateHttpSurface( 'apps/web/src/app/(studio)/studio/invitations/[invitationId]/page.tsx', 'apps/web/src/app/(studio)/studio/invitation-policy/page.tsx', 'apps/web/src/app/(studio)/studio/federation/page.tsx', + 'apps/web/src/app/(studio)/studio/data-requests/page.tsx', + 'apps/web/src/app/(studio)/studio/data-requests/[requestId]/page.tsx', + 'apps/web/src/app/(studio)/studio/data-requests/erasure/page.tsx', 'apps/web/src/app/(studio)/studio/custom-fields/page.tsx', 'apps/web/src/app/(studio)/studio/custom-fields/[definitionId]/page.tsx', 'apps/web/src/app/(portal)/portal/page.tsx', diff --git a/frontend/apps/web/tsconfig.server.json b/frontend/apps/web/tsconfig.server.json index 57e6ae8a0..833718cd9 100644 --- a/frontend/apps/web/tsconfig.server.json +++ b/frontend/apps/web/tsconfig.server.json @@ -28,6 +28,7 @@ "src/server/auth/logout-response.ts", "src/server/auth/native-invitation-http.ts", "src/server/auth/native-consent-http.ts", + "src/server/auth/native-data-request-http.ts", "src/server/auth/native-invitation-client.ts", "src/server/auth/native-federation-client.ts", "src/server/auth/invitation-html.ts" diff --git a/frontend/packages/sdk/src/administration-contract.ts b/frontend/packages/sdk/src/administration-contract.ts index 72e91789e..1b240116e 100644 --- a/frontend/packages/sdk/src/administration-contract.ts +++ b/frontend/packages/sdk/src/administration-contract.ts @@ -26,7 +26,7 @@ export type AdministrationError = }; /** Aggregate versions never pass through a JavaScript number, including error hints. */ -export type AdministrationResult<T, Status extends 200 | 201 = 200> = +export type AdministrationResult<T, Status extends 200 | 201 | 202 = 200> = | Exclude<ApiResult<T>, { kind: 'success' } | { kind: 'api-error' }> | { readonly kind: 'api-error'; @@ -94,4 +94,10 @@ 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', + '/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/administration-server.test.ts b/frontend/packages/sdk/src/administration-server.test.ts index 5ae9153a6..06909a017 100644 --- a/frontend/packages/sdk/src/administration-server.test.ts +++ b/frontend/packages/sdk/src/administration-server.test.ts @@ -157,6 +157,30 @@ describe('closed administration server SDK', () => { 'renameOrganization', 'archiveOrganization', 'selectDefaultOrganization', + 'listOwnDataRequests', + 'getOwnDataRequest', + 'createOwnDataExport', + 'createOwnDataErasure', + 'createOwnAccountClosure', + 'cancelOwnDataRequest', + 'revokeOwnDataExport', + 'mintOwnDataExportTicket', + 'readOwnDataExportChunk', + 'listRetainedDataRequestScopes', + 'listRetainedDataRequests', + 'createRetainedDataExport', + 'createRetainedDataErasure', + 'createRetainedAccountClosure', + 'cancelRetainedDataRequest', + 'revokeRetainedDataExport', + 'mintRetainedDataExportTicket', + 'readRetainedDataExportChunk', + 'listDataRequests', + 'getDataRequest', + 'createDataExportForSubject', + 'createDataErasureForSubject', + 'cancelDataRequest', + 'revokeDataExport', ]); expect(sdk).not.toHaveProperty('request'); expectTypeOf< diff --git a/frontend/packages/sdk/src/administration-server.ts b/frontend/packages/sdk/src/administration-server.ts index 8aeb292e5..39c7c642a 100644 --- a/frontend/packages/sdk/src/administration-server.ts +++ b/frontend/packages/sdk/src/administration-server.ts @@ -42,11 +42,13 @@ import { } from './administration-policy.js'; import type { AdministrationShape } from './administration-policy.js'; import { createCustomFieldServerSdk } from './custom-field-server.js'; +import { createDataRequestServerSdk } from './data-request-server.js'; import { createFederationServerSdk } from './federation-server.js'; import { appError, parseProblem } from './response-policy.js'; export type * from './administration-contract.js'; export type * from './custom-field-contract.js'; +export type * from './data-request-contract.js'; export type * from './federation-contract.js'; export { createCustomFieldServerSdk, @@ -54,6 +56,21 @@ export { parseCustomFieldNumber, isCustomFieldSchema, } from './custom-field-server.js'; +/** + * The data-request policy callers share: the download relay's exact chunk geometry (ADR-0107 § 4), closed wire + * vocabularies the receipts are validated against, and the retained-group grammar. + */ +export { + DATA_EXPORT_ARTIFACT_STATUSES, + DATA_EXPORT_CHUNK_BYTES, + DATA_REQUEST_FAILURE_REASONS, + DATA_REQUEST_KINDS, + DATA_REQUEST_LAST_REFUSALS, + DATA_REQUEST_ORIGINS, + DATA_REQUEST_RETAINED_KINDS, + DATA_REQUEST_STATUSES, + dataRequestGroup as isDataRequestGroup, +} from './data-request-policy.js'; /** The invitation API's mailbox grammar, for callers that must refuse a recipient before sending. */ export { invitationEmail as isInvitationEmail } from './administration-policy.js'; @@ -545,6 +562,7 @@ export function createAdministrationServerSdk(transport: AdministrationFetch) { identifier(organizationId), options, ), + ...createDataRequestServerSdk(transport), }); } diff --git a/frontend/packages/sdk/src/authenticated-contract.test.ts b/frontend/packages/sdk/src/authenticated-contract.test.ts index d6aa7c563..1484ff30d 100644 --- a/frontend/packages/sdk/src/authenticated-contract.test.ts +++ b/frontend/packages/sdk/src/authenticated-contract.test.ts @@ -84,6 +84,12 @@ 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', + '/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', @@ -123,6 +129,12 @@ describe('generated GET contract ownership', () => { | 'GetOwnMembershipFieldConsent' | 'ListOwnFieldConsentScopes' | 'ListOwnMembershipFieldConsents' + | 'ListOwnDataRequests' + | 'GetOwnDataRequest' + | 'ListDataRequests' + | 'GetDataRequest' + | 'ListRetainedDataRequestScopes' + | 'ListRetainedDataRequests' >(); expect(RootContracts).toBe(AUTHENTICATED_GET_CONTRACTS); expectTypeOf<RootAccountSite>().toEqualTypeOf<AccountSite>(); diff --git a/frontend/packages/sdk/src/data-request-administration-server.test.ts b/frontend/packages/sdk/src/data-request-administration-server.test.ts new file mode 100644 index 000000000..c41c21820 --- /dev/null +++ b/frontend/packages/sdk/src/data-request-administration-server.test.ts @@ -0,0 +1,287 @@ +import { describe, expect, expectTypeOf, it, vi } from 'vitest'; + +import type { AdministrationFetch } from './administration-contract'; +import { DATA_REQUEST_ORIGINS, createAdministrationServerSdk } from './administration-server'; +import { DATA_REQUEST_ADMINISTRATION_POST_CONTRACTS } from './data-request-contract'; +import type { DataExportArtifact, SubjectDataRequest } from './data-request-contract'; +import type { components, operations, paths } from './generated/schema'; +import snapshot from '../../../../backend/openapi/v1.json'; + +const id = '019a154b-0000-7000-8000-000000000041'; +const member = '019a154b-0000-7000-8000-000000000011'; +const other = '019a154b-0000-7000-8000-000000000012'; +const key = 'k'.repeat(43); +const pageInfo = { nextCursor: null, previousCursor: null, hasNext: false, hasPrevious: false }; +const artifact: DataExportArtifact = { + id: '019a154b-0000-7000-8000-000000000042', + status: 'available', + expiresAt: '2026-11-30T10:00:00.0000000+00:00', + purgedAt: null, + byteCount: 2048, + chunkCount: 1, + truncations: [], + version: '9007199254740993', + readable: true, +}; +const item = (value: Partial<SubjectDataRequest> = {}): SubjectDataRequest => ({ + id, + kind: 'export', + origin: 'administrator', + status: 'completed', + createdAt: '2026-11-23T10:00:00.0000000+00:00', + updatedAt: '2026-11-23T10:01:00.0000000+00:00', + completedAt: '2026-11-23T10:01:00.0000000+00:00', + lastRefusal: null, + failureReason: null, + retained: [], + artifact, + version: '3', + executeAt: null, + requestedByYou: true, + membershipIds: [member], + ...value, +}); +const json = (body: unknown, status = 200, headers: Record<string, string> = {}) => + new Response(JSON.stringify(body), { + status, + headers: { + 'Content-Type': 'application/json; charset=utf-8', + 'Cache-Control': 'no-store', + ...headers, + }, + }); +const sdkWith = (...responses: Response[]) => { + const transport = vi.fn<AdministrationFetch>(async () => responses.shift() ?? json({})); + return { transport, sdk: createAdministrationServerSdk(transport) }; +}; +const sent = (transport: ReturnType<typeof sdkWith>['transport'], call = 0) => { + const [path, init] = transport.mock.calls[call]!; + return { + path, + method: init.method, + headers: init.headers as Record<string, string>, + body: init.body === undefined ? undefined : JSON.parse(String(init.body)), + }; +}; + +describe('administrator data-request wrappers (ADR-0106 §§ 3, 6, 10, 13; ADR-0107 § 4)', () => { + it('owns exactly the administrator POST operations of the committed OpenAPI document', () => { + const owned = Object.entries(DATA_REQUEST_ADMINISTRATION_POST_CONTRACTS); + const documented = Object.entries( + snapshot.paths as Record<string, { post?: { operationId: string } }>, + ).flatMap(([path, value]) => + value.post && path.startsWith('/api/v1/identity/data-requests') + ? [[path, value.post.operationId] as const] + : [], + ); + expect(Object.isFrozen(DATA_REQUEST_ADMINISTRATION_POST_CONTRACTS)).toBe(true); + expect(owned.sort()).toEqual([...documented].sort()); + expectTypeOf< + paths['/api/v1/identity/data-requests/{id}/artifact/revocations']['post'] + >().toEqualTypeOf<operations['RevokeDataExport']>(); + expectTypeOf<operations['CreateDataErasureForSubject']['requestBody']>().toEqualTypeOf<{ + content: { 'application/json': components['schemas']['DataExportForSubjectInput'] }; + }>(); + expectTypeOf< + Exclude<keyof SubjectDataRequest, keyof components['schemas']['OwnDataRequestResponse']> + >().toEqualTypeOf<'requestedByYou' | 'membershipIds'>(); + }); + + it('lists and reads with the exact path, the request ETag and no key', async () => { + const page = { + items: [item(), item({ id: artifact.id, kind: 'erasure', artifact: null })], + pageInfo: { ...pageInfo, nextCursor: 'n-1', hasNext: true }, + }; + const { sdk, transport } = sdkWith(json(page), json(item(), 200, { ETag: '"3"' })); + expect((await sdk.listDataRequests({ cursor: 'c-1', limit: 20 })).kind).toBe('success'); + expect(sent(transport)).toMatchObject({ + path: '/api/v1/identity/data-requests?cursor=c-1&limit=20', + method: 'GET', + }); + expect(sent(transport).headers).not.toHaveProperty('Idempotency-Key'); + expect((await sdk.getDataRequest(id)).kind).toBe('success'); + expect(sent(transport, 1)).toMatchObject({ + path: '/api/v1/identity/data-requests/' + id, + method: 'GET', + }); + for (const bad of [ + json(item(), 200, { ETag: '"4"' }), + json(item()), + json(item({ id: artifact.id }), 200, { ETag: '"3"' }), + ]) { + const { sdk: refused } = sdkWith(bad); + expect((await refused.getDataRequest(id)).kind).toBe('invalid-response'); + } + }); + + it('admits a receipt at the Membership snapshot bound and one of every origin', async () => { + const ids = (count: number) => + Array.from( + { length: count }, + (_, index) => member.slice(0, -3) + String(index).padStart(3, '0'), + ); + // The bound is inclusive: 256 distinct Memberships are valid, one more is refused above. + const { sdk: bound } = sdkWith(json({ items: [item({ membershipIds: ids(256) })], pageInfo })); + expect(await bound.listDataRequests()).toMatchObject({ kind: 'success' }); + const { sdk: one } = sdkWith(json({ items: [item({ membershipIds: ids(1) })], pageInfo })); + expect(await one.listDataRequests()).toMatchObject({ kind: 'success' }); + const receipts = DATA_REQUEST_ORIGINS.map((origin, index) => + item({ + id: '019a154b-0000-7000-8000-0000000009' + String(index).padStart(2, '0'), + kind: 'erasure', + origin, + status: 'scheduled', + completedAt: null, + executeAt: '2026-11-24T10:00:00Z', + artifact: null, + }), + ); + const { sdk: origins } = sdkWith(json({ items: receipts, pageInfo })); + const result = await origins.listDataRequests(); + expect(result).toMatchObject({ kind: 'success' }); + if (result.kind === 'success') expect(result.data.items).toEqual(receipts); + }); + + it('refuses a receipt an administrator never reads', async () => { + for (const bad of [ + item({ kind: 'closure', artifact: null, executeAt: '2026-11-24T10:00:00Z' }), + item({ membershipIds: [] }), + item({ membershipIds: [member, member] }), + item({ membershipIds: ['019a154b-0000-4000-8000-000000000011'] }), + item({ + membershipIds: Array.from( + { length: 257 }, + (_, index) => member.slice(0, -3) + String(index).padStart(3, '0'), + ), + }), + { ...item(), requestedByYou: 'yes' }, + (({ requestedByYou: _, ...rest }) => rest)(item()), + { ...item(), subjectUserId: member }, + ]) { + const { sdk } = sdkWith(json({ items: [bad], pageInfo })); + expect((await sdk.listDataRequests()).kind).toBe('invalid-response'); + } + const { sdk: duplicate } = sdkWith(json({ items: [item(), item()], pageInfo })); + expect((await duplicate.listDataRequests()).kind).toBe('invalid-response'); + }); + + it.each([ + ['createDataExportForSubject', 'export', 'requested', 'exports'], + ['createDataErasureForSubject', 'erasure', 'scheduled', 'erasures'], + ] as const)( + 'files %s for a Membership keyed, answering 202 with the exact Location', + async (method, kind, status, path) => { + const accepted = { id, kind, status, version: '0' }; + const location = { ETag: '"0"', Location: '/api/v1/identity/data-requests/' + id }; + const { sdk, transport } = sdkWith(json(accepted, 202, location)); + expect(await sdk[method](member, { idempotencyKey: key })).toMatchObject({ + kind: 'success', + status: 202, + location: location.Location, + }); + expect(sent(transport)).toEqual({ + path: '/api/v1/identity/data-requests/' + path, + method: 'POST', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + 'Idempotency-Key': key, + }, + body: { membershipId: member }, + }); + for (const bad of [ + json(accepted, 202, { ETag: '"0"' }), + json(accepted, 202, { ...location, Location: '/api/v1/identity/me/data-requests/' + id }), + json(accepted, 202, { ...location, Location: '/api/v1/identity/data-requests/' + other }), + json({ ...accepted, kind: kind === 'export' ? 'erasure' : 'export' }, 202, location), + json(accepted, 200, location), + ]) { + const { sdk: refused } = sdkWith(bad); + expect((await refused[method](member, { idempotencyKey: key })).kind).toBe( + 'invalid-response', + ); + } + const { sdk: replay } = sdkWith( + json(accepted, 202, { ...location, 'Idempotency-Replayed': 'true' }), + ); + expect(await replay[method](member, { idempotencyKey: key })).toMatchObject({ + replayed: true, + }); + }, + ); + + it('cancels at the request version and revokes at the artifact version, keyed', async () => { + const receipt = (version: string) => json({ version }, 200, { ETag: '"' + version + '"' }); + const { sdk, transport } = sdkWith(receipt('4'), receipt('9007199254740994')); + expect((await sdk.cancelDataRequest(id, { version: '3', idempotencyKey: key })).kind).toBe( + 'success', + ); + expect( + (await sdk.revokeDataExport(id, { version: artifact.version, idempotencyKey: key })).kind, + ).toBe('success'); + expect(sent(transport, 0)).toEqual({ + path: '/api/v1/identity/data-requests/' + id + '/cancellations', + method: 'POST', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + 'Idempotency-Key': key, + 'If-Match': '"3"', + }, + body: {}, + }); + expect(sent(transport, 1)).toMatchObject({ + path: '/api/v1/identity/data-requests/' + id + '/artifact/revocations', + headers: { 'If-Match': '"' + artifact.version + '"', 'Idempotency-Key': key }, + body: {}, + }); + }); + + it('refuses hostile input before any network call', async () => { + const { sdk, transport } = sdkWith(); + const write = { version: '3', idempotencyKey: key }; + for (const attempt of [ + () => sdk.getDataRequest('not-a-uuid'), + () => sdk.getDataRequest('019a154b-0000-4000-8000-000000000041'), + () => sdk.listDataRequests({ limit: 101 }), + () => sdk.listDataRequests({ limit: 0 }), + () => sdk.listDataRequests({ cursor: 'x'.repeat(1025) }), + () => sdk.listDataRequests({ cursor: 'a b' }), + () => sdk.createDataExportForSubject('../exports', { idempotencyKey: key }), + () => sdk.createDataErasureForSubject(member.toUpperCase(), { idempotencyKey: key }), + () => sdk.createDataExportForSubject(member, { idempotencyKey: 'short' }), + () => sdk.cancelDataRequest(id, { ...write, version: '01' }), + () => sdk.cancelDataRequest(id, { ...write, version: '9223372036854775808' }), + () => sdk.cancelDataRequest('x', write), + () => sdk.revokeDataExport(id, { ...write, idempotencyKey: 'k k k k k' }), + ]) + expect(await attempt()).toEqual({ kind: 'invalid-request' }); + expect(transport).not.toHaveBeenCalled(); + }); + + it('keeps the API refusal reason for the administrator sentence', async () => { + const { sdk } = sdkWith( + new Response( + JSON.stringify({ + type: 'https://errors.learnstack.dev/business_rule_violation', + title: 'Refused', + status: 409, + instance: '/api/v1/identity/data-requests/erasures', + code: 'business_rule_violation', + messageKey: 'lockey_business_rule_violation', + correlationId: 'request-123', + errors: { $: [{ key: 'lockey_subject_membership_current' }] }, + }), + { + status: 409, + headers: { 'Content-Type': 'application/problem+json', 'Cache-Control': 'no-store' }, + }, + ), + ); + const result = await sdk.createDataErasureForSubject(member, { idempotencyKey: key }); + if (result.kind !== 'api-error') throw new Error('Expected refusal'); + expect(result.status).toBe(409); + expect(result.problem.code).toBe('business_rule_violation'); + expect(result.problem.errors).toEqual({ $: [{ key: 'lockey_subject_membership_current' }] }); + }); +}); diff --git a/frontend/packages/sdk/src/data-request-contract.ts b/frontend/packages/sdk/src/data-request-contract.ts new file mode 100644 index 000000000..096af6a53 --- /dev/null +++ b/frontend/packages/sdk/src/data-request-contract.ts @@ -0,0 +1,59 @@ +import type { components } from './generated/schema.js'; + +/** The person's own receipt-safe projection (ADR-0106 § 9): status and counts, never content. */ +export type OwnDataRequest = components['schemas']['OwnDataRequestResponse']; +export type OwnDataRequestPage = components['schemas']['OwnDataRequestPage']; +export type DataExportArtifact = components['schemas']['DataExportArtifactResponse']; +export type DataRequestRetained = components['schemas']['DataRequestRetainedResponse']; +export type DataRequestAccepted = + | components['schemas']['DataRequestAcceptedResponse'] + | components['schemas']['DataErasureAcceptedResponse'] + | components['schemas']['AccountClosureAcceptedResponse']; +/** A sensitive download cursor; it travels only in a request body and never reaches a page, URL or log. */ +export type DataExportTicket = components['schemas']['DataExportTicketResponse']; +export type DataExportChunk = components['schemas']['DataExportChunkResponse']; +export type RetainedDataRequestScope = components['schemas']['RetainedDataRequestScopeResponse']; +export type RetainedDataRequestScopePage = + components['schemas']['RetainedDataRequestScopePageResponse']; +/** + * An administrator's receipt of a request of the context's group (ADR-0106 §§ 3, 6, 13): the own receipt plus who + * filed it relative to the caller and the frozen Membership snapshot that names the subject. Never a closure. + */ +export type SubjectDataRequest = components['schemas']['DataRequestResponse']; +export type SubjectDataRequestPage = components['schemas']['DataRequestPage']; +export type DataRequestSubjectInput = components['schemas']['DataExportForSubjectInput']; +/** The one retained group an entry operation acts in: `tenant` or an organization's canonical UUIDv7. */ +export type DataRequestGroup = string; +export type DataRequestKind = OwnDataRequest['kind']; +export type DataRequestStatus = OwnDataRequest['status']; +/** + * Exact POST ownership of the administrator's wrappers (ADR-0106 §§ 3, 10; ADR-0107 § 4): creation for a Membership + * of the group, and cancellation and revocation of a request the caller filed. No ticket or chunk route exists here: + * an administrator never receives the bundle. + */ +export const DATA_REQUEST_ADMINISTRATION_POST_CONTRACTS = Object.freeze({ + '/api/v1/identity/data-requests/exports': 'CreateDataExportForSubject', + '/api/v1/identity/data-requests/erasures': 'CreateDataErasureForSubject', + '/api/v1/identity/data-requests/{id}/cancellations': 'CancelDataRequest', + '/api/v1/identity/data-requests/{id}/artifact/revocations': 'RevokeDataExport', +} as const); +/** + * Exact POST ownership of the person's own and retained-entry wrappers (ADR-0106 §§ 9–10, ADR-0107 § 4). The + * administrator routes are above and the operator routes belong to no web surface. + */ +export const DATA_REQUEST_POST_CONTRACTS = Object.freeze({ + '/api/v1/identity/me/data-requests/exports': 'CreateOwnDataExport', + '/api/v1/identity/me/data-requests/erasures': 'CreateOwnDataErasure', + '/api/v1/identity/me/data-requests/closures': 'CreateOwnAccountClosure', + '/api/v1/identity/me/data-requests/{id}/cancellations': 'CancelOwnDataRequest', + '/api/v1/identity/me/data-requests/{id}/artifact/revocations': 'RevokeOwnDataExport', + '/api/v1/identity/me/data-requests/{id}/artifact/tickets': 'MintOwnDataExportTicket', + '/api/v1/identity/me/data-requests/{id}/artifact/chunks': 'ReadOwnDataExportChunk', + '/api/v1/identity/data-request-entry/exports': 'CreateRetainedDataExport', + '/api/v1/identity/data-request-entry/erasures': 'CreateRetainedDataErasure', + '/api/v1/identity/data-request-entry/closures': 'CreateRetainedAccountClosure', + '/api/v1/identity/data-request-entry/cancellations': 'CancelRetainedDataRequest', + '/api/v1/identity/data-request-entry/revocations': 'RevokeRetainedDataExport', + '/api/v1/identity/data-request-entry/tickets': 'MintRetainedDataExportTicket', + '/api/v1/identity/data-request-entry/chunks': 'ReadRetainedDataExportChunk', +} as const); diff --git a/frontend/packages/sdk/src/data-request-policy.ts b/frontend/packages/sdk/src/data-request-policy.ts new file mode 100644 index 000000000..3df3aa123 --- /dev/null +++ b/frontend/packages/sdk/src/data-request-policy.ts @@ -0,0 +1,261 @@ +import { fields, identifier, text, version } from './administration-policy.js'; + +/** Closed validation of the subject data-request wire (ADR-0106 §§ 8–9, ADR-0107 §§ 4 and 6). */ +export const DATA_REQUEST_KINDS = ['export', 'erasure', 'closure'] as const; +export const DATA_REQUEST_ORIGINS = ['self', 'administrator', 'closure_fanout'] as const; +export const DATA_REQUEST_STATUSES = [ + 'requested', + 'scheduled', + 'fulfilling', + 'awaiting_privileged_step', + 'completed', + 'blocked', + 'failed', + 'cancelled', +] as const; +export const DATA_REQUEST_LAST_REFUSALS = [ + 'blocked_window', + 'blocked_hold', + 'blocked_last_administrator', +] as const; +export const DATA_REQUEST_FAILURE_REASONS = ['export_too_large', 'execution_failed'] as const; +export const DATA_EXPORT_ARTIFACT_STATUSES = ['available', 'revoked', 'expired', 'purged'] as const; +export const DATA_REQUEST_RETAINED_KINDS = [ + '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', +] as const; +/** ADR-0107 § 4: at most 128 KiB of plaintext per chunk, at most 64 MiB per bundle. */ +export const DATA_EXPORT_CHUNK_BYTES = 128 * 1024; +export const DATA_EXPORT_MAXIMUM_BYTES = 64 * 1024 * 1024; +export const DATA_EXPORT_MAXIMUM_CHUNKS = DATA_EXPORT_MAXIMUM_BYTES / DATA_EXPORT_CHUNK_BYTES; + +const oneOf = (value: unknown, choices: readonly string[]): value is string => + typeof value === 'string' && choices.includes(value); +const integer = (value: unknown, minimum: number, maximum: number): value is number => + typeof value === 'number' && Number.isSafeInteger(value) && value >= minimum && value <= maximum; +export function dataRequestInstant(value: unknown): value is string { + if ( + typeof value !== 'string' || + !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,7})?(?:Z|\+00:00)$/.test(value) + ) + return false; + const timestamp = Date.parse(value); + return ( + Number.isFinite(timestamp) && + new Date(timestamp).toISOString().slice(0, 19) === value.slice(0, 19) + ); +} +const nullableInstant = (value: unknown) => value === null || dataRequestInstant(value); +/** `tenant` for the real host's tenant-wide group, or an organization's canonical UUIDv7. */ +export function dataRequestGroup(value: unknown): value is string { + return value === 'tenant' || identifier(value); +} +/** Canonical unpadded base64url of 32 bytes; never a route, query, page or log value. */ +export function dataExportTicket(value: unknown): value is string { + // 43 characters whose last carries two zero bits: exactly 32 bytes, one spelling. + return typeof value === 'string' && /^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/.test(value); +} + +function pageInfo(value: unknown, cursor: number): boolean { + return ( + fields(value, ['nextCursor', 'previousCursor', 'hasNext', 'hasPrevious']) && + (value.nextCursor === null || text(value.nextCursor, cursor)) && + value.previousCursor === null && + value.hasPrevious === false && + typeof value.hasNext === 'boolean' && + value.hasNext === (value.nextCursor !== null) + ); +} +function artifact(value: unknown): boolean { + if ( + !fields(value, [ + 'id', + 'status', + 'expiresAt', + 'purgedAt', + 'byteCount', + 'chunkCount', + 'truncations', + 'version', + 'readable', + ]) || + !identifier(value.id) || + !oneOf(value.status, DATA_EXPORT_ARTIFACT_STATUSES) || + !dataRequestInstant(value.expiresAt) || + !nullableInstant(value.purgedAt) || + !integer(value.byteCount, 1, DATA_EXPORT_MAXIMUM_BYTES) || + !integer(value.chunkCount, 1, DATA_EXPORT_MAXIMUM_CHUNKS) || + // Every chunk but the last is full, so the counts agree exactly. + value.chunkCount !== Math.ceil(value.byteCount / DATA_EXPORT_CHUNK_BYTES) || + !version(value.version) || + typeof value.readable !== 'boolean' || + (value.readable && value.status !== 'available') || + !Array.isArray(value.truncations) || + value.truncations.length > 32 + ) + return false; + return value.truncations.every( + (item) => + fields(item, ['collection', 'included', 'total']) && + text(item.collection, 65) && + /^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*$/.test(item.collection) && + integer(item.included, 0, Number.MAX_SAFE_INTEGER) && + integer(item.total, 0, Number.MAX_SAFE_INTEGER) && + item.included <= item.total, + ); +} +const RECEIPT_FIELDS = [ + 'id', + 'kind', + 'origin', + 'status', + 'createdAt', + 'updatedAt', + 'completedAt', + 'lastRefusal', + 'failureReason', + 'retained', + 'artifact', + 'version', + 'executeAt', +] as const; +/** ADR-0106 § 9: the person's own receipt, with exactly the receipt fields. */ +export function ownDataRequest(value: unknown): boolean { + return receipt(value, RECEIPT_FIELDS); +} +/** + * ADR-0106 §§ 3, 6, 13: an administrator's receipt of a request of the group. It adds who filed it relative to the + * caller and the frozen Membership snapshot (1 to 256 distinct identifiers), and is never a closure. + */ +export function subjectDataRequest(value: unknown): boolean { + return ( + receipt(value, [...RECEIPT_FIELDS, 'requestedByYou', 'membershipIds']) && + (value as { kind: string }).kind !== 'closure' && + typeof (value as { requestedByYou: unknown }).requestedByYou === 'boolean' && + memberships((value as { membershipIds: unknown }).membershipIds) + ); +} +function memberships(value: unknown): boolean { + return ( + Array.isArray(value) && + value.length >= 1 && + value.length <= 256 && + value.every(identifier) && + new Set(value).size === value.length + ); +} +function receipt(value: unknown, keys: readonly string[]): boolean { + if ( + !fields(value, keys) || + !identifier(value.id) || + !oneOf(value.kind, DATA_REQUEST_KINDS) || + !oneOf(value.origin, DATA_REQUEST_ORIGINS) || + !oneOf(value.status, DATA_REQUEST_STATUSES) || + !dataRequestInstant(value.createdAt) || + !nullableInstant(value.updatedAt) || + !nullableInstant(value.completedAt) || + (value.completedAt !== null && value.status !== 'completed') || + !(value.lastRefusal === null || oneOf(value.lastRefusal, DATA_REQUEST_LAST_REFUSALS)) || + !(value.failureReason === null || oneOf(value.failureReason, DATA_REQUEST_FAILURE_REASONS)) || + !version(value.version) || + !nullableInstant(value.executeAt) || + (value.kind === 'export' && value.executeAt !== null) || + !(value.artifact === null || (value.kind === 'export' && artifact(value.artifact))) || + !Array.isArray(value.retained) || + value.retained.length > DATA_REQUEST_RETAINED_KINDS.length + ) + return false; + return ( + value.retained.every( + (item) => + fields(item, ['kind', 'count']) && + oneOf(item.kind, DATA_REQUEST_RETAINED_KINDS) && + integer(item.count, 0, Number.MAX_SAFE_INTEGER), + ) && + new Set(value.retained.map((item) => (item as { kind: string }).kind)).size === + value.retained.length + ); +} +export function ownDataRequestPage(value: unknown, maximum: number): boolean { + return ( + fields(value, ['items', 'pageInfo']) && + Array.isArray(value.items) && + value.items.length <= maximum && + value.items.every(ownDataRequest) && + new Set(value.items.map((item) => (item as { id: string }).id)).size === value.items.length && + pageInfo(value.pageInfo, 1024) + ); +} +export function subjectDataRequestPage(value: unknown, maximum: number): boolean { + return ( + fields(value, ['items', 'pageInfo']) && + Array.isArray(value.items) && + value.items.length <= maximum && + value.items.every(subjectDataRequest) && + new Set(value.items.map((item) => (item as { id: string }).id)).size === value.items.length && + pageInfo(value.pageInfo, 1024) + ); +} +export function retainedScopePage(value: unknown): boolean { + return ( + fields(value, ['items', 'pageInfo']) && + Array.isArray(value.items) && + value.items.length <= 20 && + value.items.every( + (item) => + fields(item, ['tenantId', 'organizationId']) && + identifier(item.tenantId) && + (item.organizationId === null || identifier(item.organizationId)), + ) && + new Set(value.items.map((item) => (item as { organizationId: string | null }).organizationId)) + .size === value.items.length && + pageInfo(value.pageInfo, 36) + ); +} +const accepted = { export: 'requested', erasure: 'scheduled', closure: 'scheduled' } as const; +export function dataRequestAccepted(value: unknown, kind: keyof typeof accepted): boolean { + return ( + fields(value, ['id', 'kind', 'status', 'version']) && + identifier(value.id) && + value.kind === kind && + value.status === accepted[kind] && + version(value.version) + ); +} +export function dataExportTicketResponse(value: unknown): boolean { + return ( + fields(value, ['ticket', 'expiresAt', 'chunkCount', 'byteCount']) && + dataExportTicket(value.ticket) && + dataRequestInstant(value.expiresAt) && + integer(value.chunkCount, 1, DATA_EXPORT_MAXIMUM_CHUNKS) && + integer(value.byteCount, 1, DATA_EXPORT_MAXIMUM_BYTES) && + value.chunkCount === Math.ceil(value.byteCount / DATA_EXPORT_CHUNK_BYTES) + ); +} +/** Canonical padded base64 of 1 to 128 KiB; the relay checks the exact size per index. */ +export function dataExportChunkResponse(value: unknown): boolean { + return ( + fields(value, ['index', 'count', 'bytes']) && + integer(value.count, 1, DATA_EXPORT_MAXIMUM_CHUNKS) && + integer(value.index, 0, value.count - 1) && + typeof value.bytes === 'string' && + value.bytes.length >= 4 && + value.bytes.length <= 174764 && + value.bytes.length % 4 === 0 && + /^[A-Za-z0-9+/]*(?:[AQgw]==|[AEIMQUYcgkosw048]=)?$/.test(value.bytes) + ); +} diff --git a/frontend/packages/sdk/src/data-request-server.test.ts b/frontend/packages/sdk/src/data-request-server.test.ts new file mode 100644 index 000000000..bac6e2e62 --- /dev/null +++ b/frontend/packages/sdk/src/data-request-server.test.ts @@ -0,0 +1,989 @@ +import { describe, expect, expectTypeOf, it, vi } from 'vitest'; + +import type { AdministrationFetch, AdministrationResult } from './administration-contract'; +import { + DATA_EXPORT_ARTIFACT_STATUSES, + DATA_REQUEST_FAILURE_REASONS, + DATA_REQUEST_KINDS, + DATA_REQUEST_LAST_REFUSALS, + DATA_REQUEST_ORIGINS, + DATA_REQUEST_RETAINED_KINDS, + DATA_REQUEST_STATUSES, + createAdministrationServerSdk, +} from './administration-server'; +import { + DATA_REQUEST_ADMINISTRATION_POST_CONTRACTS, + DATA_REQUEST_POST_CONTRACTS, +} from './data-request-contract'; +import type { + DataExportArtifact, + OwnDataRequest, + SubjectDataRequest, +} from './data-request-contract'; +import type { components, operations, paths } from './generated/schema'; +import snapshot from '../../../../backend/openapi/v1.json'; + +const id = '019a154b-0000-7000-8000-000000000041'; +const organization = '019a154b-0000-7000-8000-0000000000a1'; +const key = 'k'.repeat(43); +const ticket = 'T'.repeat(42) + 'A'; +const pageInfo = { nextCursor: null, previousCursor: null, hasNext: false, hasPrevious: false }; +const artifact: DataExportArtifact = { + id: '019a154b-0000-7000-8000-000000000042', + status: 'available', + expiresAt: '2026-11-30T10:00:00.0000000+00:00', + purgedAt: null, + byteCount: 131073, + chunkCount: 2, + truncations: [{ collection: 'audit.entries', included: 10, total: 12 }], + version: '9007199254740993', + readable: true, +}; +const item = (value: Partial<OwnDataRequest> = {}): OwnDataRequest => ({ + id, + kind: 'export', + origin: 'self', + status: 'completed', + createdAt: '2026-11-23T10:00:00.0000000+00:00', + updatedAt: '2026-11-23T10:01:00.0000000+00:00', + completedAt: '2026-11-23T10:01:00.0000000+00:00', + lastRefusal: null, + failureReason: null, + retained: [], + artifact, + version: '3', + executeAt: null, + ...value, +}); +const json = (body: unknown, status = 200, headers: Record<string, string> = {}) => + new Response(JSON.stringify(body), { + status, + headers: { + 'Content-Type': 'application/json; charset=utf-8', + 'Cache-Control': 'no-store', + ...headers, + }, + }); +const problem = (status: number, code: string, errors?: Record<string, { key: string }[]>) => + new Response( + JSON.stringify({ + type: 'https://errors.learnstack.dev/' + code, + title: 'Refused', + status, + instance: '/api/v1/identity/me/data-requests/exports', + code, + messageKey: 'lockey_' + code, + correlationId: 'request-123', + ...(errors ? { errors } : {}), + }), + { + status, + headers: { 'Content-Type': 'application/problem+json', 'Cache-Control': 'no-store' }, + }, + ); +const sdkWith = (...responses: Response[]) => { + const transport = vi.fn<AdministrationFetch>(async () => responses.shift() ?? json({})); + return { transport, sdk: createAdministrationServerSdk(transport) }; +}; +const sent = (transport: ReturnType<typeof sdkWith>['transport'], call = 0) => { + const [path, init] = transport.mock.calls[call]!; + return { + path, + method: init.method, + headers: init.headers as Record<string, string>, + body: init.body === undefined ? undefined : JSON.parse(String(init.body)), + }; +}; + +describe('subject data-request wrappers (ADR-0106 § 9, ADR-0107 § 4)', () => { + it('owns exactly the person-facing POST operations of the committed OpenAPI document', () => { + const owned = Object.entries(DATA_REQUEST_POST_CONTRACTS); + const documented = Object.entries( + snapshot.paths as Record<string, { post?: { operationId: string } }>, + ).flatMap(([path, item]) => + item.post && + (path.startsWith('/api/v1/identity/me/data-requests') || + path.startsWith('/api/v1/identity/data-request-entry')) + ? [[path, item.post.operationId] as const] + : [], + ); + expect(Object.isFrozen(DATA_REQUEST_POST_CONTRACTS)).toBe(true); + expect(owned.sort()).toEqual([...documented].sort()); + expect(new Set(owned.map(([, operation]) => operation)).size).toBe(owned.length); + expectTypeOf< + paths['/api/v1/identity/me/data-requests/{id}/artifact/chunks']['post'] + >().toEqualTypeOf<operations['ReadOwnDataExportChunk']>(); + expectTypeOf< + operations['CreateOwnDataExport']['responses'][202]['content']['application/json'] + >().toEqualTypeOf<components['schemas']['DataRequestAcceptedResponse']>(); + expectTypeOf<operations['MintRetainedDataExportTicket']['requestBody']>().toEqualTypeOf<{ + content: { 'application/json': components['schemas']['RetainedDataRequestTargetInput'] }; + }>(); + expectTypeOf<keyof OwnDataRequest>().toEqualTypeOf< + | 'id' + | 'kind' + | 'origin' + | 'status' + | 'createdAt' + | 'updatedAt' + | 'completedAt' + | 'lastRefusal' + | 'failureReason' + | 'retained' + | 'artifact' + | 'version' + | 'executeAt' + >(); + expectTypeOf< + Extract<AdministrationResult<unknown, 202>, { kind: 'success' }>['status'] + >().toEqualTypeOf<202>(); + }); + + it('reads the own page and receipt with the exact path, query, ETag and no-store', async () => { + const page = { items: [item()], pageInfo: { ...pageInfo, nextCursor: 'n', hasNext: true } }; + const { sdk, transport } = sdkWith(json(page), json(item(), 200, { ETag: '"3"' })); + expect((await sdk.listOwnDataRequests({ limit: 20, cursor: 'c-1' })).kind).toBe('success'); + expect(sent(transport)).toMatchObject({ + path: '/api/v1/identity/me/data-requests?cursor=c-1&limit=20', + method: 'GET', + }); + expect(sent(transport).headers).not.toHaveProperty('Idempotency-Key'); + expect((await sdk.getOwnDataRequest(id)).kind).toBe('success'); + expect(sent(transport, 1).path).toBe('/api/v1/identity/me/data-requests/' + id); + for (const bad of [ + json(item(), 200, { ETag: '"4"' }), + json(item()), + json({ ...item(), id: artifact.id }, 200, { ETag: '"3"' }), + new Response(JSON.stringify(item()), { + headers: { 'Content-Type': 'application/json', ETag: '"3"' }, + }), + ]) { + const { sdk: other } = sdkWith(bad); + expect((await other.getOwnDataRequest(id)).kind).toBe('invalid-response'); + } + }); + + it('files own requests keyed, answering 202 with the exact Location and ETag', async () => { + for (const [method, kind, status, path] of [ + ['createOwnDataExport', 'export', 'requested', 'exports'], + ['createOwnDataErasure', 'erasure', 'scheduled', 'erasures'], + ['createOwnAccountClosure', 'closure', 'scheduled', 'closures'], + ] as const) { + const accepted = { id, kind, status, version: '0' }; + const location = { ETag: '"0"', Location: '/api/v1/identity/me/data-requests/' + id }; + const { sdk, transport } = sdkWith(json(accepted, 202, location)); + const result = await sdk[method]({ idempotencyKey: key }); + expect(result).toMatchObject({ kind: 'success', status: 202, location: location.Location }); + expect(sent(transport)).toEqual({ + path: '/api/v1/identity/me/data-requests/' + path, + method: 'POST', + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + 'Idempotency-Key': key, + }, + body: {}, + }); + for (const bad of [ + json(accepted, 200, location), + json(accepted, 202, { ETag: '"0"' }), + json(accepted, 202, { + ...location, + Location: '/api/v1/identity/me/data-requests/' + organization, + }), + json({ ...accepted, kind: kind === 'export' ? 'erasure' : 'export' }, 202, location), + json({ ...accepted, status: 'completed' }, 202, location), + ]) { + const { sdk: other } = sdkWith(bad); + expect((await other[method]({ idempotencyKey: key })).kind).toBe('invalid-response'); + } + const { sdk: replay } = sdkWith( + json(accepted, 202, { ...location, 'Idempotency-Replayed': 'true' }), + ); + expect(await replay[method]({ idempotencyKey: key })).toMatchObject({ replayed: true }); + } + }); + + it('cancels and revokes with If-Match and a key; tickets and chunks carry neither', async () => { + const receipt = (version: string) => json({ version }, 200, { ETag: '"' + version + '"' }); + const { sdk, transport } = sdkWith( + receipt('4'), + receipt('9007199254740994'), + json({ ticket, expiresAt: artifact.expiresAt, chunkCount: 2, byteCount: 131073 }), + json({ index: 1, count: 2, bytes: 'AA==' }), + ); + await sdk.cancelOwnDataRequest(id, { version: '3', idempotencyKey: key }); + await sdk.revokeOwnDataExport(id, { version: artifact.version, idempotencyKey: key }); + expect((await sdk.mintOwnDataExportTicket(id)).kind).toBe('success'); + expect((await sdk.readOwnDataExportChunk(id, ticket, 1)).kind).toBe('success'); + expect(sent(transport, 0)).toMatchObject({ + path: '/api/v1/identity/me/data-requests/' + id + '/cancellations', + headers: { 'If-Match': '"3"', 'Idempotency-Key': key }, + body: {}, + }); + expect(sent(transport, 1)).toMatchObject({ + path: '/api/v1/identity/me/data-requests/' + id + '/artifact/revocations', + headers: { 'If-Match': '"' + artifact.version + '"' }, + }); + for (const call of [2, 3]) { + expect(sent(transport, call).headers).not.toHaveProperty('If-Match'); + expect(sent(transport, call).headers).not.toHaveProperty('Idempotency-Key'); + } + expect(sent(transport, 2)).toMatchObject({ + path: '/api/v1/identity/me/data-requests/' + id + '/artifact/tickets', + body: {}, + }); + expect(sent(transport, 3)).toMatchObject({ + path: '/api/v1/identity/me/data-requests/' + id + '/artifact/chunks', + body: { ticket, index: 1 }, + }); + }); + + it('acts in one retained group named only by the group query value', async () => { + const { sdk, transport } = sdkWith( + json({ items: [{ tenantId: id, organizationId: null }], pageInfo }), + json({ items: [item()], pageInfo }), + json({ id, kind: 'erasure', status: 'scheduled', version: '0' }, 202, { ETag: '"0"' }), + json({ version: '4' }, 200, { ETag: '"4"' }), + json({ ticket, expiresAt: artifact.expiresAt, chunkCount: 2, byteCount: 131073 }), + json({ index: 0, count: 2, bytes: 'AA==' }), + ); + expect((await sdk.listRetainedDataRequestScopes({ limit: 20 })).kind).toBe('success'); + expect((await sdk.listRetainedDataRequests(organization, { limit: 5 })).kind).toBe('success'); + expect((await sdk.createRetainedDataErasure('tenant', { idempotencyKey: key })).kind).toBe( + 'success', + ); + expect( + (await sdk.cancelRetainedDataRequest('tenant', id, { version: '3', idempotencyKey: key })) + .kind, + ).toBe('success'); + expect((await sdk.mintRetainedDataExportTicket('tenant', id)).kind).toBe('success'); + expect((await sdk.readRetainedDataExportChunk('tenant', id, ticket, 0)).kind).toBe('success'); + expect(transport.mock.calls.map(([path]) => path)).toEqual([ + '/api/v1/identity/data-request-entry/scopes?limit=20', + '/api/v1/identity/data-request-entry/requests?group=' + organization + '&limit=5', + '/api/v1/identity/data-request-entry/erasures?group=tenant', + '/api/v1/identity/data-request-entry/cancellations?group=tenant', + '/api/v1/identity/data-request-entry/tickets?group=tenant', + '/api/v1/identity/data-request-entry/chunks?group=tenant', + ]); + expect(sent(transport, 3).body).toEqual({ requestId: id }); + expect(sent(transport, 4).body).toEqual({ requestId: id }); + expect(sent(transport, 5).body).toEqual({ requestId: id, ticket, index: 0 }); + // A retained creation has no per-request route, so a Location is a contract violation. + const { sdk: located } = sdkWith( + json({ id, kind: 'export', status: 'requested', version: '0' }, 202, { + ETag: '"0"', + Location: '/api/v1/identity/me/data-requests/' + id, + }), + ); + expect((await located.createRetainedDataExport('tenant', { idempotencyKey: key })).kind).toBe( + 'invalid-response', + ); + }); + + it('refuses hostile input before any network call', async () => { + const { sdk, transport } = sdkWith(); + const write = { version: '3', idempotencyKey: key }; + for (const attempt of [ + () => sdk.getOwnDataRequest('not-a-uuid'), + () => sdk.getOwnDataRequest('019a154b-0000-4000-8000-000000000041'), + () => sdk.listOwnDataRequests({ limit: 101 }), + () => sdk.listOwnDataRequests({ limit: 0 }), + () => sdk.listOwnDataRequests({ cursor: 'x'.repeat(1025) }), + () => sdk.listOwnDataRequests({ cursor: 'a b' }), + () => sdk.listRetainedDataRequests('tenant', { limit: 21 }), + () => sdk.listRetainedDataRequestScopes({ cursor: 'x'.repeat(37) }), + () => sdk.listRetainedDataRequests('Tenant'), + () => sdk.listRetainedDataRequests('tenant&group=tenant'), + () => sdk.createOwnDataExport({ idempotencyKey: 'short' }), + () => sdk.createRetainedDataExport('../exports', { idempotencyKey: key }), + () => sdk.cancelOwnDataRequest(id, { ...write, version: '01' }), + () => sdk.cancelOwnDataRequest(id, { ...write, version: '9223372036854775808' }), + () => sdk.revokeRetainedDataExport('tenant', 'x', write), + () => sdk.readOwnDataExportChunk(id, ticket, 512), + () => sdk.readOwnDataExportChunk(id, ticket, -1), + () => sdk.readOwnDataExportChunk(id, ticket, 1.5), + () => sdk.readOwnDataExportChunk(id, 'T'.repeat(43), 0), + () => sdk.readOwnDataExportChunk(id, ticket + 'A', 0), + () => sdk.readRetainedDataExportChunk('tenant', id, 'not a ticket', 0), + () => sdk.mintRetainedDataExportTicket('tenant', 'x'), + ]) + expect(await attempt()).toEqual({ kind: 'invalid-request' }); + expect(transport).not.toHaveBeenCalled(); + }); + + it('validates the closed receipt, ticket and chunk shapes', async () => { + const page = (value: unknown) => json({ items: [value], pageInfo }); + for (const bad of [ + { ...item(), status: 'unknown' }, + { ...item(), extra: true }, + { ...item(), executeAt: '2026-11-24T10:00:00Z' }, + item({ kind: 'erasure' }), + item({ status: 'requested' }), + item({ + retained: [ + { kind: 'request_receipt', count: 1 }, + { kind: 'request_receipt', count: 2 }, + ], + }), + item({ retained: [{ kind: 'everything', count: 1 } as never] }), + item({ retained: [{ kind: 'request_receipt', count: -1 }] }), + item({ artifact: { ...artifact, chunkCount: 3 } }), + item({ artifact: { ...artifact, readable: true, status: 'revoked' } }), + item({ + artifact: { ...artifact, truncations: [{ collection: 'entries', included: 1, total: 2 }] }, + }), + item({ + artifact: { + ...artifact, + truncations: [{ collection: 'audit.entries', included: 3, total: 2 }], + }, + }), + item({ createdAt: '2026-11-23 10:00' }), + item({ version: '01' }), + ]) { + const { sdk } = sdkWith(page(bad)); + expect((await sdk.listOwnDataRequests()).kind).toBe('invalid-response'); + } + const { sdk: duplicate } = sdkWith(json({ items: [item(), item()], pageInfo })); + expect((await duplicate.listOwnDataRequests()).kind).toBe('invalid-response'); + const { sdk: paging } = sdkWith(json({ items: [], pageInfo: { ...pageInfo, hasNext: true } })); + expect((await paging.listOwnDataRequests()).kind).toBe('invalid-response'); + for (const bad of [ + { ticket: 'T'.repeat(43), expiresAt: artifact.expiresAt, chunkCount: 2, byteCount: 131073 }, + { ticket, expiresAt: artifact.expiresAt, chunkCount: 1, byteCount: 131073 }, + { ticket, expiresAt: artifact.expiresAt, chunkCount: 513, byteCount: 67108865 }, + { ticket, expiresAt: 'later', chunkCount: 2, byteCount: 131073 }, + ]) { + const { sdk } = sdkWith(json(bad)); + expect((await sdk.mintOwnDataExportTicket(id)).kind).toBe('invalid-response'); + } + for (const bad of [ + { index: 2, count: 2, bytes: 'AA==' }, + { index: 0, count: 2, bytes: 'AB==' }, + { index: 0, count: 2, bytes: 'AA=' }, + { index: 0, count: 2, bytes: 'A'.repeat(174768) }, + { index: 0, count: 2, bytes: 'AA==', extra: 1 }, + ]) { + const { sdk } = sdkWith(json(bad)); + expect((await sdk.readOwnDataExportChunk(id, ticket, 0)).kind).toBe('invalid-response'); + } + const { sdk: large } = sdkWith(json({ index: 0, count: 2, bytes: 'A'.repeat(300 * 1024) })); + expect(await large.readOwnDataExportChunk(id, ticket, 0)).toEqual({ + kind: 'invalid-response', + reason: 'invalid-success', + }); + }); + + it('labels a body that breaks off as a transport failure and only an undecodable body as malformed', async () => { + const headers = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }; + let pulls = 0; + const broken = new Response( + new ReadableStream<Uint8Array>({ + pull(controller) { + if (pulls++ === 0) controller.enqueue(new TextEncoder().encode('{"index":0,')); + else controller.error(new TypeError('terminated')); + }, + }), + { headers }, + ); + const { sdk } = sdkWith(broken); + expect(await sdk.readOwnDataExportChunk(id, ticket, 0)).toEqual({ kind: 'transport-error' }); + for (const body of ['{"index":0,', new Uint8Array([0x7b, 0x22, 0xc3, 0x28, 0x22, 0x7d])]) { + const { sdk: garbled } = sdkWith(new Response(body, { headers })); + expect(await garbled.readOwnDataExportChunk(id, ticket, 0)).toEqual({ + kind: 'invalid-response', + reason: 'malformed-json', + }); + } + }); + + it('keeps the API refusal reason for the person-facing sentence', async () => { + const { sdk } = sdkWith( + problem(409, 'business_rule_violation', { + artifact: [{ key: 'lockey_data_export_ticket_limit' }], + }), + ); + const result = await sdk.mintOwnDataExportTicket(id); + expect(result.kind).toBe('api-error'); + if (result.kind !== 'api-error') throw new Error('Expected refusal'); + expect(result.status).toBe(409); + expect(result.problem.errors).toEqual({ + artifact: [{ key: 'lockey_data_export_ticket_limit' }], + }); + }); +}); + +type Sdk = ReturnType<typeof createAdministrationServerSdk>; +type OpenApiOperation = { + operationId?: string; + parameters?: { in: string; name: string; required?: boolean }[]; + requestBody?: { content: Record<string, { schema: { $ref: string } }> }; +}; +const documented = Object.entries( + snapshot.paths as unknown as Record<string, Record<string, OpenApiOperation>>, +).flatMap(([path, value]) => + /^\/api\/v1\/identity\/(?:me\/data-requests|data-request-entry|data-requests)(?:\/|$)/.test(path) + ? Object.entries(value).map(([method, operation]) => ({ + path, + method: method.toUpperCase(), + operation, + })) + : [], +); +const schemas = snapshot.components.schemas as unknown as Record< + string, + { properties?: Record<string, { enum?: (string | null)[] }> } +>; +const own = '/api/v1/identity/me/data-requests'; +const entry = '/api/v1/identity/data-request-entry'; +const administered = '/api/v1/identity/data-requests'; +const member = '019a154b-0000-7000-8000-000000000011'; +const subject = (value: Partial<SubjectDataRequest> = {}): SubjectDataRequest => ({ + ...item({ origin: 'administrator' }), + requestedByYou: true, + membershipIds: [member], + ...value, +}); +const accepted = (kind: 'export' | 'erasure' | 'closure', located?: string) => + json( + { id, kind, status: kind === 'export' ? 'requested' : 'scheduled', version: '0' }, + 202, + located === undefined ? { ETag: '"0"' } : { ETag: '"0"', Location: located + '/' + id }, + ); +const receipt = () => json({ version: '4' }, 200, { ETag: '"4"' }); +const ticketBody = () => + json({ ticket, expiresAt: artifact.expiresAt, chunkCount: 2, byteCount: 131073 }); +const chunkBody = () => json({ index: 1, count: 2, bytes: 'AA==' }); +const guarded = { 'Idempotency-Key': key, 'If-Match': '"3"' }; +const write = { version: '3', idempotencyKey: key }; +type Row = Readonly<{ + /** The SDK member under test, and the OpenAPI operation it must be. */ + name: string; + operationId: string; + call: (sdk: Sdk) => Promise<{ kind: string }>; + method: 'GET' | 'POST'; + path: string; + /** The headers beyond `Accept` and, for a POST, `Content-Type`. */ + headers?: Record<string, string>; + body?: unknown; + response: () => Response; +}>; +/** All 24 wrappers, each with the exact request it must put on the wire. */ +const WRAPPERS: readonly Row[] = [ + { + name: 'listOwnDataRequests', + operationId: 'ListOwnDataRequests', + call: (sdk) => sdk.listOwnDataRequests({ cursor: 'c-1', limit: 20 }), + method: 'GET', + path: own + '?cursor=c-1&limit=20', + response: () => json({ items: [item()], pageInfo }), + }, + { + name: 'getOwnDataRequest', + operationId: 'GetOwnDataRequest', + call: (sdk) => sdk.getOwnDataRequest(id), + method: 'GET', + path: own + '/' + id, + response: () => json(item(), 200, { ETag: '"3"' }), + }, + { + name: 'createOwnDataExport', + operationId: 'CreateOwnDataExport', + call: (sdk) => sdk.createOwnDataExport({ idempotencyKey: key }), + method: 'POST', + path: own + '/exports', + headers: { 'Idempotency-Key': key }, + body: {}, + response: () => accepted('export', own), + }, + { + name: 'createOwnDataErasure', + operationId: 'CreateOwnDataErasure', + call: (sdk) => sdk.createOwnDataErasure({ idempotencyKey: key }), + method: 'POST', + path: own + '/erasures', + headers: { 'Idempotency-Key': key }, + body: {}, + response: () => accepted('erasure', own), + }, + { + name: 'createOwnAccountClosure', + operationId: 'CreateOwnAccountClosure', + call: (sdk) => sdk.createOwnAccountClosure({ idempotencyKey: key }), + method: 'POST', + path: own + '/closures', + headers: { 'Idempotency-Key': key }, + body: {}, + response: () => accepted('closure', own), + }, + { + name: 'cancelOwnDataRequest', + operationId: 'CancelOwnDataRequest', + call: (sdk) => sdk.cancelOwnDataRequest(id, write), + method: 'POST', + path: own + '/' + id + '/cancellations', + headers: guarded, + body: {}, + response: receipt, + }, + { + name: 'revokeOwnDataExport', + operationId: 'RevokeOwnDataExport', + call: (sdk) => sdk.revokeOwnDataExport(id, write), + method: 'POST', + path: own + '/' + id + '/artifact/revocations', + headers: guarded, + body: {}, + response: receipt, + }, + { + name: 'mintOwnDataExportTicket', + operationId: 'MintOwnDataExportTicket', + call: (sdk) => sdk.mintOwnDataExportTicket(id), + method: 'POST', + path: own + '/' + id + '/artifact/tickets', + body: {}, + response: ticketBody, + }, + { + name: 'readOwnDataExportChunk', + operationId: 'ReadOwnDataExportChunk', + call: (sdk) => sdk.readOwnDataExportChunk(id, ticket, 1), + method: 'POST', + path: own + '/' + id + '/artifact/chunks', + body: { ticket, index: 1 }, + response: chunkBody, + }, + { + name: 'listRetainedDataRequestScopes', + operationId: 'ListRetainedDataRequestScopes', + call: (sdk) => sdk.listRetainedDataRequestScopes({ cursor: 'c-1', limit: 20 }), + method: 'GET', + path: entry + '/scopes?cursor=c-1&limit=20', + response: () => json({ items: [{ tenantId: id, organizationId: null }], pageInfo }), + }, + { + name: 'listRetainedDataRequests', + operationId: 'ListRetainedDataRequests', + call: (sdk) => sdk.listRetainedDataRequests(organization, { cursor: 'c-1', limit: 20 }), + method: 'GET', + path: entry + '/requests?group=' + organization + '&cursor=c-1&limit=20', + response: () => json({ items: [item()], pageInfo }), + }, + { + name: 'createRetainedDataExport', + operationId: 'CreateRetainedDataExport', + call: (sdk) => sdk.createRetainedDataExport('tenant', { idempotencyKey: key }), + method: 'POST', + path: entry + '/exports?group=tenant', + headers: { 'Idempotency-Key': key }, + body: {}, + response: () => accepted('export'), + }, + { + name: 'createRetainedDataErasure', + operationId: 'CreateRetainedDataErasure', + call: (sdk) => sdk.createRetainedDataErasure(organization, { idempotencyKey: key }), + method: 'POST', + path: entry + '/erasures?group=' + organization, + headers: { 'Idempotency-Key': key }, + body: {}, + response: () => accepted('erasure'), + }, + { + name: 'createRetainedAccountClosure', + operationId: 'CreateRetainedAccountClosure', + call: (sdk) => sdk.createRetainedAccountClosure('tenant', { idempotencyKey: key }), + method: 'POST', + path: entry + '/closures?group=tenant', + headers: { 'Idempotency-Key': key }, + body: {}, + response: () => accepted('closure'), + }, + { + name: 'cancelRetainedDataRequest', + operationId: 'CancelRetainedDataRequest', + call: (sdk) => sdk.cancelRetainedDataRequest('tenant', id, write), + method: 'POST', + path: entry + '/cancellations?group=tenant', + headers: guarded, + body: { requestId: id }, + response: receipt, + }, + { + name: 'revokeRetainedDataExport', + operationId: 'RevokeRetainedDataExport', + call: (sdk) => sdk.revokeRetainedDataExport(organization, id, write), + method: 'POST', + path: entry + '/revocations?group=' + organization, + headers: guarded, + body: { requestId: id }, + response: receipt, + }, + { + name: 'mintRetainedDataExportTicket', + operationId: 'MintRetainedDataExportTicket', + call: (sdk) => sdk.mintRetainedDataExportTicket('tenant', id), + method: 'POST', + path: entry + '/tickets?group=tenant', + body: { requestId: id }, + response: ticketBody, + }, + { + name: 'readRetainedDataExportChunk', + operationId: 'ReadRetainedDataExportChunk', + call: (sdk) => sdk.readRetainedDataExportChunk('tenant', id, ticket, 1), + method: 'POST', + path: entry + '/chunks?group=tenant', + body: { requestId: id, ticket, index: 1 }, + response: chunkBody, + }, + { + name: 'listDataRequests', + operationId: 'ListDataRequests', + call: (sdk) => sdk.listDataRequests({ cursor: 'c-1', limit: 20 }), + method: 'GET', + path: administered + '?cursor=c-1&limit=20', + response: () => json({ items: [subject()], pageInfo }), + }, + { + name: 'getDataRequest', + operationId: 'GetDataRequest', + call: (sdk) => sdk.getDataRequest(id), + method: 'GET', + path: administered + '/' + id, + response: () => json(subject(), 200, { ETag: '"3"' }), + }, + { + name: 'createDataExportForSubject', + operationId: 'CreateDataExportForSubject', + call: (sdk) => sdk.createDataExportForSubject(member, { idempotencyKey: key }), + method: 'POST', + path: administered + '/exports', + headers: { 'Idempotency-Key': key }, + body: { membershipId: member }, + response: () => accepted('export', administered), + }, + { + name: 'createDataErasureForSubject', + operationId: 'CreateDataErasureForSubject', + call: (sdk) => sdk.createDataErasureForSubject(member, { idempotencyKey: key }), + method: 'POST', + path: administered + '/erasures', + headers: { 'Idempotency-Key': key }, + body: { membershipId: member }, + response: () => accepted('erasure', administered), + }, + { + name: 'cancelDataRequest', + operationId: 'CancelDataRequest', + call: (sdk) => sdk.cancelDataRequest(id, write), + method: 'POST', + path: administered + '/' + id + '/cancellations', + headers: guarded, + body: {}, + response: receipt, + }, + { + name: 'revokeDataExport', + operationId: 'RevokeDataExport', + call: (sdk) => sdk.revokeDataExport(id, write), + method: 'POST', + path: administered + '/' + id + '/artifact/revocations', + headers: guarded, + body: {}, + response: receipt, + }, +]; + +describe('every data-request wrapper puts its documented request on the wire', () => { + it('covers exactly the 24 documented operations, each once', () => { + expect(WRAPPERS).toHaveLength(24); + expect(documented).toHaveLength(24); + expect(WRAPPERS.map((row) => row.operationId).sort()).toEqual( + documented.map(({ operation }) => operation.operationId).sort(), + ); + expect(new Set(WRAPPERS.map((row) => row.name)).size).toBe(24); + const { sdk } = sdkWith(); + for (const row of WRAPPERS) + expect(typeof (sdk as Record<string, unknown>)[row.name]).toBe('function'); + const posts = Object.entries({ + ...DATA_REQUEST_POST_CONTRACTS, + ...DATA_REQUEST_ADMINISTRATION_POST_CONTRACTS, + }); + expect(posts).toHaveLength(18); + expect( + WRAPPERS.filter((row) => row.method === 'POST') + .map((row) => row.operationId) + .sort(), + ).toEqual(posts.map(([, operation]) => operation).sort()); + }); + + it.each(WRAPPERS.map((row) => [row.name, row] as const))( + '%s sends the method, path, query, headers and body of its OpenAPI operation', + async (_name, row) => { + const { sdk, transport } = sdkWith(row.response()); + expect((await row.call(sdk)).kind).toBe('success'); + expect(transport).toHaveBeenCalledOnce(); + const call = sent(transport); + expect(call.method).toBe(row.method); + expect(call.path).toBe(row.path); + expect(call.headers).toEqual({ + Accept: 'application/json', + ...(row.method === 'POST' ? { 'Content-Type': 'application/json' } : {}), + ...row.headers, + }); + expect(call.body).toEqual(row.body); + // The same request, read back against the committed OpenAPI document. + const doc = documented.find(({ operation }) => operation.operationId === row.operationId)!; + const [pathname, search = ''] = call.path.split('?'); + expect(pathname!.replaceAll(id, '{id}')).toBe(doc.path); + expect(row.method).toBe(doc.method); + const parameters = doc.operation.parameters ?? []; + const names = (place: string) => + parameters.filter(({ in: where }) => where === place).map(({ name }) => name); + expect( + Object.keys(call.headers) + .filter((name) => !['Accept', 'Content-Type'].includes(name)) + .sort(), + ).toEqual(names('header').sort()); + const query = [...new URLSearchParams(search).keys()]; + for (const name of query) expect(names('query')).toContain(name); + for (const { name, required } of parameters.filter(({ in: where }) => where === 'query')) + if (required) expect(query).toContain(name); + expect(names('path').length).toBe(pathname!.includes(id) ? 1 : 0); + if (row.method === 'POST') { + const schema = doc.operation + .requestBody!.content['application/json']!.schema.$ref.split('/') + .pop()!; + expect(Object.keys(call.body as object).sort()).toEqual( + Object.keys(schemas[schema]!.properties ?? {}).sort(), + ); + } + }, + ); + + it('keeps every cancellation and revocation wrapper on its own route', async () => { + for (const row of WRAPPERS.filter((value) => /^(?:cancel|revoke)/.test(value.name))) { + const cancel = row.name.startsWith('cancel'); + const { sdk, transport } = sdkWith(row.response()); + expect((await row.call(sdk)).kind).toBe('success'); + const [pathname] = sent(transport).path.split('?'); + expect(pathname!.endsWith(cancel ? '/cancellations' : '/revocations')).toBe(true); + expect(pathname!.endsWith(cancel ? '/revocations' : '/cancellations')).toBe(false); + // A per-request revocation names the artifact; a cancellation never does, and the retained route carries none. + expect(pathname!.includes('/artifact/')).toBe(!cancel && !pathname!.startsWith(entry)); + } + }); +}); + +describe('the closed data-request vocabularies', () => { + const enumOf = (schema: string, property: string) => + schemas[schema]!.properties![property]!.enum!; + it('equal the OpenAPI enums, value for value', () => { + const sorted = (values: readonly (string | null)[]) => [...values].sort(); + expect(sorted(DATA_REQUEST_KINDS)).toEqual(sorted(enumOf('OwnDataRequestResponse', 'kind'))); + expect(sorted(DATA_REQUEST_ORIGINS)).toEqual( + sorted(enumOf('OwnDataRequestResponse', 'origin')), + ); + expect(sorted(DATA_REQUEST_STATUSES)).toEqual( + sorted(enumOf('OwnDataRequestResponse', 'status')), + ); + expect(sorted([...DATA_REQUEST_LAST_REFUSALS, null])).toEqual( + sorted(enumOf('OwnDataRequestResponse', 'lastRefusal')), + ); + expect(sorted([...DATA_REQUEST_FAILURE_REASONS, null])).toEqual( + sorted(enumOf('OwnDataRequestResponse', 'failureReason')), + ); + expect(sorted(DATA_EXPORT_ARTIFACT_STATUSES)).toEqual( + sorted(enumOf('DataExportArtifactResponse', 'status')), + ); + expect(sorted(DATA_REQUEST_RETAINED_KINDS)).toEqual( + sorted(enumOf('DataRequestRetainedResponse', 'kind')), + ); + // The administrator's receipt names the same vocabularies. + for (const property of ['kind', 'origin', 'status']) + expect(enumOf('DataRequestResponse', property)).toEqual( + enumOf('OwnDataRequestResponse', property), + ); + }); + + it('admit a receipt carrying every value of every closed vocabulary', async () => { + const instant = '2026-11-23T10:00:00.0000000+00:00'; + const receipts: OwnDataRequest[] = [ + ...DATA_REQUEST_KINDS.map((kind, index) => + item({ + id: '019a154b-0000-7000-8000-0000000001' + String(index).padStart(2, '0'), + kind, + origin: 'self', + status: 'scheduled', + completedAt: null, + executeAt: kind === 'export' ? null : instant, + artifact: null, + }), + ), + ...DATA_REQUEST_ORIGINS.map((origin, index) => + item({ + id: '019a154b-0000-7000-8000-0000000002' + String(index).padStart(2, '0'), + kind: 'erasure', + origin, + status: 'scheduled', + completedAt: null, + executeAt: instant, + artifact: null, + }), + ), + ...DATA_REQUEST_STATUSES.map((status, index) => + item({ + id: '019a154b-0000-7000-8000-0000000003' + String(index).padStart(2, '0'), + kind: 'erasure', + status, + completedAt: status === 'completed' ? instant : null, + executeAt: null, + artifact: null, + }), + ), + ...DATA_EXPORT_ARTIFACT_STATUSES.map((status, index) => + item({ + id: '019a154b-0000-7000-8000-0000000004' + String(index).padStart(2, '0'), + artifact: { + ...artifact, + status, + readable: status === 'available', + purgedAt: status === 'purged' ? instant : null, + }, + }), + ), + ...DATA_REQUEST_LAST_REFUSALS.map((lastRefusal, index) => + item({ + id: '019a154b-0000-7000-8000-0000000005' + String(index).padStart(2, '0'), + kind: 'erasure', + status: 'blocked', + completedAt: null, + executeAt: null, + artifact: null, + lastRefusal, + }), + ), + ...DATA_REQUEST_FAILURE_REASONS.map((failureReason, index) => + item({ + id: '019a154b-0000-7000-8000-0000000006' + String(index).padStart(2, '0'), + status: 'failed', + completedAt: null, + artifact: null, + failureReason, + }), + ), + item({ + id: '019a154b-0000-7000-8000-000000000700', + kind: 'erasure', + status: 'completed', + executeAt: null, + artifact: null, + retained: DATA_REQUEST_RETAINED_KINDS.map((kind, index) => ({ kind, count: index })), + }), + ]; + // One page holds at most 100 receipts; each value is read back exactly as the API sent it. + expect(receipts.length).toBeLessThanOrEqual(100); + const { sdk } = sdkWith(json({ items: receipts, pageInfo })); + const result = await sdk.listOwnDataRequests({ limit: 100 }); + expect(result.kind).toBe('success'); + if (result.kind !== 'success') return; + expect(result.data.items).toEqual(receipts); + // The same single receipt, one value at a time, so a refused value names itself. + for (const receipt of receipts) { + const { sdk: single } = sdkWith(json(receipt, 200, { ETag: '"' + receipt.version + '"' })); + expect(await single.getOwnDataRequest(receipt.id), JSON.stringify(receipt)).toMatchObject({ + kind: 'success', + }); + } + }); +}); + +describe('the data-request response gate', () => { + it('refuses a success that is not application/json, with or without no-store', async () => { + for (const type of [ + 'text/plain', + 'text/html; charset=utf-8', + 'application/problem+json', + 'application/jsonx', + ]) { + const { sdk } = sdkWith( + new Response(JSON.stringify(item()), { + headers: { 'Content-Type': type, 'Cache-Control': 'no-store', ETag: '"3"' }, + }), + ); + expect(await sdk.getOwnDataRequest(id), type).toEqual({ + kind: 'invalid-response', + reason: 'invalid-success', + }); + } + const { sdk: missing } = sdkWith( + new Response(JSON.stringify(item()), { + headers: { 'Cache-Control': 'no-store', ETag: '"3"' }, + }), + ); + expect((await missing.getOwnDataRequest(id)).kind).toBe('invalid-response'); + }); + + it('refuses an Idempotency-Replayed marker on a call that carries no key', async () => { + const replay = { 'Idempotency-Replayed': 'true' }; + const calls: [string, Response, (sdk: Sdk) => Promise<{ kind: string }>][] = [ + ['a list', json({ items: [], pageInfo }, 200, replay), (sdk) => sdk.listOwnDataRequests()], + ['a read', json(item(), 200, { ETag: '"3"', ...replay }), (sdk) => sdk.getOwnDataRequest(id)], + ['a ticket', ticketResponseWith(replay), (sdk) => sdk.mintOwnDataExportTicket(id)], + [ + 'a chunk', + json({ index: 0, count: 2, bytes: 'AA==' }, 200, replay), + (sdk) => sdk.readOwnDataExportChunk(id, ticket, 0), + ], + [ + 'a retained ticket', + ticketResponseWith(replay), + (sdk) => sdk.mintRetainedDataExportTicket('tenant', id), + ], + ]; + for (const [name, response, call] of calls) { + const { sdk } = sdkWith(response); + expect((await call(sdk)).kind, name).toBe('invalid-response'); + } + // A keyed call may be replayed, and only with the literal value `true`. + const { sdk: keyed } = sdkWith( + json({ version: '4' }, 200, { ETag: '"4"', 'Idempotency-Replayed': 'false' }), + ); + expect((await keyed.cancelOwnDataRequest(id, write)).kind).toBe('invalid-response'); + }); + + it('refuses a page that names a previous page and a page that disagrees with itself', async () => { + for (const bad of [ + { ...pageInfo, previousCursor: 'p-1' }, + { ...pageInfo, previousCursor: 'p-1', hasPrevious: true }, + { ...pageInfo, hasPrevious: true }, + { ...pageInfo, nextCursor: 'n-1' }, + ]) { + const { sdk } = sdkWith(json({ items: [item()], pageInfo: bad })); + expect((await sdk.listOwnDataRequests()).kind).toBe('invalid-response'); + const { sdk: scopes } = sdkWith(json({ items: [], pageInfo: bad })); + expect((await scopes.listRetainedDataRequestScopes()).kind).toBe('invalid-response'); + } + }); + + it('leaves a chunk position to the download relay: any well-formed index is a valid chunk', async () => { + // The relay (and the route test) refuse a chunk whose index is not the one asked for; the SDK validates shape. + const { sdk } = sdkWith(json({ index: 1, count: 2, bytes: 'AA==' })); + expect(await sdk.readOwnDataExportChunk(id, ticket, 0)).toMatchObject({ + kind: 'success', + data: { index: 1, count: 2 }, + }); + }); +}); + +function ticketResponseWith(headers: Record<string, string>) { + return json( + { ticket, expiresAt: artifact.expiresAt, chunkCount: 2, byteCount: 131073 }, + 200, + headers, + ); +} diff --git a/frontend/packages/sdk/src/data-request-server.ts b/frontend/packages/sdk/src/data-request-server.ts new file mode 100644 index 000000000..06faec6b7 --- /dev/null +++ b/frontend/packages/sdk/src/data-request-server.ts @@ -0,0 +1,437 @@ +import type { + AdministrationCreateOptions, + AdministrationFetch, + AdministrationPageOptions, + AdministrationReadOptions, + AdministrationResult, + AdministrationVersion, + AdministrationWriteOptions, +} from './administration-contract.js'; +import { identifier, object, text, version } from './administration-policy.js'; +import type { + DataExportChunk, + DataExportTicket, + DataRequestAccepted, + DataRequestGroup, + OwnDataRequest, + OwnDataRequestPage, + RetainedDataRequestScopePage, + SubjectDataRequest, + SubjectDataRequestPage, +} from './data-request-contract.js'; +import { + dataExportChunkResponse, + dataExportTicket, + dataExportTicketResponse, + dataRequestAccepted, + dataRequestGroup, + ownDataRequest, + ownDataRequestPage, + retainedScopePage, + subjectDataRequest, + subjectDataRequestPage, +} from './data-request-policy.js'; +import { appError, parseProblem } from './response-policy.js'; +export type * from './data-request-contract.js'; + +const own = '/api/v1/identity/me/data-requests'; +const entry = '/api/v1/identity/data-request-entry'; +const administered = '/api/v1/identity/data-requests'; +const maximumBody = 256 * 1024; + +class BodyLimit extends Error { + constructor() { + super('Data request response refused'); + } +} +/** + * Reads one bounded UTF-8 body and zeroes every byte buffer it holds, because a chunk body is decrypted plaintext. + * That covers this reader's own buffers only: the transport's buffers are the transport's to clear, and the decoded + * text and the parsed strings (the chunk's base64 included) cannot be cleared, so this is best effort. A failure to + * decode or parse is a `SyntaxError`; a failure of the body stream itself propagates as it is. + */ +async function read(response: Response, signal?: AbortSignal): Promise<unknown> { + const reader = response.body?.getReader(); + if (!reader) throw new SyntaxError('Data request response refused'); + let cancelling: Promise<void> | undefined; + const cancel = () => { + cancelling ??= reader.cancel().catch(() => undefined); + }; + signal?.addEventListener('abort', cancel, { once: true }); + const chunks: Uint8Array[] = []; + let bytes: Uint8Array | undefined; + let size = 0; + try { + if (signal?.aborted) cancel(); + for (;;) { + const chunk = await reader.read(); + if (signal?.aborted) { + chunk.value?.fill(0); + throw new DOMException('Cancelled', 'AbortError'); + } + if (chunk.done) break; + size += chunk.value.byteLength; + if (size > maximumBody) { + chunk.value.fill(0); + cancel(); + throw new BodyLimit(); + } + chunks.push(chunk.value); + } + bytes = new Uint8Array(size); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + try { + return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) as unknown; + } catch { + throw new SyntaxError('Data request response refused'); + } + } finally { + bytes?.fill(0); + for (const chunk of chunks) chunk.fill(0); + signal?.removeEventListener('abort', cancel); + if (cancelling) await cancelling; + reader.releaseLock(); + } +} + +type Plan = Readonly<{ + path: string | undefined; + method: 'GET' | 'POST'; + body?: unknown; + /** Present for the keyed creations, cancellations and revocations; never for a ticket or chunk. */ + idempotencyKey?: string; + /** A strong precondition: the request's version, or for a revocation the artifact's. */ + version?: string; + /** ETag rule of the success: the body's own `version`, or none. */ + etag: 'version' | 'none'; + /** The exact Location of an own creation; every other success carries none. */ + location?: (value: Record<string, unknown>) => string; +}>; + +/** + * ADR-0106 §§ 3 and 9, ADR-0107 § 4: the subject's own and retained-entry data-request operations, and the + * administrator's operations on the requests of the context's group. The injected native caller owns credentials, + * host, scope and lifetime; nothing here selects a tenant, organization or credential. + */ +export function createDataRequestServerSdk(transport: AdministrationFetch) { + async function request<T, Status extends 200 | 202 = 200>( + plan: Plan, + valid: (value: unknown) => boolean, + expected: Status, + options?: AdministrationReadOptions, + ): Promise<AdministrationResult<T, Status>> { + const signal = options?.signal; + if (signal?.aborted) return { kind: 'cancelled' }; + const headers: Record<string, string> = { Accept: 'application/json' }; + let body: string | undefined; + try { + if (!plan.path) return { kind: 'invalid-request' }; + if (plan.method === 'POST') { + body = JSON.stringify(plan.body ?? {}); + if (new TextEncoder().encode(body).length > 16 * 1024) return { kind: 'invalid-request' }; + headers['Content-Type'] = 'application/json'; + } + if (plan.idempotencyKey !== undefined) { + if (!/^[\x21-\x7e]{8,128}$/.test(plan.idempotencyKey)) return { kind: 'invalid-request' }; + headers['Idempotency-Key'] = plan.idempotencyKey; + } + if (plan.version !== undefined) { + if (!version(plan.version)) return { kind: 'invalid-request' }; + headers['If-Match'] = '"' + plan.version + '"'; + } + } catch { + return { kind: 'invalid-request' }; + } + let response: Response; + try { + response = await transport(plan.path, { + method: plan.method, + cache: 'no-store', + headers, + ...(body === undefined ? {} : { body }), + signal, + }); + } catch { + return { kind: signal?.aborted ? 'cancelled' : 'transport-error' }; + } + if (response.status !== expected && response.status < 400) { + await response.body?.cancel().catch(() => undefined); + return signal?.aborted + ? { kind: 'cancelled' } + : { kind: 'invalid-response', reason: 'unexpected-status' }; + } + let value: unknown; + try { + value = await read(response, signal); + } catch (error) { + if (signal?.aborted) return { kind: 'cancelled' }; + if (error instanceof BodyLimit) + return { + kind: 'invalid-response', + reason: response.status === expected ? 'invalid-success' : 'invalid-problem', + }; + // Only a body that arrived and does not decode is malformed; a body that broke off is the transport's failure. + if (error instanceof SyntaxError) + return { kind: 'invalid-response', reason: 'malformed-json' }; + return { kind: 'transport-error' }; + } + if (signal?.aborted) return { kind: 'cancelled' }; + if (response.status !== expected) { + const problem = parseProblem(value, response.status); + if (!problem) return { kind: 'invalid-response', reason: 'invalid-problem' }; + const error = appError(problem, response.headers.get('Retry-After')); + return { + kind: 'api-error', + status: response.status, + problem, + error: error.code === 'concurrency_conflict' ? { code: 'concurrency_conflict' } : error, + }; + } + const etag = response.headers.get('ETag'); + const location = response.headers.get('Location'); + const replayed = response.headers.get('Idempotency-Replayed'); + if ( + response.headers.get('Content-Type')?.split(';', 1)[0]?.trim().toLowerCase() !== + 'application/json' || + response.headers.get('Cache-Control') !== 'no-store' || + !valid(value) || + !object(value) || + (plan.etag === 'version' ? etag !== '"' + String(value.version) + '"' : etag !== null) || + location !== (plan.location ? plan.location(value) : null) || + (replayed !== null && (plan.idempotencyKey === undefined || replayed !== 'true')) + ) + return { kind: 'invalid-response', reason: 'invalid-success' }; + return { + kind: 'success', + status: expected, + data: value as T, + etag, + location, + replayed: replayed === 'true', + }; + } + const page = ( + path: string, + options: AdministrationPageOptions | undefined, + limit: number, + cursor: number, + group?: string, + ) => { + if ( + (group !== undefined && !dataRequestGroup(group)) || + (options?.cursor !== undefined && + (!text(options.cursor, cursor) || !/^[\x21-\x7e]+$/.test(options.cursor))) || + (options?.limit !== undefined && + (!Number.isSafeInteger(options.limit) || options.limit < 1 || options.limit > limit)) + ) + return undefined; + const query = new URLSearchParams(); + if (group !== undefined) query.set('group', group); + if (options?.cursor !== undefined) query.set('cursor', options.cursor); + if (options?.limit !== undefined) query.set('limit', String(options.limit)); + return path + (query.size ? '?' + query.toString() : ''); + }; + const resource = (id: string, suffix = '', base = own) => + identifier(id) ? base + '/' + id + suffix : undefined; + const grouped = (group: DataRequestGroup, action: string) => + dataRequestGroup(group) + ? entry + '/' + action + '?' + new URLSearchParams({ group }).toString() + : undefined; + const target = (id: string, extra: Record<string, unknown> = {}) => + identifier(id) ? { requestId: id, ...extra } : undefined; + const receipt = (value: unknown) => + object(value) && Object.keys(value).length === 1 && version(value.version); + /** A creation answers 202; its Location names the request under `located`, and a retained one has none. */ + const create = + ( + kind: 'export' | 'erasure' | 'closure', + path: string | undefined, + located: string | undefined, + body: unknown = {}, + ) => + (options: AdministrationCreateOptions) => + request<DataRequestAccepted, 202>( + { + path, + method: 'POST', + body, + idempotencyKey: options.idempotencyKey, + etag: 'version', + ...(located === undefined + ? {} + : { location: (value) => located + '/' + String(value.id) }), + }, + (value) => dataRequestAccepted(value, kind), + 202, + options, + ); + /** ADR-0106 § 3: an administrator names the subject only by a Membership of the group, never by a User. */ + const forSubject = (kind: 'export' | 'erasure', membershipId: string) => + create( + kind, + identifier(membershipId) + ? administered + (kind === 'export' ? '/exports' : '/erasures') + : undefined, + administered, + { membershipId }, + ); + const keyed = (path: string | undefined, body: unknown, options: AdministrationWriteOptions) => + request<AdministrationVersion>( + { + path: body === undefined ? undefined : path, + method: 'POST', + body, + idempotencyKey: options.idempotencyKey, + version: options.version, + etag: 'version', + }, + receipt, + 200, + options, + ); + const chunk = ( + path: string | undefined, + body: Record<string, unknown> | undefined, + options?: AdministrationReadOptions, + ) => + request<DataExportChunk>( + { path: body === undefined ? undefined : path, method: 'POST', body, etag: 'none' }, + dataExportChunkResponse, + 200, + options, + ); + const index = (value: number) => Number.isSafeInteger(value) && value >= 0 && value <= 511; + return Object.freeze({ + listOwnDataRequests: (options?: AdministrationPageOptions) => + request<OwnDataRequestPage>( + { path: page(own, options, 100, 1024), method: 'GET', etag: 'none' }, + (value) => ownDataRequestPage(value, 100), + 200, + options, + ), + getOwnDataRequest: (id: string, options?: AdministrationReadOptions) => + request<OwnDataRequest>( + { path: resource(id), method: 'GET', etag: 'version' }, + (value) => ownDataRequest(value) && (value as { id: string }).id === id, + 200, + options, + ), + createOwnDataExport: create('export', own + '/exports', own), + createOwnDataErasure: create('erasure', own + '/erasures', own), + createOwnAccountClosure: create('closure', own + '/closures', own), + cancelOwnDataRequest: (id: string, options: AdministrationWriteOptions) => + keyed(resource(id, '/cancellations'), {}, options), + revokeOwnDataExport: (id: string, options: AdministrationWriteOptions) => + keyed(resource(id, '/artifact/revocations'), {}, options), + mintOwnDataExportTicket: (id: string, options?: AdministrationReadOptions) => + request<DataExportTicket>( + { path: resource(id, '/artifact/tickets'), method: 'POST', body: {}, etag: 'none' }, + dataExportTicketResponse, + 200, + options, + ), + readOwnDataExportChunk: ( + id: string, + ticket: string, + chunkIndex: number, + options?: AdministrationReadOptions, + ) => + chunk( + resource(id, '/artifact/chunks'), + dataExportTicket(ticket) && index(chunkIndex) ? { ticket, index: chunkIndex } : undefined, + options, + ), + listRetainedDataRequestScopes: (options?: AdministrationPageOptions) => + request<RetainedDataRequestScopePage>( + { path: page(entry + '/scopes', options, 20, 36), method: 'GET', etag: 'none' }, + retainedScopePage, + 200, + options, + ), + listRetainedDataRequests: (group: DataRequestGroup, options?: AdministrationPageOptions) => + request<OwnDataRequestPage>( + { path: page(entry + '/requests', options, 20, 1024, group), method: 'GET', etag: 'none' }, + (value) => ownDataRequestPage(value, 20), + 200, + options, + ), + createRetainedDataExport: (group: DataRequestGroup, options: AdministrationCreateOptions) => + create('export', grouped(group, 'exports'), undefined)(options), + createRetainedDataErasure: (group: DataRequestGroup, options: AdministrationCreateOptions) => + create('erasure', grouped(group, 'erasures'), undefined)(options), + createRetainedAccountClosure: (group: DataRequestGroup, options: AdministrationCreateOptions) => + create('closure', grouped(group, 'closures'), undefined)(options), + cancelRetainedDataRequest: ( + group: DataRequestGroup, + id: string, + options: AdministrationWriteOptions, + ) => keyed(grouped(group, 'cancellations'), target(id), options), + revokeRetainedDataExport: ( + group: DataRequestGroup, + id: string, + options: AdministrationWriteOptions, + ) => keyed(grouped(group, 'revocations'), target(id), options), + mintRetainedDataExportTicket: ( + group: DataRequestGroup, + id: string, + options?: AdministrationReadOptions, + ) => { + const body = target(id); + return request<DataExportTicket>( + { + path: body === undefined ? undefined : grouped(group, 'tickets'), + method: 'POST', + body, + etag: 'none', + }, + dataExportTicketResponse, + 200, + options, + ); + }, + readRetainedDataExportChunk: ( + group: DataRequestGroup, + id: string, + ticket: string, + chunkIndex: number, + options?: AdministrationReadOptions, + ) => + chunk( + grouped(group, 'chunks'), + dataExportTicket(ticket) && index(chunkIndex) + ? target(id, { ticket, index: chunkIndex }) + : undefined, + options, + ), + /** The group's export and erasure requests, newest first: status and counts only (MUST read-sensitive). */ + listDataRequests: (options?: AdministrationPageOptions) => + request<SubjectDataRequestPage>( + { path: page(administered, options, 100, 1024), method: 'GET', etag: 'none' }, + (value) => subjectDataRequestPage(value, 100), + 200, + options, + ), + getDataRequest: (id: string, options?: AdministrationReadOptions) => + request<SubjectDataRequest>( + { path: resource(id, '', administered), method: 'GET', etag: 'version' }, + (value) => subjectDataRequest(value) && (value as { id: string }).id === id, + 200, + options, + ), + createDataExportForSubject: (membershipId: string, options: AdministrationCreateOptions) => + forSubject('export', membershipId)(options), + createDataErasureForSubject: (membershipId: string, options: AdministrationCreateOptions) => + forSubject('erasure', membershipId)(options), + /** Only the administrator who filed the request cancels it; `version` is the request's. */ + cancelDataRequest: (id: string, options: AdministrationWriteOptions) => + keyed(resource(id, '/cancellations', administered), {}, options), + /** Only the administrator who filed the export revokes its artifact; `version` is the ARTIFACT's. */ + revokeDataExport: (id: string, options: AdministrationWriteOptions) => + keyed(resource(id, '/artifact/revocations', administered), {}, options), + }); +} +export type DataRequestServerSdk = ReturnType<typeof createDataRequestServerSdk>; diff --git a/frontend/packages/sdk/src/generated/schema.d.ts b/frontend/packages/sdk/src/generated/schema.d.ts index 7c268b4cc..36ae141e1 100644 --- a/frontend/packages/sdk/src/generated/schema.d.ts +++ b/frontend/packages/sdk/src/generated/schema.d.ts @@ -267,15 +267,15 @@ export interface paths { patch?: never; trace?: never; }; - "/api/v1/identity/federation": { + "/api/v1/identity/data-request-entry/scopes": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - /** @description Current tenant's nonsecret federation connection in an orgless context, under Tenant identity.federation.admin. Audit Off: no personal data. One provider readback under the request deadline; a definitive drift or an expired test window is recorded as a MUST apply outcome. No request body or query. No-store. */ - get: operations["GetFederationConnection"]; + /** @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; @@ -284,16 +284,16 @@ export interface paths { patch?: never; trace?: never; }; - "/api/v1/identity/federation/configuration": { + "/api/v1/identity/data-request-entry/requests": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - get?: never; - /** @description ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited. */ - put: operations["ConfigureFederation"]; + /** @description 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. */ + get: operations["ListRetainedDataRequests"]; + put?: never; post?: never; delete?: never; options?: never; @@ -301,7 +301,7 @@ export interface paths { patch?: never; trace?: never; }; - "/api/v1/identity/federation/secret-rotations": { + "/api/v1/identity/data-request-entry/exports": { parameters: { query?: never; header?: never; @@ -310,15 +310,15 @@ export interface paths { }; get?: never; put?: never; - /** @description ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited. */ - post: operations["RotateFederationSecret"]; + /** @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/federation/display-name": { + "/api/v1/identity/data-request-entry/erasures": { parameters: { query?: never; header?: never; @@ -326,16 +326,16 @@ export interface paths { cookie?: never; }; get?: never; - /** @description ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited. */ - put: operations["RenameFederation"]; - post?: never; + put?: never; + /** @description The subject files an erasure of their own data in one retained group (ADR-0106 § 3, § 9; ADR-0107 § 5): the path of a Suspended person and of one whose Membership was revoked. The request is scheduled and its job runs once the 24-hour window ends; until then it can be cancelled. Refused when the subject holds no Membership of any status there, while the subject is the tenant's only eligible tenant-wide administrator (tenant-wide group) or while a hold applies. Strict empty JSON object. MUST audited. */ + post: operations["CreateRetainedDataErasure"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/identity/federation/test-starts": { + "/api/v1/identity/data-request-entry/closures": { parameters: { query?: never; header?: never; @@ -344,15 +344,15 @@ export interface paths { }; get?: never; put?: never; - /** @description ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited. */ - post: operations["StartFederationTest"]; + /** @description The subject files the closure of their whole account from one retained group, its originating group (ADR-0106 § 3, § 9; ADR-0107 § 7): the path of a Suspended person and of one whose Membership was revoked. An account closure ends the person's account in every tenant and organization where they hold a Membership, not only in this group. The request is scheduled with its execution time 24 hours after it is filed and holds the frozen snapshot of the subject's Memberships of any status in the group. No job is queued: an operator confirms the request with the person and Begins it at or after its execution time, and the person can cancel it until that Begin commits. Once begun it is irreversible: the account stops working at once, the person's data is erased group by group, and the sign-in account is removed when an operator finalizes the closure. No in-product status remains afterwards; the person can read the receipt only while the account still works. Refused when the subject holds no Membership of any status there, while another closure of the subject is active in the group, or while a hold applies. Strict empty JSON object. MUST audited. */ + post: operations["CreateRetainedAccountClosure"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/identity/federation/test-results": { + "/api/v1/identity/data-request-entry/cancellations": { parameters: { query?: never; header?: never; @@ -361,15 +361,15 @@ export interface paths { }; get?: never; put?: never; - /** @description ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited. The access token must also carry the optional federation.test_record client scope, which only the BFF's federation_test authorization requests; an ordinary sign-in or Studio token is refused with 403 before the body is read. */ - post: operations["RecordFederationTestResult"]; + /** @description The subject cancels their own request in one retained group: a requested export (requested to cancelled), or a scheduled erasure before its execution time (scheduled to cancelled). Strict JSON object with requestId only. MUST audited. A scheduled closure is cancelled the same way (scheduled to cancelled) until an operator's Begin commits, also after its execution time; a begun closure is fulfilling and cannot be cancelled. */ + post: operations["CancelRetainedDataRequest"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/identity/federation/activation": { + "/api/v1/identity/data-request-entry/revocations": { parameters: { query?: never; header?: never; @@ -378,15 +378,15 @@ export interface paths { }; get?: never; put?: never; - /** @description ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited. */ - post: operations["ActivateFederation"]; + /** @description The subject revokes an unexpired available artifact of their own request in one retained group, which deletes its chunks at once; the metadata stays as the receipt (ADR-0107 § 4). If-Match carries the ARTIFACT version: the receipt's artifact.version, not the request's. Strict JSON object with requestId only. MUST audited. */ + post: operations["RevokeRetainedDataExport"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/identity/federation/disablement": { + "/api/v1/identity/data-request-entry/tickets": { parameters: { query?: never; header?: never; @@ -395,15 +395,15 @@ export interface paths { }; get?: never; put?: never; - /** @description ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited. */ - post: operations["DisableFederation"]; + /** @description The subject mints a 15-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/federation/enablement": { + "/api/v1/identity/data-request-entry/chunks": { parameters: { query?: never; header?: never; @@ -412,15 +412,15 @@ export interface paths { }; get?: never; put?: never; - /** @description ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited. */ - post: operations["EnableFederation"]; + /** @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/federation/deletion": { + "/api/v1/identity/me/data-requests/exports": { parameters: { query?: never; header?: never; @@ -429,15 +429,15 @@ export interface paths { }; get?: never; put?: never; - /** @description ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited. */ - post: operations["DeleteFederation"]; + /** @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. When it completes, it revokes the subject's previous available artifact in the group, whoever filed that one. Strict empty JSON object. MUST audited. */ + post: operations["CreateOwnDataExport"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/identity/federation/resumption": { + "/api/v1/identity/me/data-requests/erasures": { parameters: { query?: never; header?: never; @@ -446,15 +446,15 @@ export interface paths { }; get?: never; put?: never; - /** @description ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited. */ - post: operations["ResumeFederationOperation"]; + /** @description The subject files an erasure of their own data in the session's group (ADR-0106 § 3; ADR-0107 § 5). Requires an Active Membership in exactly that group; no permission key. The request is scheduled, holds the frozen snapshot of the subject's Memberships of any status in the group, and its job is submitted on the same transaction, due when the 24-hour cancellable window ends. The job then revokes the subject's export artifacts in the group, removes the Membership's role assignments, clears its profile, leaves it as a Revoked tombstone and revokes the pending invitations the subject issued there; the request then awaits the operator's privileged step. Refused while the subject is the tenant's only eligible tenant-wide administrator (tenant-wide group) or while a hold applies. Strict empty JSON object. MUST audited. */ + post: operations["CreateOwnDataErasure"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/identity/invitation-entry/inspections": { + "/api/v1/identity/me/data-requests/closures": { parameters: { query?: never; header?: never; @@ -463,84 +463,83 @@ export interface paths { }; get?: never; put?: never; - /** @description Exact native recipient entry. Strict UTF-8 application/json object, at most 8 KiB, with invitationId and code only. Unknown, repeated and missing fields, query, generic Idempotency-Key and irrelevant conditional headers refuse. Current stock-validated token, installed binding, trusted native source and real host are independently required; no caller scope selectors. No-store and no session/grant publication. Pending inspection and first acceptance each observe current verified provider email. Accepted acceptance preflight selects the Off original-result read before Pending-only If-Match, provider I/O or mutation intents. Unknown commit outcomes require explicit original-result reconciliation; never automatically retry. */ - post: operations["InspectInvitation"]; + /** @description The subject files the closure of their whole account from the session's group, its originating group (ADR-0106 § 3; ADR-0107 § 7). Only the person files one; no administrator can file, read or cancel a closure. Requires an Active Membership in exactly that group; no permission key. An account closure ends the person's account in every tenant and organization where they hold a Membership, not only in this group. The request is scheduled with its execution time 24 hours after it is filed and holds the frozen snapshot of the subject's Memberships of any status in the group. No job is queued: an operator confirms the request with the person and Begins it at or after its execution time, and the person can cancel it until that Begin commits. Once begun it is irreversible: the account stops working at once, the person's data is erased group by group, and the sign-in account is removed when an operator finalizes the closure. No in-product status remains afterwards; the person can read the receipt only while the account still works. Refused while another closure of the subject is active in the group or while a hold applies. Strict empty JSON object. MUST audited. */ + post: operations["CreateOwnAccountClosure"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/identity/invitation-entry/acceptances": { + "/api/v1/identity/me/data-requests": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - get?: 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; - /** @description Exact native recipient entry. Strict UTF-8 application/json object, at most 8 KiB, with invitationId and code only. Unknown, repeated and missing fields, query, generic Idempotency-Key and irrelevant conditional headers refuse. Current stock-validated token, installed binding, trusted native source and real host are independently required; no caller scope selectors. No-store and no session/grant publication. Pending inspection and first acceptance each observe current verified provider email. Accepted acceptance preflight selects the Off original-result read before Pending-only If-Match, provider I/O or mutation intents. Unknown commit outcomes require explicit original-result reconciliation; never automatically retry. */ - post: operations["AcceptInvitation"]; + post?: never; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/identity/invitation-entry/results": { + "/api/v1/identity/me/data-requests/{id}": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - get?: never; + /** @description The subject's own request receipt: identity, kind, origin, status, timestamps, the recorded refusal or failure code, the closed retained-reference kinds with their counts (the list is partial: a kind absent from it is not counted, which is not zero) and the artifact's metadata. No content. Audit Off. No request body. */ + get: operations["GetOwnDataRequest"]; put?: never; - /** @description Exact native recipient entry. Strict UTF-8 application/json object, at most 8 KiB, with invitationId and code only. Unknown, repeated and missing fields, query, generic Idempotency-Key and irrelevant conditional headers refuse. Current stock-validated token, installed binding, trusted native source and real host are independently required; no caller scope selectors. No-store and no session/grant publication. Pending inspection and first acceptance each observe current verified provider email. Accepted acceptance preflight selects the Off original-result read before Pending-only If-Match, provider I/O or mutation intents. Unknown commit outcomes require explicit original-result reconciliation; never automatically retry. */ - post: operations["GetOwnInvitationResult"]; + post?: never; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/identity/invitations": { + "/api/v1/identity/me/data-requests/{id}/cancellations": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - /** @description Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization. */ - get: operations["ListInvitations"]; + get?: never; put?: never; - /** @description Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried. */ - post: operations["CreateInvitation"]; + /** @description The subject cancels a requested export (requested to cancelled) or a scheduled erasure before its execution time (scheduled to cancelled). A request already fulfilling finishes. Strict empty JSON object. MUST audited. A scheduled closure is cancelled the same way (scheduled to cancelled) until an operator's Begin commits, also after its execution time; a begun closure is fulfilling and cannot be cancelled. */ + post: operations["CancelOwnDataRequest"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/identity/invitations/{id}": { + "/api/v1/identity/me/data-requests/{id}/artifact/revocations": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - /** @description Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization. */ - get: operations["GetInvitation"]; + get?: never; put?: never; - post?: 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/invitations/{id}/revocations": { + "/api/v1/identity/me/data-requests/{id}/artifact/tickets": { parameters: { query?: never; header?: never; @@ -549,15 +548,15 @@ export interface paths { }; get?: never; put?: never; - /** @description Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried. */ - post: operations["RevokeInvitation"]; + /** @description The subject mints a 15-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/invitations/{id}/reissues": { + "/api/v1/identity/me/data-requests/{id}/artifact/chunks": { parameters: { query?: never; header?: never; @@ -566,76 +565,74 @@ export interface paths { }; get?: never; put?: never; - /** @description Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried. */ - post: operations["ReissueInvitation"]; + /** @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/invitable-roles": { + "/api/v1/identity/data-requests/exports": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - /** @description Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization. */ - get: operations["ListInvitableRoles"]; + get?: never; put?: never; - post?: 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. Refused while the person holds a readable artifact in the group, of any origin, because the new export would revoke it. 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/memberships/{id}/custom-fields": { + "/api/v1/identity/data-requests/erasures": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - /** @description Fresh exact scoped projection. No body; only the declared query keys. No-store. Own consent history remains available through retained scope without an Active Membership; it never authorizes a grant or profile write. */ - get: operations["GetMembershipCustomFields"]; + get?: never; put?: never; - post?: never; + /** @description An administrator holding identity.membership.admin over the group files an erasure for the person who held the named Membership in the group, only once that Membership is Revoked: an Active or Suspended member is revoked first, by the separately audited administration act (ADR-0106 § 3). Never for themselves. The request is scheduled and runs when its 24-hour window ends; the administrator who filed it may cancel it until then. Status and counts only. Strict JSON object with membershipId only. MUST audited. */ + post: operations["CreateDataErasureForSubject"]; delete?: never; options?: never; head?: never; - /** @description Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions. */ - patch: operations["SetMembershipCustomFields"]; + patch?: never; trace?: never; }; - "/api/v1/identity/me/custom-fields": { + "/api/v1/identity/data-requests": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - /** @description Fresh exact scoped projection. No body; only the declared query keys. No-store. Own consent history remains available through retained scope without an Active Membership; it never authorizes a grant or profile write. */ - get: operations["GetOwnMembershipCustomFields"]; + /** @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; - /** @description Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions. */ - patch: operations["SetOwnMembershipCustomFields"]; + patch?: never; trace?: never; }; - "/api/v1/identity/memberships": { + "/api/v1/identity/data-requests/{id}": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - /** @description Tenant administrative membership directory requiring current Tenant identity.membership.admin. Rechecks live membership, lifecycle and capability for every page; accepts HostAndClaim, confirmed ClaimAndMembership (including a legacy platform host), or independently verified HostAndNativeSessionScope on a real Tenant/Organization host. Returns only membership/user/organization identifiers, status, contextual displayName and preferredLocale. Active/Suspended undeleted memberships only, ordered by membership UUID. No search, sorting, editing, provider data, grants or global profile. No-store; the MUST ReadSensitive audit row commits before any result is disclosed. The closed native listMemberships caller retains the same live page authority and MUST ReadSensitive audit; native transport grants no additional authority. */ - get: operations["ListMemberships"]; + /** @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; @@ -644,24 +641,24 @@ export interface paths { patch?: never; trace?: never; }; - "/api/v1/identity/memberships/{id}": { + "/api/v1/identity/data-requests/{id}/cancellations": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - /** @description Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization. */ - get: operations["GetMembershipDetail"]; + get?: never; put?: never; - post?: never; + /** @description The administrator who filed a request cancels it: an export while it is still requested, an erasure before its execution time. Strict empty JSON object. MUST audited. */ + post: operations["CancelDataRequest"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/identity/memberships/{id}/profile": { + "/api/v1/identity/data-requests/{id}/artifact/revocations": { parameters: { query?: never; header?: never; @@ -669,25 +666,25 @@ export interface paths { cookie?: never; }; get?: never; - /** @description Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried. */ - put: operations["SetMembershipProfile"]; - post?: 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/memberships/{id}/role-assignments": { + "/api/v1/identity/federation": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - get?: never; - /** @description Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried. */ - put: operations["ReplaceMembershipRoleAssignments"]; + /** @description Current tenant's nonsecret federation connection in an orgless context, under Tenant identity.federation.admin. Audit Off: no personal data. One provider readback under the request deadline; a definitive drift or an expired test window is recorded as a MUST apply outcome. No request body or query. No-store. */ + get: operations["GetFederationConnection"]; + put?: never; post?: never; delete?: never; options?: never; @@ -695,7 +692,7 @@ export interface paths { patch?: never; trace?: never; }; - "/api/v1/identity/memberships/{id}/status": { + "/api/v1/identity/federation/configuration": { parameters: { query?: never; header?: never; @@ -703,8 +700,8 @@ export interface paths { cookie?: never; }; get?: never; - /** @description Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried. */ - put: operations["ChangeMembershipStatus"]; + /** @description ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited. */ + put: operations["ConfigureFederation"]; post?: never; delete?: never; options?: never; @@ -712,7 +709,7 @@ export interface paths { patch?: never; trace?: never; }; - "/api/v1/identity/session-scope/admissions": { + "/api/v1/identity/federation/secret-rotations": { parameters: { query?: never; header?: never; @@ -721,24 +718,24 @@ export interface paths { }; get?: never; put?: never; - /** @description Explicit initial selection or scope switch only. Requires a current native source, real host ceiling and live stored-actor membership/lifecycle. The central MUST security event names the admitted Membership and commits before an association witness is returned. This proves API admission, never cookie delivery. Ordinary refresh uses Off self/AccountSite reads and does not invoke this POST. No query or Idempotency-Key; empty JSON object only. */ - post: operations["AdmitNativeSessionScope"]; + /** @description ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited. */ + post: operations["RotateFederationSecret"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/identity/organization-memberships": { + "/api/v1/identity/federation/display-name": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - /** @description Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization. */ - get: operations["ListOrganizationMemberships"]; - put?: never; + get?: never; + /** @description ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited. */ + put: operations["RenameFederation"]; post?: never; delete?: never; options?: never; @@ -746,110 +743,109 @@ export interface paths { patch?: never; trace?: never; }; - "/api/v1/identity/me/profile": { + "/api/v1/identity/federation/test-starts": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - /** @description Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization. */ - get: operations["GetOwnMembershipProfile"]; - /** @description Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried. */ - put: operations["SetOwnMembershipProfile"]; - post?: never; + get?: never; + put?: never; + /** @description ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited. */ + post: operations["StartFederationTest"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/identity/me/contexts": { + "/api/v1/identity/federation/test-results": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - /** @description Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization. */ - get: operations["ListOwnMembershipContexts"]; + get?: never; put?: never; - post?: never; + /** @description ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited. The access token must also carry the optional federation.test_record client scope, which only the BFF's federation_test authorization requests; an ordinary sign-in or Studio token is refused with 403 before the body is read. */ + post: operations["RecordFederationTestResult"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/identity/me/capabilities": { + "/api/v1/identity/federation/activation": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - /** @description Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization. */ - get: operations["GetOwnCapabilities"]; + get?: never; put?: never; - post?: never; + /** @description ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited. */ + post: operations["ActivateFederation"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/identity/permissions": { + "/api/v1/identity/federation/disablement": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - /** @description Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization. */ - get: operations["GetPermissionRegistry"]; + get?: never; put?: never; - post?: never; + /** @description ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited. */ + post: operations["DisableFederation"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/identity/roles": { + "/api/v1/identity/federation/enablement": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - /** @description Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization. */ - get: operations["ListRoles"]; + get?: never; put?: never; - post?: never; + /** @description ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited. */ + post: operations["EnableFederation"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/identity/roles/{id}": { + "/api/v1/identity/federation/deletion": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - /** @description Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization. */ - get: operations["GetRoleDetail"]; + get?: never; put?: never; - post?: never; + /** @description ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited. */ + post: operations["DeleteFederation"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/identity/roles/{id}/grants": { + "/api/v1/identity/federation/resumption": { parameters: { query?: never; header?: never; @@ -857,16 +853,16 @@ export interface paths { cookie?: never; }; get?: never; - /** @description Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried. */ - put: operations["ChangeRoleGrants"]; - post?: never; + put?: never; + /** @description ADR-0099 intent-first federation operation under Tenant identity.federation.admin in an orgless context. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. No Idempotency-Key: the operation converges through If-Match on the connection revision, the pending operation and a fresh read. Every settled outcome is 200 with its outcome; an uncertain or pending operation is settled later by Resume after its quiet window. A secret is never returned, logged or audited. */ + post: operations["ResumeFederationOperation"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/identity/roles/{id}/manifest-adoptions": { + "/api/v1/identity/invitation-entry/inspections": { parameters: { query?: never; header?: never; @@ -875,85 +871,84 @@ export interface paths { }; get?: never; put?: never; - /** @description Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried. */ - post: operations["AdoptRoleGrantManifest"]; + /** @description Exact native recipient entry. Strict UTF-8 application/json object, at most 8 KiB, with invitationId and code only. Unknown, repeated and missing fields, query, generic Idempotency-Key and irrelevant conditional headers refuse. Current stock-validated token, installed binding, trusted native source and real host are independently required; no caller scope selectors. No-store and no session/grant publication. Pending inspection and first acceptance each observe current verified provider email. Accepted acceptance preflight selects the Off original-result read before Pending-only If-Match, provider I/O or mutation intents. Unknown commit outcomes require explicit original-result reconciliation; never automatically retry. */ + post: operations["InspectInvitation"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/customization/custom-field-definitions": { + "/api/v1/identity/invitation-entry/acceptances": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - /** @description Fresh exact scoped projection. No body; only the declared query keys. No-store. Own consent history remains available through retained scope without an Active Membership; it never authorizes a grant or profile write. */ - get: operations["ListCustomFieldDefinitions"]; + get?: never; put?: never; - /** @description Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions. */ - post: operations["RegisterCustomFieldDefinition"]; + /** @description Exact native recipient entry. Strict UTF-8 application/json object, at most 8 KiB, with invitationId and code only. Unknown, repeated and missing fields, query, generic Idempotency-Key and irrelevant conditional headers refuse. Current stock-validated token, installed binding, trusted native source and real host are independently required; no caller scope selectors. No-store and no session/grant publication. Pending inspection and first acceptance each observe current verified provider email. Accepted acceptance preflight selects the Off original-result read before Pending-only If-Match, provider I/O or mutation intents. Unknown commit outcomes require explicit original-result reconciliation; never automatically retry. */ + post: operations["AcceptInvitation"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/customization/custom-field-definitions/{id}": { + "/api/v1/identity/invitation-entry/results": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - /** @description Fresh exact scoped projection. No body; only the declared query keys. No-store. Own consent history remains available through retained scope without an Active Membership; it never authorizes a grant or profile write. */ - get: operations["GetCustomFieldDefinition"]; - /** @description Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions. */ - put: operations["ReviseCustomFieldDefinitionDraft"]; - post?: never; + get?: never; + put?: never; + /** @description Exact native recipient entry. Strict UTF-8 application/json object, at most 8 KiB, with invitationId and code only. Unknown, repeated and missing fields, query, generic Idempotency-Key and irrelevant conditional headers refuse. Current stock-validated token, installed binding, trusted native source and real host are independently required; no caller scope selectors. No-store and no session/grant publication. Pending inspection and first acceptance each observe current verified provider email. Accepted acceptance preflight selects the Off original-result read before Pending-only If-Match, provider I/O or mutation intents. Unknown commit outcomes require explicit original-result reconciliation; never automatically retry. */ + post: operations["GetOwnInvitationResult"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/customization/custom-field-definitions/{id}/revisions": { + "/api/v1/identity/invitations": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - /** @description Fresh exact scoped projection. No body; only the declared query keys. No-store. Own consent history remains available through retained scope without an Active Membership; it never authorizes a grant or profile write. */ - get: operations["ListCustomFieldDefinitionRevisions"]; + /** @description Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization. */ + get: operations["ListInvitations"]; put?: never; - post?: never; + /** @description Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried. */ + post: operations["CreateInvitation"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/customization/custom-field-definitions/{id}/publication": { + "/api/v1/identity/invitations/{id}": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - get?: never; + /** @description Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization. */ + get: operations["GetInvitation"]; put?: never; - /** @description Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions. */ - post: operations["PublishCustomFieldDefinition"]; + post?: never; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/customization/custom-field-definitions/{id}/retirement": { + "/api/v1/identity/invitations/{id}/revocations": { parameters: { query?: never; header?: never; @@ -962,15 +957,15 @@ export interface paths { }; get?: never; put?: never; - /** @description Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions. */ - post: operations["RetireCustomFieldDefinition"]; + /** @description Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried. */ + post: operations["RevokeInvitation"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/customization/custom-field-definitions/{id}/discard": { + "/api/v1/identity/invitations/{id}/reissues": { parameters: { query?: never; header?: never; @@ -979,23 +974,23 @@ export interface paths { }; get?: never; put?: never; - /** @description Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions. */ - post: operations["DiscardCustomFieldDefinitionDraft"]; + /** @description Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried. */ + post: operations["ReissueInvitation"]; delete?: never; options?: never; head?: never; patch?: never; trace?: never; }; - "/api/v1/account/site": { + "/api/v1/identity/invitable-roles": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - /** @description Authenticated host-backed read through the physical read-only pipeline. Returns only the validated actor UUID, resolved tenant/organization UUIDs and existing public site projection. Accepts no query parameters or client-selected identifiers. No response caching or validators. */ - get: operations["GetAccountSite"]; + /** @description Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization. */ + get: operations["ListInvitableRoles"]; put?: never; post?: never; delete?: never; @@ -1004,49 +999,51 @@ export interface paths { patch?: never; trace?: never; }; - "/api/v1/identity/self": { + "/api/v1/identity/memberships/{id}/custom-fields": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - /** @description Off self-only binding read. Missing is distinct from Active; Closing/Closed/conflicting bindings return 401 and never look missing. federationAlias is the host tenant's Active, entitled federation alias or null, read through the one host-only read-only setter; an undecidable read is 503 and never null. It is a provider hint for the BFF host binding, not authority. No request body, query or assertion/scope selectors. */ - get: operations["GetIdentitySelf"]; + /** @description Fresh exact scoped projection. No body; only the declared query keys. No-store. Own consent history remains available through retained scope without an Active Membership; it never authorizes a grant or profile write. */ + get: operations["GetMembershipCustomFields"]; put?: never; post?: never; delete?: never; options?: never; head?: never; - patch?: never; + /** @description Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions. */ + patch: operations["SetMembershipCustomFields"]; trace?: never; }; - "/api/v1/identity/self/bootstrap": { + "/api/v1/identity/me/custom-fields": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - get?: never; + /** @description Fresh exact scoped projection. No body; only the declared query keys. No-store. Own consent history remains available through retained scope without an Active Membership; it never authorizes a grant or profile write. */ + get: operations["GetOwnMembershipCustomFields"]; put?: never; - /** @description Opt-in tenantless natural-key convergent create. New binding returns 201, existing/racing winner returns 200; unknown COMMIT returns 503 and a deliberate retry resolves the actual stored binding. Real creation alone writes the central MUST event. No membership, scoped session or browser cookie is created. Idempotency-Key and scope/assertion selectors are refused. Empty JSON object only, at most 512 bytes. */ - post: operations["BootstrapIdentitySelf"]; + post?: never; delete?: never; options?: never; head?: never; - patch?: never; + /** @description Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions. */ + patch: operations["SetOwnMembershipCustomFields"]; trace?: never; }; - "/api/v1/identity/self/contexts": { + "/api/v1/identity/memberships": { parameters: { query?: never; header?: never; path?: never; cookie?: never; }; - /** @description Off self-only navigation read. Returns only Active self membership scopes with live tenant/organization labels and configured HTTPS entry origins. No profiles, role grants or arbitrary actor selection. Forward-only subject-bound seek cursor, not authority or a snapshot. No request body or assertion/scope selectors. */ - get: operations["ListIdentitySelfContexts"]; + /** @description Tenant administrative membership directory requiring current Tenant identity.membership.admin. Rechecks live membership, lifecycle and capability for every page; accepts HostAndClaim, confirmed ClaimAndMembership (including a legacy platform host), or independently verified HostAndNativeSessionScope on a real Tenant/Organization host. Returns only membership/user/organization identifiers, status, contextual displayName and preferredLocale. Active/Suspended undeleted memberships only, ordered by membership UUID. No search, sorting, editing, provider data, grants or global profile. No-store; the MUST ReadSensitive audit row commits before any result is disclosed. The closed native listMemberships caller retains the same live page authority and MUST ReadSensitive audit; native transport grants no additional authority. */ + get: operations["ListMemberships"]; put?: never; post?: never; delete?: never; @@ -1055,874 +1052,4193 @@ export interface paths { patch?: never; trace?: never; }; -} -export type webhooks = Record<string, never>; -export interface components { - schemas: { - AccountSite: { - actorId: components["schemas"]["UserId"]; - tenantId: components["schemas"]["TenantId"]; - organizationId: null | components["schemas"]["OrganizationId"]; - site: components["schemas"]["PublicSite"]; + "/api/v1/identity/memberships/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; }; - AdministrationGrantResponse: { - /** @enum {string} */ - scope: "Tenant"; - /** @enum {string} */ - key: "customization.custom_field.admin"; - } | { - /** @enum {string} */ - scope: "Tenant"; - /** @enum {string} */ - key: "identity.federation.admin"; - } | { - /** @enum {string} */ - scope: "Tenant"; - /** @enum {string} */ - key: "identity.membership.admin"; - } | { - /** @enum {string} */ - scope: "Tenant"; - /** @enum {string} */ - key: "identity.membership_profile.write"; - } | { - /** @enum {string} */ - scope: "Tenant"; - /** @enum {string} */ - key: "identity.role.admin"; - } | { - /** @enum {string} */ - scope: "Tenant"; - /** @enum {string} */ - key: "tenancy.locale.write"; - } | { - /** @enum {string} */ - scope: "Tenant"; - /** @enum {string} */ - key: "tenancy.organization.admin"; - } | { - /** @enum {string} */ - scope: "Tenant"; - /** @enum {string} */ - key: "tenancy.setting.write"; - } | { - /** @enum {string} */ - scope: "Organization"; - /** @enum {string} */ - key: "identity.membership.admin"; - } | { - /** @enum {string} */ - scope: "Organization"; - /** @enum {string} */ - key: "identity.membership_profile.write"; + /** @description Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization. */ + get: operations["GetMembershipDetail"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/memberships/{id}/profile": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; }; - AdministrationVersionReceipt: { - /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ - version: string; + get?: never; + /** @description Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried. */ + put: operations["SetMembershipProfile"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/memberships/{id}/role-assignments": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; }; - ConsentDetailsResponse: { - /** Format: uuid */ - evidenceId: string; - sequence: string; - isGranted: boolean; - /** Format: uuid */ - membershipId: string; - /** Format: uuid */ - definitionId: string; - definitionVersion: number; - purposeKey: string; - noticeLocale: string; - noticeHash: string; - noticeText: string; - labels: components["schemas"]["CustomFieldLocalizedText"]; + get?: never; + /** @description Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried. */ + put: operations["ReplaceMembershipRoleAssignments"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/memberships/{id}/status": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; }; - ConsentHistoryPageResponse: { - items: components["schemas"]["ConsentDetailsResponse"][]; - pageInfo: components["schemas"]["PageInfo"]; + get?: never; + /** @description Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried. */ + put: operations["ChangeMembershipStatus"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/session-scope/admissions": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; }; - ConsentScopePageResponse: { - items: { - /** Format: uuid */ - membershipId: string; - /** Format: uuid */ - tenantId: string; - organizationId: string | null; - }[]; - pageInfo: components["schemas"]["PageInfo"]; + get?: never; + put?: never; + /** @description Explicit initial selection or scope switch only. Requires a current native source, real host ceiling and live stored-actor membership/lifecycle. The central MUST security event names the admitted Membership and commits before an association witness is returned. This proves API admission, never cookie delivery. Ordinary refresh uses Off self/AccountSite reads and does not invoke this POST. No query or Idempotency-Key; empty JSON object only. */ + post: operations["AdmitNativeSessionScope"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/organization-memberships": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; }; - CustomFieldDefinitionInput: { - /** @enum {string} */ - targetEntity: "Membership"; - key: string; - schemaVersion: number; - schema: components["schemas"]["CustomFieldFiniteSchema"]; - labels: components["schemas"]["CustomFieldLocalizedText"]; - /** @enum {string} */ - piiCategory: "None" | "Identity" | "Behaviour" | "Sensitive"; - isRequired: boolean; - sort: number; - purposeKey: string | null; - notices: components["schemas"]["CustomFieldNoticeText"] | null; - formLabels: components["schemas"]["CustomFieldFormLabel"][] | null; + /** @description Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization. */ + get: operations["ListOrganizationMemberships"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/me/profile": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; }; - CustomFieldDefinitionPageResponse: { - items: components["schemas"]["CustomFieldDefinitionResponse"][]; - pageInfo: components["schemas"]["PageInfo"]; + /** @description Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization. */ + get: operations["GetOwnMembershipProfile"]; + /** @description Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried. */ + put: operations["SetOwnMembershipProfile"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/me/contexts": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; }; - CustomFieldDefinitionResponse: { - /** @enum {string} */ - targetEntity: "Membership"; - key: string; - schemaVersion: number; - schema: components["schemas"]["CustomFieldFiniteSchema"]; - labels: components["schemas"]["CustomFieldLocalizedText"]; - /** @enum {string} */ - piiCategory: "None" | "Identity" | "Behaviour" | "Sensitive"; - isRequired: boolean; - sort: number; - purposeKey: string | null; - notices: components["schemas"]["CustomFieldNoticeText"] | null; - formLabels: components["schemas"]["CustomFieldFormLabel"][] | null; - /** Format: uuid */ - definitionId: string; - /** @enum {string} */ - status: "Draft" | "Active" | "Deprecated"; - version: string; - isDiscarded: boolean; - maximumValueBytes: number; - activeRevision: { - /** Format: uuid */ - id: string; - version: string; - } | null; + /** @description Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization. */ + get: operations["ListOwnMembershipContexts"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/me/capabilities": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; }; - CustomFieldFiniteSchema: { - /** @enum {string} */ - $schema: "https://json-schema.org/draft/2020-12/schema"; - /** @enum {string} */ - type: "object"; - properties: { - value: components["schemas"]["CustomFieldSchemaNode0"]; - }; - required: "value"[]; - /** @enum {boolean} */ - additionalProperties: false; + /** @description Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization. */ + get: operations["GetOwnCapabilities"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/permissions": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; }; - CustomFieldFormLabel: { - location: string; - labels: components["schemas"]["CustomFieldLocalizedText"] | null; - choices: components["schemas"]["CustomFieldLocalizedText"][] | null; + /** @description Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization. */ + get: operations["GetPermissionRegistry"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/roles": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; }; - CustomFieldLocalizedText: { - [key: string]: string; + /** @description Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization. */ + get: operations["ListRoles"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/roles/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; }; - CustomFieldNoticeHashes: { - [key: string]: string; + /** @description Current live scoped read. No request body; only the declared query fields are accepted. Protected configuration and other-person reads commit their MUST read audit before disclosure. Own context/capability/profile navigation is Off. No-store; capability flags are advisory and never authorization. */ + get: operations["GetRoleDetail"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/roles/{id}/grants": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; }; - CustomFieldNoticeText: { - [key: string]: string; + get?: never; + /** @description Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried. */ + put: operations["ChangeRoleGrants"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/roles/{id}/manifest-adoptions": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; }; - CustomFieldPublicationInput: { - expectedIncumbentId: string | null; - expectedIncumbentVersion: string | null; + get?: never; + put?: never; + /** @description Exact protected mutation. Strict UTF-8 application/json object, at most 16 KiB; unknown, duplicate and missing properties refuse. Current authority, exact target scope and business predicates are checked independently. A completed exact-key replay performs a fresh MUST original-target disclosure read before returning the retained receipt; it never reruns the mutation. Unknown outcomes do not prove rollback and are never automatically retried. */ + post: operations["AdoptRoleGrantManifest"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/customization/custom-field-definitions": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; }; - CustomFieldReceiptResponse: { - /** Format: uuid */ - id: string; - version: string; + /** @description Fresh exact scoped projection. No body; only the declared query keys. No-store. Own consent history remains available through retained scope without an Active Membership; it never authorizes a grant or profile write. */ + get: operations["ListCustomFieldDefinitions"]; + put?: never; + /** @description Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions. */ + post: operations["RegisterCustomFieldDefinition"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/customization/custom-field-definitions/{id}": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; }; - CustomFieldSchemaNode0: { - /** @enum {string} */ - type: "string"; - minLength: number; - maxLength: number; - } | { - /** @enum {string} */ - type: "string"; - minLength: number; - maxLength: number; - enum: string[]; - } | { - /** @enum {string} */ - type: "integer"; - minimum: number; - maximum: number; - } | { - /** @enum {string} */ - type: "number"; - minimum: number; - maximum: number; - } | { - /** @enum {string} */ - type: "boolean"; - } | { - /** @enum {string} */ - type: "object"; - properties: { - [key: string]: components["schemas"]["CustomFieldSchemaNode1"]; - }; - required: string[]; - /** @enum {boolean} */ - additionalProperties: false; - } | { - /** @enum {string} */ - type: "array"; - items: components["schemas"]["CustomFieldSchemaNode1"]; - minItems: number; - maxItems: number; + /** @description Fresh exact scoped projection. No body; only the declared query keys. No-store. Own consent history remains available through retained scope without an Active Membership; it never authorizes a grant or profile write. */ + get: operations["GetCustomFieldDefinition"]; + /** @description Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions. */ + put: operations["ReviseCustomFieldDefinitionDraft"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/customization/custom-field-definitions/{id}/revisions": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; }; - CustomFieldSchemaNode1: { - /** @enum {string} */ - type: "string"; - minLength: number; - maxLength: number; - } | { - /** @enum {string} */ - type: "string"; - minLength: number; - maxLength: number; - enum: string[]; - } | { - /** @enum {string} */ - type: "integer"; - minimum: number; - maximum: number; - } | { - /** @enum {string} */ - type: "number"; - minimum: number; - maximum: number; - } | { - /** @enum {string} */ - type: "boolean"; - } | { - /** @enum {string} */ - type: "object"; - properties: { - [key: string]: components["schemas"]["CustomFieldSchemaNode2"]; - }; - required: string[]; - /** @enum {boolean} */ - additionalProperties: false; - } | { + /** @description Fresh exact scoped projection. No body; only the declared query keys. No-store. Own consent history remains available through retained scope without an Active Membership; it never authorizes a grant or profile write. */ + get: operations["ListCustomFieldDefinitionRevisions"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/customization/custom-field-definitions/{id}/publication": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** @description Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions. */ + post: operations["PublishCustomFieldDefinition"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/customization/custom-field-definitions/{id}/retirement": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** @description Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions. */ + post: operations["RetireCustomFieldDefinition"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/customization/custom-field-definitions/{id}/discard": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** @description Closed UTF-8 JSON mutation, at most 4 KiB raw and normalized input; duplicate/unknown/missing names refuse. Exact versioned scoped HMAC idempotency; retained receipts contain identifiers and versions only, with fresh original-target MUST disclosure before replay. No automatic retry or exactly-once claim. Missing configured current/retained HMAC material fails only these new mutations closed. Consent uses exact predecessor body CAS, not If-Match; grants require own Active Membership and explicit notice confirmation. Withdrawal remains independent of profile-write or administration permissions. */ + post: operations["DiscardCustomFieldDefinitionDraft"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/account/site": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** @description Authenticated host-backed read through the physical read-only pipeline. Returns only the validated actor UUID, resolved tenant/organization UUIDs and existing public site projection. Accepts no query parameters or client-selected identifiers. No response caching or validators. */ + get: operations["GetAccountSite"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/self": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** @description Off self-only binding read. Missing is distinct from Active; Closing/Closed/conflicting bindings return 401 and never look missing. federationAlias is the host tenant's Active, entitled federation alias or null, read through the one host-only read-only setter; an undecidable read is 503 and never null. It is a provider hint for the BFF host binding, not authority. No request body, query or assertion/scope selectors. */ + get: operations["GetIdentitySelf"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/self/bootstrap": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** @description Opt-in tenantless natural-key convergent create. New binding returns 201, existing/racing winner returns 200; unknown COMMIT returns 503 and a deliberate retry resolves the actual stored binding. Real creation alone writes the central MUST event. No membership, scoped session or browser cookie is created. Idempotency-Key and scope/assertion selectors are refused. Empty JSON object only, at most 512 bytes. */ + post: operations["BootstrapIdentitySelf"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/identity/self/contexts": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** @description Off self-only navigation read. Returns only Active self membership scopes with live tenant/organization labels and configured HTTPS entry origins. No profiles, role grants or arbitrary actor selection. Forward-only subject-bound seek cursor, not authority or a snapshot. No request body or assertion/scope selectors. */ + get: operations["ListIdentitySelfContexts"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; +} +export type webhooks = Record<string, never>; +export interface components { + schemas: { + AccountClosureAcceptedResponse: { + /** Format: uuid */ + id: string; /** @enum {string} */ - type: "array"; - items: components["schemas"]["CustomFieldSchemaNode2"]; - minItems: number; - maxItems: number; + kind: "closure"; + /** @enum {string} */ + status: "scheduled"; + /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ + version: string; }; - CustomFieldSchemaNode2: { + AccountSite: { + actorId: components["schemas"]["UserId"]; + tenantId: components["schemas"]["TenantId"]; + organizationId: null | components["schemas"]["OrganizationId"]; + site: components["schemas"]["PublicSite"]; + }; + AdministrationGrantResponse: { /** @enum {string} */ - type: "string"; - minLength: number; - maxLength: number; - } | { + scope: "Tenant"; /** @enum {string} */ - type: "string"; - minLength: number; - maxLength: number; - enum: string[]; + key: "customization.custom_field.admin"; } | { /** @enum {string} */ - type: "integer"; - minimum: number; - maximum: number; + scope: "Tenant"; + /** @enum {string} */ + key: "identity.federation.admin"; } | { /** @enum {string} */ - type: "number"; - minimum: number; - maximum: number; + scope: "Tenant"; + /** @enum {string} */ + key: "identity.membership.admin"; } | { /** @enum {string} */ - type: "boolean"; - }; - CustomFieldValueEnvelope: { - value: components["schemas"]["CustomFieldValueNode0"]; - }; - CustomFieldValueNode0: string | number | boolean | components["schemas"]["CustomFieldValueNode1"][] | { - [key: string]: components["schemas"]["CustomFieldValueNode1"]; - }; - CustomFieldValueNode1: string | number | boolean | components["schemas"]["CustomFieldValueNode2"][] | { - [key: string]: components["schemas"]["CustomFieldValueNode2"]; - }; - CustomFieldValueNode2: string | number | boolean; - DefaultOrganizationInput: { - /** Format: uuid */ - organizationId: string; - }; - /** @enum {string} */ - DirectoryMembershipStatus: "Active" | "Suspended"; - EmptyAdministrationInput: Record<string, never>; - FederationConfigurationInput: { + scope: "Tenant"; /** @enum {string} */ - protocol: "oidc" | "saml"; - displayName: null | string; + key: "identity.membership_profile.write"; + } | { /** @enum {string} */ - source: "metadata_url" | "discovery_url" | "manual"; - documentUrl: null | string; - issuerOrEntityId: null | string; - authorizationEndpoint: null | string; - tokenEndpoint: null | string; - jwksEndpoint: null | string; - userInfoEndpoint: null | string; - singleSignOnEndpoint: null | string; - signingCertificates: string[]; - clientId: null | string; - /** @enum {null|string} */ - clientAuthentication: "client_secret_post" | "client_secret_basic" | null; - /** @description Write-only client secret, at most 1,024 UTF-8 bytes; never the mask literal or a ${ vault reference. Never returned, logged, audited or persisted. */ - clientSecret: null | string; - }; - FederationConnectionBody: { - /** Format: uuid */ - connectionId: string; + scope: "Tenant"; /** @enum {string} */ - protocol: "oidc" | "saml"; - alias: string; - displayName: string; - issuerOrEntityId: string; + key: "identity.role.admin"; + } | { /** @enum {string} */ - status: "draft" | "test_open" | "test_passed" | "active" | "disabled"; + scope: "Tenant"; /** @enum {string} */ - source: "metadata_url" | "discovery_url" | "manual"; - clientId: null | string; - /** @description Canonical decimal connection revision from 0 through 9223372036854775807. Never a JSON number. */ - configurationRevision: string; - configurationDigest: string; - desiredDigest: string; - lastProviderDigest: null | string; - pending: components["schemas"]["FederationPendingResponse"] | null; - /** Format: date-time */ - testExpiresAt: null | string; - /** @description Canonical decimal connection revision from 0 through 9223372036854775807. Never a JSON number. */ - version: string; - }; - FederationConnectionResponse: { - connection: components["schemas"]["FederationConnectionBody"] | null; + key: "tenancy.locale.write"; + } | { /** @enum {string} */ - provider: "not_read" | "matches" | "drift" | "unavailable"; - }; - FederationDisplayNameInput: { - displayName: string; - }; - FederationOperationResponse: { - /** Format: uuid */ - connectionId: string; - /** @description Canonical decimal connection revision from 0 through 9223372036854775807. Never a JSON number. */ - version: string; + scope: "Tenant"; /** @enum {string} */ - outcome: "applied" | "failed" | "uncertain" | "pending" | "drift" | "recorded" | "expired" | "superseded"; - /** @enum {null|string} */ - reason: "provider_refused" | "drift" | "owner_mismatch" | "egress_refused" | "resubmit_required" | "provider_unavailable" | "egress_unavailable" | null; - /** Format: uuid */ - testAttemptId: null | string; - }; - FederationPendingResponse: { + key: "tenancy.organization.admin"; + } | { /** @enum {string} */ - kind: "configure" | "rotate_secret" | "rename" | "test_start" | "disable" | "delete"; - /** Format: date-time */ - startedAt: string; - /** Format: date-time */ - quietUntil: string; + scope: "Tenant"; + /** @enum {string} */ + key: "tenancy.setting.write"; + } | { + /** @enum {string} */ + scope: "Organization"; + /** @enum {string} */ + key: "identity.membership.admin"; + } | { + /** @enum {string} */ + scope: "Organization"; + /** @enum {string} */ + key: "identity.membership_profile.write"; }; - FederationSecretInput: { - /** @description Write-only client secret, at most 1,024 UTF-8 bytes; never the mask literal or a ${ vault reference. Never returned, logged, audited or persisted. */ - clientSecret: string; + AdministrationVersionReceipt: { + /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ + version: string; }; - FederationTestResultInput: { + ConsentDetailsResponse: { /** Format: uuid */ - testAttemptId: string; - passed: boolean; - }; - FieldConsentGrantInput: { + evidenceId: string; + sequence: string; + isGranted: boolean; + /** Format: uuid */ + membershipId: string; /** Format: uuid */ definitionId: string; definitionVersion: number; + purposeKey: string; noticeLocale: string; - expectedNoticeHash: string; - expectedSequence: number; - expectedEvidenceId: string | null; - confirmed: boolean; + noticeHash: string; + noticeText: string; + labels: components["schemas"]["CustomFieldLocalizedText"]; }; - FieldConsentReceiptResponse: { - /** Format: uuid */ - evidenceId: string; - sequence: string; - isGranted: boolean; + ConsentHistoryPageResponse: { + items: components["schemas"]["ConsentDetailsResponse"][]; + pageInfo: components["schemas"]["PageInfo"]; }; - FieldConsentWithdrawalInput: { - /** Format: uuid */ - evidenceId: string; - expectedSequence: number; - /** Format: uuid */ - expectedEvidenceId: string; - confirmed: boolean; + ConsentScopePageResponse: { + items: { + /** Format: uuid */ + membershipId: string; + /** Format: uuid */ + tenantId: string; + organizationId: string | null; + }[]; + pageInfo: components["schemas"]["PageInfo"]; }; - IdentitySelfActive: { + CustomFieldDefinitionInput: { /** @enum {string} */ - state: "active"; - /** Format: uuid */ - authorityId: string; - subjectKey: string; - /** Format: uuid */ - actorId: string; - federationAlias: null | string; - }; - IdentitySelfMissing: { + targetEntity: "Membership"; + key: string; + schemaVersion: number; + schema: components["schemas"]["CustomFieldFiniteSchema"]; + labels: components["schemas"]["CustomFieldLocalizedText"]; /** @enum {string} */ - state: "missing"; - federationAlias: null | string; + piiCategory: "None" | "Identity" | "Behaviour" | "Sensitive"; + isRequired: boolean; + sort: number; + purposeKey: string | null; + notices: components["schemas"]["CustomFieldNoticeText"] | null; + formLabels: components["schemas"]["CustomFieldFormLabel"][] | null; }; - IdentitySelfState: components["schemas"]["IdentitySelfMissing"] | components["schemas"]["IdentitySelfActive"]; - InvitableRoleDirectory: { - items: components["schemas"]["RoleSummaryResponse"][]; + CustomFieldDefinitionPageResponse: { + items: components["schemas"]["CustomFieldDefinitionResponse"][]; + pageInfo: components["schemas"]["PageInfo"]; }; - InvitationAcceptanceResponse: { - /** Format: uuid */ - invitationId: string; - /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ - version: string; - /** Format: uuid */ - membershipId: string; + CustomFieldDefinitionResponse: { /** @enum {string} */ - disposition: "created" | "already_member"; - /** Format: uuid */ - tenantId: string; - /** Format: uuid */ - organizationId: null | string; - }; - InvitationCreateInput: { - email: string; - /** Format: uuid */ - roleId: string; - /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ - roleVersion: string; - }; - InvitationEntryInput: { - /** Format: uuid */ - invitationId: string; - /** @description Sensitive canonical invitation UUIDv7 plus canonical base64url 32-byte verifier; ID must match invitationId. Body only; never route/query/log. */ - code: string; - }; - InvitationInspectionResponse: { + targetEntity: "Membership"; + key: string; + schemaVersion: number; + schema: components["schemas"]["CustomFieldFiniteSchema"]; + labels: components["schemas"]["CustomFieldLocalizedText"]; + /** @enum {string} */ + piiCategory: "None" | "Identity" | "Behaviour" | "Sensitive"; + isRequired: boolean; + sort: number; + purposeKey: string | null; + notices: components["schemas"]["CustomFieldNoticeText"] | null; + formLabels: components["schemas"]["CustomFieldFormLabel"][] | null; /** Format: uuid */ - invitationId: string; - /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ + definitionId: string; + /** @enum {string} */ + status: "Draft" | "Active" | "Deprecated"; version: string; - /** Format: date-time */ - expiresAt: string; - tenantLabel: string; - organizationLabel: null | string; - /** Format: uuid */ - roleId: string; + isDiscarded: boolean; + maximumValueBytes: number; + activeRevision: { + /** Format: uuid */ + id: string; + version: string; + } | null; + }; + CustomFieldFiniteSchema: { /** @enum {string} */ - roleKey: "TenantAdmin" | "OrgAdmin" | "Instructor" | "OrgInstructor" | "Learner" | "Guardian" | "Editor"; + $schema: "https://json-schema.org/draft/2020-12/schema"; /** @enum {string} */ - roleScope: "Tenant" | "Organization"; - verifiedEmail: string; + type: "object"; + properties: { + value: components["schemas"]["CustomFieldSchemaNode0"]; + }; + required: "value"[]; + /** @enum {boolean} */ + additionalProperties: false; }; - InvitationLifetimeInput: { - /** Format: int32 */ - days: number; + CustomFieldFormLabel: { + location: string; + labels: components["schemas"]["CustomFieldLocalizedText"] | null; + choices: components["schemas"]["CustomFieldLocalizedText"][] | null; }; - InvitationPage: { - items: components["schemas"]["InvitationResponse"][]; - pageInfo: components["schemas"]["PageInfo"]; + CustomFieldLocalizedText: { + [key: string]: string; }; - InvitationPolicyResponse: { - /** Format: int32 */ - days: number; - present: boolean; - /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ - version: null | string; - canEdit: boolean; + CustomFieldNoticeHashes: { + [key: string]: string; }; - InvitationResponse: { - /** Format: uuid */ - invitationId: string; - email: string; - /** Format: uuid */ - organizationId: null | string; - /** Format: uuid */ - roleId: string; - /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ - roleVersion: string; - /** @enum {string} */ - status: "Pending" | "Accepted" | "Revoked" | "Expired"; - /** Format: date-time */ - expiresAt: string; - /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ - version: string; - /** @enum {string} */ - deliveryStatus: "Queued" | "SubmissionAccepted" | "Failed" | "Unresolved" | "Unavailable"; - /** @enum {null|string} */ - acceptanceDisposition: "created" | "already_member" | null; + CustomFieldNoticeText: { + [key: string]: string; }; - MembershipCustomFieldPatch: { - set: { - conceptKey: string; - /** Format: uuid */ - definitionId: string; - schemaVersion: number; - envelope: components["schemas"]["CustomFieldValueEnvelope"]; - consentEvidenceId: string | null; - }[]; - remove: { - conceptKey: string; - /** Format: uuid */ - definitionId: string; - schemaVersion: number; - }[]; + CustomFieldPublicationInput: { + expectedIncumbentId: string | null; + expectedIncumbentVersion: string | null; }; - MembershipCustomFieldsResponse: { + CustomFieldReceiptResponse: { /** Format: uuid */ - membershipId: string; + id: string; version: string; - fields: { - conceptKey: string; - /** Format: uuid */ - definitionId: string; - schemaVersion: number; - /** @enum {string} */ - state: "Current" | "Missing" | "Retired" | "Withheld"; - isRequired: boolean; - envelope: components["schemas"]["CustomFieldValueEnvelope"] | null; - definition: { - schema: components["schemas"]["CustomFieldFiniteSchema"]; - labels: components["schemas"]["CustomFieldLocalizedText"]; - /** @enum {string} */ - piiCategory: "None" | "Identity" | "Behaviour" | "Sensitive"; - sort: number; - purposeKey: string | null; - notices: components["schemas"]["CustomFieldNoticeText"] | null; - formLabels: components["schemas"]["CustomFieldFormLabel"][] | null; - noticeHashes: components["schemas"]["CustomFieldNoticeHashes"] | null; - /** @enum {string} */ - status: "Active" | "Deprecated"; - }; - consent: components["schemas"]["FieldConsentReceiptResponse"] | null; - }[]; }; - MembershipDetailResponse: { - /** Format: uuid */ - membershipId: string; - /** Format: uuid */ - userId: string; - /** Format: uuid */ - organizationId: null | string; + CustomFieldSchemaNode0: { /** @enum {string} */ - status: "Active" | "Suspended" | "Revoked"; - displayName: null | string; - preferredLocale: null | string; - roleIds: string[]; - /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ - version: string; - }; - MembershipDirectoryItem: { - /** Format: uuid */ - membershipId: string; - userId: components["schemas"]["UserId"]; - organizationId: null | components["schemas"]["OrganizationId"]; - status: components["schemas"]["DirectoryMembershipStatus"]; - displayName: null | string; - preferredLocale: null | string; - }; - MembershipProfileInput: { - displayName: null | string; - preferredLocale: null | string; + type: "string"; + minLength: number; + maxLength: number; + } | { + /** @enum {string} */ + type: "string"; + minLength: number; + maxLength: number; + enum: string[]; + } | { + /** @enum {string} */ + type: "integer"; + minimum: number; + maximum: number; + } | { + /** @enum {string} */ + type: "number"; + minimum: number; + maximum: number; + } | { + /** @enum {string} */ + type: "boolean"; + } | { + /** @enum {string} */ + type: "object"; + properties: { + [key: string]: components["schemas"]["CustomFieldSchemaNode1"]; + }; + required: string[]; + /** @enum {boolean} */ + additionalProperties: false; + } | { + /** @enum {string} */ + type: "array"; + items: components["schemas"]["CustomFieldSchemaNode1"]; + minItems: number; + maxItems: number; }; - MembershipRolesInput: { - roleIds: string[]; + CustomFieldSchemaNode1: { + /** @enum {string} */ + type: "string"; + minLength: number; + maxLength: number; + } | { + /** @enum {string} */ + type: "string"; + minLength: number; + maxLength: number; + enum: string[]; + } | { + /** @enum {string} */ + type: "integer"; + minimum: number; + maximum: number; + } | { + /** @enum {string} */ + type: "number"; + minimum: number; + maximum: number; + } | { + /** @enum {string} */ + type: "boolean"; + } | { + /** @enum {string} */ + type: "object"; + properties: { + [key: string]: components["schemas"]["CustomFieldSchemaNode2"]; + }; + required: string[]; + /** @enum {boolean} */ + additionalProperties: false; + } | { + /** @enum {string} */ + type: "array"; + items: components["schemas"]["CustomFieldSchemaNode2"]; + minItems: number; + maxItems: number; }; - MembershipStatusInput: { + CustomFieldSchemaNode2: { /** @enum {string} */ - status: "Active" | "Suspended" | "Revoked"; + type: "string"; + minLength: number; + maxLength: number; + } | { + /** @enum {string} */ + type: "string"; + minLength: number; + maxLength: number; + enum: string[]; + } | { + /** @enum {string} */ + type: "integer"; + minimum: number; + maximum: number; + } | { + /** @enum {string} */ + type: "number"; + minimum: number; + maximum: number; + } | { + /** @enum {string} */ + type: "boolean"; }; - NativeSessionScopeAdmission: { - /** Format: uuid */ - actorId: string; - /** Format: uuid */ - tenantId: string; - /** Format: uuid */ - organizationId: null | string; - /** Format: uuid */ - authorityId: string; - subjectKey: string; + CustomFieldValueEnvelope: { + value: components["schemas"]["CustomFieldValueNode0"]; }; - OrganizationCreateInput: { - slug: string; - displayName: string; + CustomFieldValueNode0: string | number | boolean | components["schemas"]["CustomFieldValueNode1"][] | { + [key: string]: components["schemas"]["CustomFieldValueNode1"]; }; - OrganizationDirectoryResponse: { - items: components["schemas"]["OrganizationResponse"][]; + CustomFieldValueNode1: string | number | boolean | components["schemas"]["CustomFieldValueNode2"][] | { + [key: string]: components["schemas"]["CustomFieldValueNode2"]; + }; + CustomFieldValueNode2: string | number | boolean; + DataErasureAcceptedResponse: { /** Format: uuid */ - defaultOrganizationId: null | string; + id: string; + /** @enum {string} */ + kind: "erasure"; + /** @enum {string} */ + status: "scheduled"; /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ - tenantVersion: string; - pageInfo: components["schemas"]["PageInfo"]; - }; - /** Format: uuid */ - OrganizationId: string; - OrganizationRenameInput: { - displayName: string; + version: string; }; - OrganizationResponse: { + DataExportArtifactResponse: { /** Format: uuid */ - organizationId: string; - slug: string; - displayName: string; + id: string; /** @enum {string} */ - status: "Active" | "Suspended" | "Archived"; - isDefault: boolean; + 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; }; - OwnCapabilitiesDto: { - canReadTenantMembers: boolean; - canReadOrganizationMembers: boolean; - canWriteMemberProfiles: boolean; - canManageMemberships: boolean; - canReadRoles: boolean; - canChangeRoleGrants: boolean; - canAdoptRoleRelease: boolean; - canWriteOwnProfile: boolean; - canManageOrganizations: boolean; - canManageCustomFields: boolean; - canManageFederation: boolean; - }; - OwnFieldConsentCurrentResponse: { - consent: components["schemas"]["ConsentDetailsResponse"] | null; + 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; }; - OwnMembershipContextPage: { - items: components["schemas"]["OwnMembershipContextResponse"][]; - pageInfo: components["schemas"]["PageInfo"]; + 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'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. */ + bytes: string; }; - OwnMembershipContextResponse: { - /** Format: uuid */ - tenantId: string; + DataExportForSubjectInput: { /** Format: uuid */ - organizationId: null | string; - tenantName: string; - organizationName: null | string; - /** Format: uri */ - entryOrigin: string; - canUseCurrentHost: boolean; + membershipId: string; }; - OwnMembershipProfileResponse: { - displayName: null | string; - preferredLocale: null | 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; }; - PageInfo: { - nextCursor: null | string; - previousCursor: null | string; - hasNext: boolean; - hasPrevious: boolean; - }; - PageOfMembershipDirectoryItem: { - items: components["schemas"]["MembershipDirectoryItem"][]; + DataRequestPage: { + items: components["schemas"]["DataRequestResponse"][]; pageInfo: components["schemas"]["PageInfo"]; }; - PermissionRegistryItemResponse: { + DataRequestResponse: { + /** Format: uuid */ + id: string; /** @enum {string} */ - scope: "Tenant" | "Organization"; - key: string; - labelKey: string; - canGrant: boolean; + kind: "export" | "erasure" | "closure"; + /** @enum {string} */ + origin: "self" | "administrator" | "closure_fanout"; + /** + * @description An erasure is scheduled until its window ends, then fulfilling and awaiting_privileged_step together (the job commits both at once, so fulfilling is not observed for an ordinary erasure), and completed once an operator finishes the audit redaction. After executeAt and before the job has run a request still reads scheduled: a client derives a 'due, running shortly' state from status and executeAt. + * @enum {string} + */ + status: "requested" | "scheduled" | "fulfilling" | "awaiting_privileged_step" | "completed" | "blocked" | "failed" | "cancelled"; + /** Format: date-time */ + createdAt: string; + /** + * Format: date-time + * @description When the request last changed; for a cancelled, blocked or failed request this is when it ended. + */ + updatedAt: null | string; + /** + * Format: date-time + * @description Set only for a completed request; a cancelled, blocked or failed request has none (read updatedAt). + */ + completedAt: null | string; + /** + * @description The closed refusal code of the last refused attempt, without the lockey_ prefix of the 409 keys. + * @enum {null|string} + */ + lastRefusal: "blocked_window" | "blocked_hold" | "blocked_last_administrator" | null; + /** @enum {null|string} */ + failureReason: "export_too_large" | "execution_failed" | null; + /** @description What the request retains, a partial list: a kind not listed is retained and not counted, never zero. The audit log's kinds appear only once the request is completed. invitation_record counts the offers the person issued or accepted; a pending offer addressed to their e-mail address is retained and not counted, because it is not locatable by person. */ + retained: components["schemas"]["DataRequestRetainedResponse"][]; + artifact: components["schemas"]["DataExportArtifactResponse"] | null; + /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ + version: string; + /** + * Format: date-time + * @description An erasure's cancellable window ends here and its job may run from here: the deadline for a cancellation, to be read from the receipt and never computed as createdAt plus a constant. Null for an export. + */ + executeAt: null | 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; }; - PermissionRegistryResponse: { - items: components["schemas"]["PermissionRegistryItemResponse"][]; - release: components["schemas"]["RoleReleaseResponse"]; - }; - ProblemDetails: { - /** Format: uri */ - type: string; - title: string; - status: number; - instance: string; - code: string; - messageKey: string; - correlationId: string; - errors?: { - [key: string]: { - key: string; - params?: { - [key: string]: string; - }; - }[]; - }; - }; - /** @enum {string} */ - PublicCourseAccess: "public" | "enrollment_required"; - PublicCourseAlternate: { - locale: string; - slug: string; - }; - PublicCourseCatalog: { - locale: string; - items: components["schemas"]["PublicCourseSummary"][]; - pageInfo: components["schemas"]["PageInfo"]; - }; - PublicCourseDetail: { - locale: string; - course: components["schemas"]["PublicCourseSummary"]; - alternates: components["schemas"]["PublicCourseAlternate"][]; - lessons: null | components["schemas"]["PublicCourseOutline"]; - }; - PublicCourseOutline: { - items: components["schemas"]["PublicOutlineItem"][]; - pageInfo: components["schemas"]["PageInfo"]; - }; - PublicCourseSummary: { - slug: string; - title: string; - summary: null | string; - contentAccess: components["schemas"]["PublicCourseAccess"]; - level: null | components["schemas"]["PublicLevel"]; + DefaultOrganizationInput: { + /** Format: uuid */ + organizationId: string; }; /** @enum {string} */ - PublicDisplayState: "ready" | "unavailable"; - PublicLabel: { - value: string; - locale: string; - }; - PublicLessonAlternate: { - locale: string; - courseSlug: string; - lessonSlug: string; - }; - PublicLessonContent: components["schemas"]["PublicLessonContentPublicReadyContent"] | components["schemas"]["PublicLessonContentPublicUnavailableContent"]; - PublicLessonContentPublicReadyContent: { + DirectoryMembershipStatus: "Active" | "Suspended"; + EmptyAdministrationInput: Record<string, never>; + FederationConfigurationInput: { /** @enum {string} */ - state: "ready"; - rendererKey: string; - label: components["schemas"]["PublicLabel"]; - fields: components["schemas"]["PublicTextField"][]; - }; - PublicLessonContentPublicUnavailableContent: { + protocol: "oidc" | "saml"; + displayName: null | string; /** @enum {string} */ - state: "unavailable"; - }; - PublicLessonDetail: { - locale: string; - course: components["schemas"]["PublicNamedResource"]; - lesson: components["schemas"]["PublicNamedResource"]; - alternates: components["schemas"]["PublicLessonAlternate"][]; - content: components["schemas"]["PublicLessonContent"]; - }; - PublicLevel: { - state: components["schemas"]["PublicDisplayState"]; - label: null | components["schemas"]["PublicLabel"]; - }; - PublicNamedResource: { - slug: string; - title: string; - }; - PublicOutlineItem: { - slug: string; - title: string; - /** Format: int32 */ - sort: number; - }; - PublicSignIn: { - federation: components["schemas"]["PublicSignInFederation"] | null; + source: "metadata_url" | "discovery_url" | "manual"; + documentUrl: null | string; + issuerOrEntityId: null | string; + authorizationEndpoint: null | string; + tokenEndpoint: null | string; + jwksEndpoint: null | string; + userInfoEndpoint: null | string; + singleSignOnEndpoint: null | string; + signingCertificates: string[]; + clientId: null | string; + /** @enum {null|string} */ + clientAuthentication: "client_secret_post" | "client_secret_basic" | null; + /** @description Write-only client secret, at most 1,024 UTF-8 bytes; never the mask literal or a ${ vault reference. Never returned, logged, audited or persisted. */ + clientSecret: null | string; }; - PublicSignInFederation: { + FederationConnectionBody: { + /** Format: uuid */ + connectionId: string; + /** @enum {string} */ + protocol: "oidc" | "saml"; alias: string; displayName: string; + issuerOrEntityId: string; + /** @enum {string} */ + status: "draft" | "test_open" | "test_passed" | "active" | "disabled"; + /** @enum {string} */ + source: "metadata_url" | "discovery_url" | "manual"; + clientId: null | string; + /** @description Canonical decimal connection revision from 0 through 9223372036854775807. Never a JSON number. */ + configurationRevision: string; + configurationDigest: string; + desiredDigest: string; + lastProviderDigest: null | string; + pending: components["schemas"]["FederationPendingResponse"] | null; + /** Format: date-time */ + testExpiresAt: null | string; + /** @description Canonical decimal connection revision from 0 through 9223372036854775807. Never a JSON number. */ + version: string; }; - PublicSite: { - displayName: string; - enabledLocales: string[]; - defaultLocale: string; - theme: null | components["schemas"]["PublicTheme"]; - showPlatformAttribution: boolean; - }; - PublicTextField: { - name: string; - label: components["schemas"]["PublicLabel"]; - value: string; + FederationConnectionResponse: { + connection: components["schemas"]["FederationConnectionBody"] | null; + /** @enum {string} */ + provider: "not_read" | "matches" | "drift" | "unavailable"; }; - PublicTheme: { - primary: string; - background: string; - foreground: string; - muted: string; + FederationDisplayNameInput: { + displayName: string; }; - RoleDetailResponse: { + FederationOperationResponse: { /** Format: uuid */ - roleId: string; + connectionId: string; + /** @description Canonical decimal connection revision from 0 through 9223372036854775807. Never a JSON number. */ + version: string; /** @enum {string} */ - builtInKey: "TenantAdmin" | "OrgAdmin" | "Instructor" | "OrgInstructor" | "Learner" | "Guardian" | "Editor"; + outcome: "applied" | "failed" | "uncertain" | "pending" | "drift" | "recorded" | "expired" | "superseded"; + /** @enum {null|string} */ + reason: "provider_refused" | "drift" | "owner_mismatch" | "egress_refused" | "resubmit_required" | "provider_unavailable" | "egress_unavailable" | null; + /** Format: uuid */ + testAttemptId: null | string; + }; + FederationPendingResponse: { /** @enum {string} */ - capabilityScope: "Tenant" | "Organization"; - /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ - version: string; - grants: components["schemas"]["AdministrationGrantResponse"][]; - /** Format: int32 */ - adoptedReleaseVersion: number; - adoptedReleaseFingerprint: string; + kind: "configure" | "rotate_secret" | "rename" | "test_start" | "disable" | "delete"; + /** Format: date-time */ + startedAt: string; + /** Format: date-time */ + quietUntil: string; }; - RoleDirectoryResponse: { - items: components["schemas"]["RoleSummaryResponse"][]; + FederationSecretInput: { + /** @description Write-only client secret, at most 1,024 UTF-8 bytes; never the mask literal or a ${ vault reference. Never returned, logged, audited or persisted. */ + clientSecret: string; }; - RoleGrantsInput: { - grants: components["schemas"]["AdministrationGrantResponse"][]; + FederationTestResultInput: { + /** Format: uuid */ + testAttemptId: string; + passed: boolean; }; - RoleManifestInput: { - /** Format: int32 */ - manifestVersion: number; - manifestFingerprint: string; + FieldConsentGrantInput: { + /** Format: uuid */ + definitionId: string; + definitionVersion: number; + noticeLocale: string; + expectedNoticeHash: string; + expectedSequence: number; + expectedEvidenceId: string | null; + confirmed: boolean; }; - RoleReleaseResponse: { - /** Format: int32 */ - version: number; - fingerprint: string; - tenantAdminDelta: components["schemas"]["AdministrationGrantResponse"][]; + FieldConsentReceiptResponse: { + /** Format: uuid */ + evidenceId: string; + sequence: string; + isGranted: boolean; }; - RoleSummaryResponse: { + FieldConsentWithdrawalInput: { /** Format: uuid */ - roleId: string; + evidenceId: string; + expectedSequence: number; + /** Format: uuid */ + expectedEvidenceId: string; + confirmed: boolean; + }; + IdentitySelfActive: { /** @enum {string} */ - builtInKey: "TenantAdmin" | "OrgAdmin" | "Instructor" | "OrgInstructor" | "Learner" | "Guardian" | "Editor"; + state: "active"; + /** Format: uuid */ + authorityId: string; + subjectKey: string; + /** Format: uuid */ + actorId: string; + federationAlias: null | string; + }; + IdentitySelfMissing: { /** @enum {string} */ - capabilityScope: "Tenant" | "Organization"; + state: "missing"; + federationAlias: null | string; + }; + IdentitySelfState: components["schemas"]["IdentitySelfMissing"] | components["schemas"]["IdentitySelfActive"]; + InvitableRoleDirectory: { + items: components["schemas"]["RoleSummaryResponse"][]; + }; + InvitationAcceptanceResponse: { + /** Format: uuid */ + invitationId: string; /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ version: string; - }; - SelfContextItem: { + /** Format: uuid */ + membershipId: string; + /** @enum {string} */ + disposition: "created" | "already_member"; /** Format: uuid */ tenantId: string; /** Format: uuid */ organizationId: null | string; - tenantName: string; - organizationName: null | string; - /** Format: uri */ - entryOrigin: string; - canUseCurrentHost: boolean; }; - SelfContextPage: { - items: components["schemas"]["SelfContextItem"][]; - pageInfo: components["schemas"]["PageInfo"]; + InvitationCreateInput: { + email: string; + /** Format: uuid */ + roleId: string; + /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ + roleVersion: string; + }; + InvitationEntryInput: { + /** Format: uuid */ + invitationId: string; + /** @description Sensitive canonical invitation UUIDv7 plus canonical base64url 32-byte verifier; ID must match invitationId. Body only; never route/query/log. */ + code: string; + }; + InvitationInspectionResponse: { + /** Format: uuid */ + invitationId: string; + /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ + version: string; + /** Format: date-time */ + expiresAt: string; + tenantLabel: string; + organizationLabel: null | string; + /** Format: uuid */ + roleId: string; + /** @enum {string} */ + roleKey: "TenantAdmin" | "OrgAdmin" | "Instructor" | "OrgInstructor" | "Learner" | "Guardian" | "Editor"; + /** @enum {string} */ + roleScope: "Tenant" | "Organization"; + verifiedEmail: string; + }; + InvitationLifetimeInput: { + /** Format: int32 */ + days: number; + }; + InvitationPage: { + items: components["schemas"]["InvitationResponse"][]; + pageInfo: components["schemas"]["PageInfo"]; + }; + InvitationPolicyResponse: { + /** Format: int32 */ + days: number; + present: boolean; + /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ + version: null | string; + canEdit: boolean; + }; + InvitationResponse: { + /** Format: uuid */ + invitationId: string; + email: string; + /** Format: uuid */ + organizationId: null | string; + /** Format: uuid */ + roleId: string; + /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ + roleVersion: string; + /** @enum {string} */ + status: "Pending" | "Accepted" | "Revoked" | "Expired"; + /** Format: date-time */ + expiresAt: string; + /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ + version: string; + /** @enum {string} */ + deliveryStatus: "Queued" | "SubmissionAccepted" | "Failed" | "Unresolved" | "Unavailable"; + /** @enum {null|string} */ + acceptanceDisposition: "created" | "already_member" | null; + }; + MembershipCustomFieldPatch: { + set: { + conceptKey: string; + /** Format: uuid */ + definitionId: string; + schemaVersion: number; + envelope: components["schemas"]["CustomFieldValueEnvelope"]; + consentEvidenceId: string | null; + }[]; + remove: { + conceptKey: string; + /** Format: uuid */ + definitionId: string; + schemaVersion: number; + }[]; + }; + MembershipCustomFieldsResponse: { + /** Format: uuid */ + membershipId: string; + version: string; + fields: { + conceptKey: string; + /** Format: uuid */ + definitionId: string; + schemaVersion: number; + /** @enum {string} */ + state: "Current" | "Missing" | "Retired" | "Withheld"; + isRequired: boolean; + envelope: components["schemas"]["CustomFieldValueEnvelope"] | null; + definition: { + schema: components["schemas"]["CustomFieldFiniteSchema"]; + labels: components["schemas"]["CustomFieldLocalizedText"]; + /** @enum {string} */ + piiCategory: "None" | "Identity" | "Behaviour" | "Sensitive"; + sort: number; + purposeKey: string | null; + notices: components["schemas"]["CustomFieldNoticeText"] | null; + formLabels: components["schemas"]["CustomFieldFormLabel"][] | null; + noticeHashes: components["schemas"]["CustomFieldNoticeHashes"] | null; + /** @enum {string} */ + status: "Active" | "Deprecated"; + }; + consent: components["schemas"]["FieldConsentReceiptResponse"] | null; + }[]; + }; + MembershipDetailResponse: { + /** Format: uuid */ + membershipId: string; + /** Format: uuid */ + userId: string; + /** Format: uuid */ + organizationId: null | string; + /** @enum {string} */ + status: "Active" | "Suspended" | "Revoked"; + displayName: null | string; + preferredLocale: null | string; + roleIds: string[]; + /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ + version: string; + }; + MembershipDirectoryItem: { + /** Format: uuid */ + membershipId: string; + userId: components["schemas"]["UserId"]; + organizationId: null | components["schemas"]["OrganizationId"]; + status: components["schemas"]["DirectoryMembershipStatus"]; + displayName: null | string; + preferredLocale: null | string; + }; + MembershipProfileInput: { + displayName: null | string; + preferredLocale: null | string; + }; + MembershipRolesInput: { + roleIds: string[]; + }; + MembershipStatusInput: { + /** @enum {string} */ + status: "Active" | "Suspended" | "Revoked"; + }; + NativeSessionScopeAdmission: { + /** Format: uuid */ + actorId: string; + /** Format: uuid */ + tenantId: string; + /** Format: uuid */ + organizationId: null | string; + /** Format: uuid */ + authorityId: string; + subjectKey: string; + }; + OrganizationCreateInput: { + slug: string; + displayName: string; + }; + OrganizationDirectoryResponse: { + items: components["schemas"]["OrganizationResponse"][]; + /** Format: uuid */ + defaultOrganizationId: null | string; + /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ + tenantVersion: string; + pageInfo: components["schemas"]["PageInfo"]; + }; + /** Format: uuid */ + OrganizationId: string; + OrganizationRenameInput: { + displayName: string; + }; + OrganizationResponse: { + /** Format: uuid */ + organizationId: string; + slug: string; + displayName: string; + /** @enum {string} */ + status: "Active" | "Suspended" | "Archived"; + isDefault: boolean; + /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ + version: string; + }; + OwnCapabilitiesDto: { + canReadTenantMembers: boolean; + canReadOrganizationMembers: boolean; + canWriteMemberProfiles: boolean; + canManageMemberships: boolean; + canReadRoles: boolean; + canChangeRoleGrants: boolean; + canAdoptRoleRelease: boolean; + canWriteOwnProfile: boolean; + canManageOrganizations: boolean; + 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"; + /** + * @description An erasure is scheduled until its window ends, then fulfilling and awaiting_privileged_step together (the job commits both at once, so fulfilling is not observed for an ordinary erasure), and completed once an operator finishes the audit redaction. After executeAt and before the job has run a request still reads scheduled: a client derives a 'due, running shortly' state from status and executeAt. A closure has no job: it reads scheduled until an operator Begins it, at or after its executeAt, then fulfilling (the account no longer works, so its owner rarely reads it), and completed once an operator finalizes it; it is never blocked or failed. + * @enum {string} + */ + status: "requested" | "scheduled" | "fulfilling" | "awaiting_privileged_step" | "completed" | "blocked" | "failed" | "cancelled"; + /** Format: date-time */ + createdAt: string; + /** + * Format: date-time + * @description When the request last changed; for a cancelled, blocked or failed request this is when it ended. + */ + updatedAt: null | string; + /** + * Format: date-time + * @description Set only for a completed request; a cancelled, blocked or failed request has none (read updatedAt). + */ + completedAt: null | string; + /** + * @description The closed refusal code of the last refused attempt, without the lockey_ prefix of the 409 keys. For a scheduled closure it is the reason an operator's Begin was refused (blocked_window, blocked_hold or blocked_last_administrator: another eligible tenant-wide administrator must be appointed first); the closure stays scheduled and cancellable. + * @enum {null|string} + */ + lastRefusal: "blocked_window" | "blocked_hold" | "blocked_last_administrator" | null; + /** @enum {null|string} */ + failureReason: "export_too_large" | "execution_failed" | null; + /** @description What the request retains, a partial list: a kind not listed is retained and not counted, never zero. The audit log's kinds appear only once the request is completed. invitation_record counts the offers the person issued or accepted; a pending offer addressed to their e-mail address is retained and not counted, because it is not locatable by person. */ + retained: components["schemas"]["DataRequestRetainedResponse"][]; + artifact: components["schemas"]["DataExportArtifactResponse"] | null; + /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ + version: string; + /** + * Format: date-time + * @description An erasure's cancellable window ends here and its job may run from here: the deadline for a cancellation, to be read from the receipt and never computed as createdAt plus a constant. Null for an export. For a closure it is the earliest time an operator may Begin it, not a cancellation deadline: a scheduled closure can be cancelled until that Begin commits. + */ + executeAt: null | string; + }; + OwnFieldConsentCurrentResponse: { + consent: components["schemas"]["ConsentDetailsResponse"] | null; + }; + OwnMembershipContextPage: { + items: components["schemas"]["OwnMembershipContextResponse"][]; + pageInfo: components["schemas"]["PageInfo"]; + }; + OwnMembershipContextResponse: { + /** Format: uuid */ + tenantId: string; + /** Format: uuid */ + organizationId: null | string; + tenantName: string; + organizationName: null | string; + /** Format: uri */ + entryOrigin: string; + canUseCurrentHost: boolean; + }; + OwnMembershipProfileResponse: { + displayName: null | string; + preferredLocale: null | string; + /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ + version: string; + }; + PageInfo: { + nextCursor: null | string; + previousCursor: null | string; + hasNext: boolean; + hasPrevious: boolean; + }; + PageOfMembershipDirectoryItem: { + items: components["schemas"]["MembershipDirectoryItem"][]; + pageInfo: components["schemas"]["PageInfo"]; + }; + PermissionRegistryItemResponse: { + /** @enum {string} */ + scope: "Tenant" | "Organization"; + key: string; + labelKey: string; + canGrant: boolean; + }; + PermissionRegistryResponse: { + items: components["schemas"]["PermissionRegistryItemResponse"][]; + release: components["schemas"]["RoleReleaseResponse"]; + }; + ProblemDetails: { + /** Format: uri */ + type: string; + title: string; + status: number; + instance: string; + code: string; + messageKey: string; + correlationId: string; + errors?: { + [key: string]: { + key: string; + params?: { + [key: string]: string; + }; + }[]; + }; + }; + /** @enum {string} */ + PublicCourseAccess: "public" | "enrollment_required"; + PublicCourseAlternate: { + locale: string; + slug: string; + }; + PublicCourseCatalog: { + locale: string; + items: components["schemas"]["PublicCourseSummary"][]; + pageInfo: components["schemas"]["PageInfo"]; + }; + PublicCourseDetail: { + locale: string; + course: components["schemas"]["PublicCourseSummary"]; + alternates: components["schemas"]["PublicCourseAlternate"][]; + lessons: null | components["schemas"]["PublicCourseOutline"]; + }; + PublicCourseOutline: { + items: components["schemas"]["PublicOutlineItem"][]; + pageInfo: components["schemas"]["PageInfo"]; + }; + PublicCourseSummary: { + slug: string; + title: string; + summary: null | string; + contentAccess: components["schemas"]["PublicCourseAccess"]; + level: null | components["schemas"]["PublicLevel"]; + }; + /** @enum {string} */ + PublicDisplayState: "ready" | "unavailable"; + PublicLabel: { + value: string; + locale: string; + }; + PublicLessonAlternate: { + locale: string; + courseSlug: string; + lessonSlug: string; + }; + PublicLessonContent: components["schemas"]["PublicLessonContentPublicReadyContent"] | components["schemas"]["PublicLessonContentPublicUnavailableContent"]; + PublicLessonContentPublicReadyContent: { + /** @enum {string} */ + state: "ready"; + rendererKey: string; + label: components["schemas"]["PublicLabel"]; + fields: components["schemas"]["PublicTextField"][]; + }; + PublicLessonContentPublicUnavailableContent: { + /** @enum {string} */ + state: "unavailable"; + }; + PublicLessonDetail: { + locale: string; + course: components["schemas"]["PublicNamedResource"]; + lesson: components["schemas"]["PublicNamedResource"]; + alternates: components["schemas"]["PublicLessonAlternate"][]; + content: components["schemas"]["PublicLessonContent"]; + }; + PublicLevel: { + state: components["schemas"]["PublicDisplayState"]; + label: null | components["schemas"]["PublicLabel"]; + }; + PublicNamedResource: { + slug: string; + title: string; + }; + PublicOutlineItem: { + slug: string; + title: string; + /** Format: int32 */ + sort: number; + }; + PublicSignIn: { + federation: components["schemas"]["PublicSignInFederation"] | null; + }; + PublicSignInFederation: { + alias: string; + displayName: string; + }; + PublicSite: { + displayName: string; + enabledLocales: string[]; + defaultLocale: string; + theme: null | components["schemas"]["PublicTheme"]; + showPlatformAttribution: boolean; + }; + PublicTextField: { + name: string; + label: components["schemas"]["PublicLabel"]; + value: string; + }; + PublicTheme: { + primary: string; + background: string; + 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; + /** @enum {string} */ + builtInKey: "TenantAdmin" | "OrgAdmin" | "Instructor" | "OrgInstructor" | "Learner" | "Guardian" | "Editor"; + /** @enum {string} */ + capabilityScope: "Tenant" | "Organization"; + /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ + version: string; + grants: components["schemas"]["AdministrationGrantResponse"][]; + /** Format: int32 */ + adoptedReleaseVersion: number; + adoptedReleaseFingerprint: string; + }; + RoleDirectoryResponse: { + items: components["schemas"]["RoleSummaryResponse"][]; + }; + RoleGrantsInput: { + grants: components["schemas"]["AdministrationGrantResponse"][]; + }; + RoleManifestInput: { + /** Format: int32 */ + manifestVersion: number; + manifestFingerprint: string; + }; + RoleReleaseResponse: { + /** Format: int32 */ + version: number; + fingerprint: string; + tenantAdminDelta: components["schemas"]["AdministrationGrantResponse"][]; + }; + RoleSummaryResponse: { + /** Format: uuid */ + roleId: string; + /** @enum {string} */ + builtInKey: "TenantAdmin" | "OrgAdmin" | "Instructor" | "OrgInstructor" | "Learner" | "Guardian" | "Editor"; + /** @enum {string} */ + capabilityScope: "Tenant" | "Organization"; + /** @description Canonical decimal aggregate version from 0 through 9223372036854775807. Never a JSON number. */ + version: string; + }; + SelfContextItem: { + /** Format: uuid */ + tenantId: string; + /** Format: uuid */ + organizationId: null | string; + tenantName: string; + organizationName: null | string; + /** Format: uri */ + entryOrigin: string; + canUseCurrentHost: boolean; + }; + SelfContextPage: { + items: components["schemas"]["SelfContextItem"][]; + pageInfo: components["schemas"]["PageInfo"]; + }; + /** Format: uuid */ + TenantId: string; + /** Format: uuid */ + UserId: string; + }; + responses: never; + parameters: never; + requestBodies: never; + headers: never; + pathItems: never; +} +export type $defs = Record<string, never>; +export interface operations { + ListOwnFieldConsentScopes: { + parameters: { + query?: { + cursor?: string; + limit?: number; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Authorized current projection or minimal committed receipt. */ + 200: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ConsentScopePageResponse"]; + }; + }; + /** @description validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized: invalid credentials. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden: no current operation authority. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found: foreign, missing or noncovered exact scope/target. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier admission gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "GET"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large: input over the outer byte bound. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by existing 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 with payload-free diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; no unconfirmed success. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + ListOwnMembershipFieldConsents: { + parameters: { + query: { + cursor?: string; + limit?: number; + membershipId: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Authorized current projection or minimal committed receipt. */ + 200: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["ConsentHistoryPageResponse"]; + }; + }; + /** @description validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized: invalid credentials. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden: no current operation authority. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found: foreign, missing or noncovered exact scope/target. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier admission gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "GET"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large: input over the outer byte bound. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by existing 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 with payload-free diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; no unconfirmed success. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + WithdrawOwnMembershipFieldConsent: { + parameters: { + query: { + membershipId: string; + }; + header: { + "Idempotency-Key": string; + }; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["FieldConsentWithdrawalInput"]; + }; + }; + responses: { + /** @description Authorized current projection or minimal committed receipt. */ + 200: { + headers: { + "Idempotency-Replayed"?: "true"; + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["FieldConsentReceiptResponse"]; + }; + }; + /** @description validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized: invalid credentials. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden: no current operation authority. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found: foreign, missing or noncovered exact scope/target. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier admission gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "POST"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description concurrency_conflict, business_rule_violation, limit_exceeded, request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable; no automatic retry. */ + 409: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large: input over the outer byte bound. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by existing 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 with payload-free diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; no unconfirmed success. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + SelectDefaultOrganization: { + 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 aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version. */ + "If-Match": string; + }; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["DefaultOrganizationInput"]; + }; + }; + responses: { + /** @description Successful current projection or retained committed receipt. */ + 200: { + headers: { + "Cache-Control": "no-store"; + ETag: string; + /** @description Present only after fresh original-target disclosure audit on a replay. */ + "Idempotency-Replayed"?: "true"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AdministrationVersionReceipt"]; + }; + }; + /** @description validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition. */ + 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 for live coverage without current operation or target disclosure capability. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement. */ + 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: "PUT"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description concurrency_conflict for a valid stale version; business_rule_violation for refused lifecycle/last-admin/last-organization rules; 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; administration bodies are at most 16 KiB, including undeclared/chunked bodies. */ + 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 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; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + GetTenantInvitationPolicy: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful current projection or retained committed receipt. */ + 200: { + headers: { + "Cache-Control": "no-store"; + /** @description Present exactly when the fixed policy setting exists; never emitted for the absent/default policy. */ + ETag?: string; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["InvitationPolicyResponse"]; + }; + }; + /** @description validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition. */ + 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 for live coverage without current operation or target disclosure capability. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement. */ + 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, PUT"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies. */ + 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 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; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + SetTenantInvitationLifetime: { + 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 aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version. */ + "If-Match"?: string; + /** @description Exactly one literal wildcard for conditional creation of the absent fixed policy. Mutually exclusive with If-Match; an existing version-zero setting is not absent. */ + "If-None-Match"?: "*"; + }; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["InvitationLifetimeInput"]; + }; + }; + responses: { + /** @description Successful current projection or retained committed receipt. */ + 200: { + headers: { + "Cache-Control": "no-store"; + ETag: string; + /** @description Present only after fresh original-target disclosure audit on a replay. */ + "Idempotency-Replayed"?: "true"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AdministrationVersionReceipt"]; + }; + }; + /** @description validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition. */ + 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 for live coverage without current operation or target disclosure capability. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement. */ + 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, PUT"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description concurrency_conflict for a valid stale version; business_rule_violation for refused lifecycle/last-admin/last-organization rules; 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; administration bodies are at most 16 KiB, including undeclared/chunked bodies. */ + 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 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; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + ListOrganizations: { + parameters: { + query?: { + /** @description Opaque canonical current-actor/scope/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 Successful current projection or retained committed receipt. */ + 200: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["OrganizationDirectoryResponse"]; + }; + }; + /** @description validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition. */ + 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 for live coverage without current operation or target disclosure capability. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement. */ + 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, POST"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies. */ + 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 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; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + CreateManagedOrganization: { + 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"]["OrganizationCreateInput"]; + }; + }; + responses: { + /** @description Committed creation receipt. */ + 201: { + headers: { + "Cache-Control": "no-store"; + ETag: string; + /** @description Present only after fresh original-target disclosure audit on a replay. */ + "Idempotency-Replayed"?: "true"; + /** @description Exact same-API relative location of the newly created original resource. */ + Location: string; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AdministrationVersionReceipt"]; + }; + }; + /** @description validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition. */ + 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 for live coverage without current operation or target disclosure capability. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement. */ + 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, POST"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description concurrency_conflict for a valid stale version; business_rule_violation for refused lifecycle/last-admin/last-organization rules; 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; administration bodies are at most 16 KiB, including undeclared/chunked bodies. */ + 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 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; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + GetOrganizationDetail: { + parameters: { + query?: never; + header?: never; + path: { + /** @description Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority. */ + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful current projection or retained committed receipt. */ + 200: { + headers: { + "Cache-Control": "no-store"; + ETag: string; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["OrganizationResponse"]; + }; + }; + /** @description validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition. */ + 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 for live coverage without current operation or target disclosure capability. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement. */ + 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, PUT"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies. */ + 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 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; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + RenameOrganization: { + 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 aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version. */ + "If-Match": string; + }; + path: { + /** @description Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority. */ + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["OrganizationRenameInput"]; + }; + }; + responses: { + /** @description Successful current projection or retained committed receipt. */ + 200: { + headers: { + "Cache-Control": "no-store"; + ETag: string; + /** @description Present only after fresh original-target disclosure audit on a replay. */ + "Idempotency-Replayed"?: "true"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AdministrationVersionReceipt"]; + }; + }; + /** @description validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition. */ + 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 for live coverage without current operation or target disclosure capability. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement. */ + 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, PUT"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description concurrency_conflict for a valid stale version; business_rule_violation for refused lifecycle/last-admin/last-organization rules; 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; administration bodies are at most 16 KiB, including undeclared/chunked bodies. */ + 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 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; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + ArchiveOrganization: { + 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 aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version. */ + "If-Match": string; + }; + path: { + /** @description Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority. */ + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["EmptyAdministrationInput"]; + }; + }; + responses: { + /** @description Successful current projection or retained committed receipt. */ + 200: { + headers: { + "Cache-Control": "no-store"; + ETag: string; + /** @description Present only after fresh original-target disclosure audit on a replay. */ + "Idempotency-Replayed"?: "true"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AdministrationVersionReceipt"]; + }; + }; + /** @description validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition. */ + 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 for live coverage without current operation or target disclosure capability. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement. */ + 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 refused lifecycle/last-admin/last-organization rules; 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; administration bodies are at most 16 KiB, including undeclared/chunked bodies. */ + 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 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; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + GetOwnMembershipFieldConsent: { + parameters: { + query: { + membershipId: string; + definitionId: string; + definitionVersion: number; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Authorized current projection or minimal committed receipt. */ + 200: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["OwnFieldConsentCurrentResponse"]; + }; + }; + /** @description validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized: invalid credentials. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden: no current operation authority. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found: foreign, missing or noncovered exact scope/target. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier admission gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "GET"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large: input over the outer byte bound. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by existing 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 with payload-free diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; no unconfirmed success. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + GrantOwnMembershipFieldConsent: { + parameters: { + query?: never; + header: { + "Idempotency-Key": string; + }; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["FieldConsentGrantInput"]; + }; + }; + responses: { + /** @description Authorized current projection or minimal committed receipt. */ + 200: { + headers: { + "Idempotency-Replayed"?: "true"; + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["FieldConsentReceiptResponse"]; + }; + }; + /** @description validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized: invalid credentials. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description forbidden: no current operation authority. */ + 403: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found: foreign, missing or noncovered exact scope/target. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed after earlier admission gates. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "POST"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description concurrency_conflict, business_rule_violation, limit_exceeded, request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable; no automatic retry. */ + 409: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large: input over the outer byte bound. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited by existing 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 with payload-free diagnostics. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable or audit_unavailable; no unconfirmed success. */ + 503: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + GetPublicCourses: { + parameters: { + query: { + /** @description Exactly one well-formed locale, canonicalized by case without trimming. Headers do not select content; absent/disabled locales give unsupported_locale. */ + locale: string; + /** @description Canonical unpadded base64url v1 seek cursor, bound to host, scope, locale, endpoint and order. Not authority or a snapshot; malformed or mismatched values give validation_failed. */ + cursor?: string; + /** @description Positive ASCII decimal, including leading zeros. Default 20; values above 100 clamp to 100. Zero, signs, whitespace and repeats are refused. */ + limit?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PublicCourseCatalog"]; + }; + }; + /** @description validation_failed or unsupported_locale; bounded localizable field errors where applicable. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized; present invalid or undecidable credentials on a known host. Bare Bearer challenge; no credential or provider details. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for unavailable host or hidden/untranslated/ineligible resource; tenant_mismatch for authenticated host/claim or header disagreement, without disclosure. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed from routing. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "GET, HEAD"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; the decoded body bound precedes host classification and authentication. Kestrel framing/backstop refusals may occur outside the application response policy and omit these headers/body. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited from early visitor/peer admission, validated-subject quota or subject-registry capacity. */ + 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 from unexpected failures; no exception or query details. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable from invalid stored public configuration or a sticky subject-registry cleanup fault. */ + 503: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested dependency retry delay in seconds; not a recovery guarantee. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + HeadPublicCourses: { + parameters: { + query: { + /** @description Exactly one well-formed locale, canonicalized by case without trimming. Headers do not select content; absent/disabled locales give unsupported_locale. */ + locale: string; + /** @description Canonical unpadded base64url v1 seek cursor, bound to host, scope, locale, endpoint and order. Not authority or a snapshot; malformed or mismatched values give validation_failed. */ + cursor?: string; + /** @description Positive ASCII decimal, including leading zeros. Default 20; values above 100 clamp to 100. Zero, signs, whitespace and repeats are refused. */ + limit?: string; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description validation_failed or unsupported_locale; bounded localizable field errors where applicable. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description unauthorized; present invalid or undecidable credentials on a known host. Bare Bearer challenge; no credential or provider details. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description not_found for unavailable host or hidden/untranslated/ineligible resource; tenant_mismatch for authenticated host/claim or header disagreement, without disclosure. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description method_not_allowed from routing. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "GET, HEAD"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description payload_too_large; the decoded body bound precedes host classification and authentication. Kestrel framing/backstop refusals may occur outside the application response policy and omit these headers/body. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description rate_limited from early visitor/peer admission, validated-subject quota or subject-registry capacity. */ + 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?: never; + }; + /** @description internal_error from unexpected failures; no exception or query details. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description dependency_unavailable from invalid stored public configuration or a sticky subject-registry cleanup fault. */ + 503: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested dependency retry delay in seconds; not a recovery guarantee. */ + "Retry-After": number; + [name: string]: unknown; + }; + content?: never; + }; + }; + }; + GetPublicCourse: { + parameters: { + query: { + /** @description Exactly one well-formed locale, canonicalized by case without trimming. Headers do not select content; absent/disabled locales give unsupported_locale. */ + locale: string; + /** @description Canonical unpadded base64url v1 seek cursor, bound to host, scope, locale, endpoint and order. Not authority or a snapshot; malformed or mismatched values give validation_failed. */ + lessonCursor?: string; + /** @description Positive ASCII decimal, including leading zeros. Default 20; values above 100 clamp to 100. Zero, signs, whitespace and repeats are refused. */ + lessonLimit?: string; + }; + header?: never; + path: { + /** @description Lowercase ASCII slug with single interior hyphens; UUID-shaped slugs are refused. */ + slug: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PublicCourseDetail"]; + }; + }; + /** @description validation_failed or unsupported_locale; bounded localizable field errors where applicable. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized; present invalid or undecidable credentials on a known host. Bare Bearer challenge; no credential or provider details. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for unavailable host or hidden/untranslated/ineligible resource; tenant_mismatch for authenticated host/claim or header disagreement, without disclosure. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed from routing. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "GET, HEAD"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; the decoded body bound precedes host classification and authentication. Kestrel framing/backstop refusals may occur outside the application response policy and omit these headers/body. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited from early visitor/peer admission, validated-subject quota or subject-registry capacity. */ + 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 from unexpected failures; no exception or query details. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable from invalid stored public configuration or a sticky subject-registry cleanup fault. */ + 503: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested dependency retry delay in seconds; not a recovery guarantee. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + HeadPublicCourse: { + parameters: { + query: { + /** @description Exactly one well-formed locale, canonicalized by case without trimming. Headers do not select content; absent/disabled locales give unsupported_locale. */ + locale: string; + /** @description Canonical unpadded base64url v1 seek cursor, bound to host, scope, locale, endpoint and order. Not authority or a snapshot; malformed or mismatched values give validation_failed. */ + lessonCursor?: string; + /** @description Positive ASCII decimal, including leading zeros. Default 20; values above 100 clamp to 100. Zero, signs, whitespace and repeats are refused. */ + lessonLimit?: string; + }; + header?: never; + path: { + /** @description Lowercase ASCII slug with single interior hyphens; UUID-shaped slugs are refused. */ + slug: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description validation_failed or unsupported_locale; bounded localizable field errors where applicable. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description unauthorized; present invalid or undecidable credentials on a known host. Bare Bearer challenge; no credential or provider details. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description not_found for unavailable host or hidden/untranslated/ineligible resource; tenant_mismatch for authenticated host/claim or header disagreement, without disclosure. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description method_not_allowed from routing. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "GET, HEAD"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description payload_too_large; the decoded body bound precedes host classification and authentication. Kestrel framing/backstop refusals may occur outside the application response policy and omit these headers/body. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description rate_limited from early visitor/peer admission, validated-subject quota or subject-registry capacity. */ + 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?: never; + }; + /** @description internal_error from unexpected failures; no exception or query details. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description dependency_unavailable from invalid stored public configuration or a sticky subject-registry cleanup fault. */ + 503: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested dependency retry delay in seconds; not a recovery guarantee. */ + "Retry-After": number; + [name: string]: unknown; + }; + content?: never; + }; + }; + }; + GetPublicLesson: { + parameters: { + query: { + /** @description Exactly one well-formed locale, canonicalized by case without trimming. Headers do not select content; absent/disabled locales give unsupported_locale. */ + locale: string; + }; + header?: never; + path: { + /** @description Lowercase ASCII slug with single interior hyphens; UUID-shaped slugs are refused. */ + slug: string; + /** @description Lowercase ASCII slug with single interior hyphens; UUID-shaped slugs are refused. */ + lessonSlug: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PublicLessonDetail"]; + }; + }; + /** @description validation_failed or unsupported_locale; bounded localizable field errors where applicable. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized; present invalid or undecidable credentials on a known host. Bare Bearer challenge; no credential or provider details. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for unavailable host or hidden/untranslated/ineligible resource; tenant_mismatch for authenticated host/claim or header disagreement, without disclosure. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed from routing. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "GET, HEAD"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; the decoded body bound precedes host classification and authentication. Kestrel framing/backstop refusals may occur outside the application response policy and omit these headers/body. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited from early visitor/peer admission, validated-subject quota or subject-registry capacity. */ + 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 from unexpected failures; no exception or query details. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable from invalid stored public configuration or a sticky subject-registry cleanup fault. */ + 503: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested dependency retry delay in seconds; not a recovery guarantee. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + HeadPublicLesson: { + parameters: { + query: { + /** @description Exactly one well-formed locale, canonicalized by case without trimming. Headers do not select content; absent/disabled locales give unsupported_locale. */ + locale: string; + }; + header?: never; + path: { + /** @description Lowercase ASCII slug with single interior hyphens; UUID-shaped slugs are refused. */ + slug: string; + /** @description Lowercase ASCII slug with single interior hyphens; UUID-shaped slugs are refused. */ + lessonSlug: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description validation_failed or unsupported_locale; bounded localizable field errors where applicable. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description unauthorized; present invalid or undecidable credentials on a known host. Bare Bearer challenge; no credential or provider details. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description not_found for unavailable host or hidden/untranslated/ineligible resource; tenant_mismatch for authenticated host/claim or header disagreement, without disclosure. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description method_not_allowed from routing. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "GET, HEAD"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description payload_too_large; the decoded body bound precedes host classification and authentication. Kestrel framing/backstop refusals may occur outside the application response policy and omit these headers/body. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description rate_limited from early visitor/peer admission, validated-subject quota or subject-registry capacity. */ + 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?: never; + }; + /** @description internal_error from unexpected failures; no exception or query details. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description dependency_unavailable from invalid stored public configuration or a sticky subject-registry cleanup fault. */ + 503: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested dependency retry delay in seconds; not a recovery guarantee. */ + "Retry-After": number; + [name: string]: unknown; + }; + content?: never; + }; + }; + }; + GetPublicSignIn: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PublicSignIn"]; + }; + }; + /** @description validation_failed; the sign-in read accepts no query parameters, and malformed or repeated assertion headers are refused. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized; present invalid or undecidable credentials on a known host. Bare Bearer challenge; no credential or provider details. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for unavailable host or hidden/untranslated/ineligible resource; tenant_mismatch for authenticated host/claim or header disagreement, without disclosure. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed from routing. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "GET, HEAD"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; the decoded body bound precedes host classification and authentication. Kestrel framing/backstop refusals may occur outside the application response policy and omit these headers/body. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited from early visitor/peer admission, validated-subject quota or subject-registry capacity. */ + 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 from unexpected failures; no exception or query details. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable from invalid stored public configuration or a sticky subject-registry cleanup fault. */ + 503: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested dependency retry delay in seconds; not a recovery guarantee. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + HeadPublicSignIn: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description validation_failed; the sign-in read accepts no query parameters, and malformed or repeated assertion headers are refused. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description unauthorized; present invalid or undecidable credentials on a known host. Bare Bearer challenge; no credential or provider details. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description not_found for unavailable host or hidden/untranslated/ineligible resource; tenant_mismatch for authenticated host/claim or header disagreement, without disclosure. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description method_not_allowed from routing. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "GET, HEAD"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description payload_too_large; the decoded body bound precedes host classification and authentication. Kestrel framing/backstop refusals may occur outside the application response policy and omit these headers/body. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description rate_limited from early visitor/peer admission, validated-subject quota or subject-registry capacity. */ + 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?: never; + }; + /** @description internal_error from unexpected failures; no exception or query details. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description dependency_unavailable from invalid stored public configuration or a sticky subject-registry cleanup fault. */ + 503: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested dependency retry delay in seconds; not a recovery guarantee. */ + "Retry-After": number; + [name: string]: unknown; + }; + content?: never; + }; + }; + }; + GetPublicSite: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["PublicSite"]; + }; + }; + /** @description validation_failed; the site bootstrap accepts no query parameters, and malformed or repeated assertion headers are refused. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description unauthorized; present invalid or undecidable credentials on a known host. Bare Bearer challenge; no credential or provider details. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description not_found for unavailable host or hidden/untranslated/ineligible resource; tenant_mismatch for authenticated host/claim or header disagreement, without disclosure. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description method_not_allowed from routing. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "GET, HEAD"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description payload_too_large; the decoded body bound precedes host classification and authentication. Kestrel framing/backstop refusals may occur outside the application response policy and omit these headers/body. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description rate_limited from early visitor/peer admission, validated-subject quota or subject-registry capacity. */ + 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 from unexpected failures; no exception or query details. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description dependency_unavailable from invalid stored public configuration or a sticky subject-registry cleanup fault. */ + 503: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested dependency retry delay in seconds; not a recovery guarantee. */ + "Retry-After": number; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + }; + }; + HeadPublicSite: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description validation_failed; the site bootstrap accepts no query parameters, and malformed or repeated assertion headers are refused. */ + 400: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description unauthorized; present invalid or undecidable credentials on a known host. Bare Bearer challenge; no credential or provider details. */ + 401: { + headers: { + "Cache-Control": "no-store"; + "WWW-Authenticate": "Bearer"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description not_found for unavailable host or hidden/untranslated/ineligible resource; tenant_mismatch for authenticated host/claim or header disagreement, without disclosure. */ + 404: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description method_not_allowed from routing. */ + 405: { + headers: { + "Cache-Control": "no-store"; + Allow: "GET, HEAD"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description payload_too_large; the decoded body bound precedes host classification and authentication. Kestrel framing/backstop refusals may occur outside the application response policy and omit these headers/body. */ + 413: { + headers: { + "Cache-Control"?: "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description rate_limited from early visitor/peer admission, validated-subject quota or subject-registry capacity. */ + 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?: never; + }; + /** @description internal_error from unexpected failures; no exception or query details. */ + 500: { + headers: { + "Cache-Control": "no-store"; + [name: string]: unknown; + }; + content?: never; + }; + /** @description dependency_unavailable from invalid stored public configuration or a sticky subject-registry cleanup fault. */ + 503: { + headers: { + "Cache-Control": "no-store"; + /** @description Suggested dependency retry delay in seconds; not a recovery guarantee. */ + "Retry-After": number; + [name: string]: unknown; + }; + content?: never; + }; }; - /** Format: uuid */ - TenantId: string; - /** Format: uuid */ - UserId: string; }; - responses: never; - parameters: never; - requestBodies: never; - headers: never; - pathItems: never; -} -export type $defs = Record<string, never>; -export interface operations { - ListOwnFieldConsentScopes: { + 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. Paging is forward only: follow pageInfo.nextCursor; there is no previous page. */ limit?: number; }; header?: never; @@ -1931,17 +5247,17 @@ export interface operations { }; requestBody?: never; responses: { - /** @description Authorized current projection or minimal committed receipt. */ + /** @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"]["ConsentScopePageResponse"]; + "application/json": components["schemas"]["RetainedDataRequestScopePageResponse"]; }; }; - /** @description validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input. */ + /** @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"; @@ -1951,7 +5267,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description unauthorized: invalid credentials. */ + /** @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"; @@ -1962,7 +5278,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description forbidden: no current operation authority. */ + /** @description forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed. */ 403: { headers: { "Cache-Control": "no-store"; @@ -1972,7 +5288,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description not_found: foreign, missing or noncovered exact scope/target. */ + /** @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"; @@ -1982,7 +5298,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description method_not_allowed after earlier admission gates. */ + /** @description method_not_allowed after earlier host, credential and scope gates. */ 405: { headers: { "Cache-Control": "no-store"; @@ -1993,7 +5309,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description payload_too_large: input over the outer byte bound. */ + /** @description payload_too_large; request bodies are at most 4 KiB. */ 413: { headers: { "Cache-Control"?: "no-store"; @@ -2003,7 +5319,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description rate_limited by existing admission. */ + /** @description rate_limited by the existing visitor/subject admission. */ 429: { headers: { "Cache-Control": "no-store"; @@ -2015,7 +5331,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description internal_error with payload-free diagnostics. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; @@ -2025,7 +5341,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description dependency_unavailable or audit_unavailable; no unconfirmed success. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; @@ -2037,12 +5353,15 @@ export interface operations { }; }; }; - ListOwnMembershipFieldConsents: { + 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. Paging is forward only: follow pageInfo.nextCursor; there is no previous page. */ limit?: number; - membershipId: string; }; header?: never; path?: never; @@ -2050,17 +5369,17 @@ export interface operations { }; requestBody?: never; responses: { - /** @description Authorized current projection or minimal committed receipt. */ + /** @description Current receipt-safe projection: status and counts, never content. */ 200: { headers: { "Cache-Control": "no-store"; [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ConsentHistoryPageResponse"]; + "application/json": components["schemas"]["OwnDataRequestPage"]; }; }; - /** @description validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input. */ + /** @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"; @@ -2070,7 +5389,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description unauthorized: invalid credentials. */ + /** @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"; @@ -2081,7 +5400,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description forbidden: no current operation authority. */ + /** @description forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed. */ 403: { headers: { "Cache-Control": "no-store"; @@ -2091,7 +5410,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description not_found: foreign, missing or noncovered exact scope/target. */ + /** @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"; @@ -2101,18 +5420,157 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description method_not_allowed after earlier admission gates. */ + /** @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. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ + 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: "GET"; + Allow: "POST"; + [name: string]: unknown; + }; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; + }; + /** @description business_rule_violation: errors.$ carries lockey_request_already_active (a request of this kind is still active in the group), lockey_blocked_hold, or lockey_subject_not_admitted (the person's account is closing or closed: nothing is filed); 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: input over the outer byte bound. */ + /** @description payload_too_large; request bodies are at most 4 KiB. */ 413: { headers: { "Cache-Control"?: "no-store"; @@ -2122,7 +5580,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description rate_limited by existing admission. */ + /** @description rate_limited by the existing visitor/subject admission. */ 429: { headers: { "Cache-Control": "no-store"; @@ -2134,7 +5592,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description internal_error with payload-free diagnostics. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; @@ -2144,7 +5602,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description dependency_unavailable or audit_unavailable; no unconfirmed success. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; @@ -2156,12 +5614,14 @@ export interface operations { }; }; }; - WithdrawOwnMembershipFieldConsent: { + CreateRetainedDataErasure: { parameters: { query: { - membershipId: string; + /** @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; @@ -2169,22 +5629,25 @@ export interface operations { }; requestBody: { content: { - "application/json": components["schemas"]["FieldConsentWithdrawalInput"]; + "application/json": components["schemas"]["EmptyAdministrationInput"]; }; }; responses: { - /** @description Authorized current projection or minimal committed receipt. */ - 200: { + /** @description Accepted: the request's initial resource, scheduled. Its erasure runs as a background job once its 24-hour cancellable window ends; read the group's requests for its status. */ + 202: { headers: { - "Idempotency-Replayed"?: "true"; "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"]["FieldConsentReceiptResponse"]; + "application/json": components["schemas"]["DataErasureAcceptedResponse"]; }; }; - /** @description validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input. */ + /** @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"; @@ -2194,7 +5657,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description unauthorized: invalid credentials. */ + /** @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"; @@ -2205,7 +5668,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description forbidden: no current operation authority. */ + /** @description forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed. */ 403: { headers: { "Cache-Control": "no-store"; @@ -2215,7 +5678,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description not_found: foreign, missing or noncovered exact scope/target. */ + /** @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"; @@ -2225,7 +5688,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description method_not_allowed after earlier admission gates. */ + /** @description method_not_allowed after earlier host, credential and scope gates. */ 405: { headers: { "Cache-Control": "no-store"; @@ -2236,7 +5699,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description concurrency_conflict, business_rule_violation, limit_exceeded, request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable; no automatic retry. */ + /** @description business_rule_violation: errors.$ carries lockey_request_already_active (an erasure is still active in the group), lockey_blocked_last_administrator (the person is the tenant's only eligible tenant-wide administrator; another must be appointed first), lockey_blocked_hold, or lockey_subject_not_admitted (the person's account is closing or closed: nothing is filed); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state. */ 409: { headers: { "Cache-Control": "no-store"; @@ -2246,7 +5709,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description payload_too_large: input over the outer byte bound. */ + /** @description payload_too_large; request bodies are at most 4 KiB. */ 413: { headers: { "Cache-Control"?: "no-store"; @@ -2256,7 +5719,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description rate_limited by existing admission. */ + /** @description rate_limited by the existing visitor/subject admission. */ 429: { headers: { "Cache-Control": "no-store"; @@ -2268,7 +5731,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description internal_error with payload-free diagnostics. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; @@ -2278,7 +5741,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description dependency_unavailable or audit_unavailable; no unconfirmed success. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; @@ -2290,38 +5753,40 @@ export interface operations { }; }; }; - SelectDefaultOrganization: { + CreateRetainedAccountClosure: { parameters: { - query?: never; + 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 aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version. */ - "If-Match": string; }; path?: never; cookie?: never; }; requestBody: { content: { - "application/json": components["schemas"]["DefaultOrganizationInput"]; + "application/json": components["schemas"]["EmptyAdministrationInput"]; }; }; responses: { - /** @description Successful current projection or retained committed receipt. */ - 200: { + /** @description Accepted: the request's initial resource, scheduled. No job runs it: an operator may Begin it from its executeAt, and until that Begin commits it can be cancelled. Read the group's requests for its status while the account still works. */ + 202: { headers: { "Cache-Control": "no-store"; + /** @description The request's version. */ ETag: string; - /** @description Present only after fresh original-target disclosure audit on a replay. */ + /** @description Present only after fresh original-request disclosure on a replay. */ "Idempotency-Replayed"?: "true"; [name: string]: unknown; }; content: { - "application/json": components["schemas"]["AdministrationVersionReceipt"]; + "application/json": components["schemas"]["AccountClosureAcceptedResponse"]; }; }; - /** @description validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition. */ + /** @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"; @@ -2331,7 +5796,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge. */ + /** @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"; @@ -2342,7 +5807,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description forbidden for live coverage without current operation or target disclosure capability. */ + /** @description forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed. */ 403: { headers: { "Cache-Control": "no-store"; @@ -2352,7 +5817,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement. */ + /** @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"; @@ -2366,14 +5831,14 @@ export interface operations { 405: { headers: { "Cache-Control": "no-store"; - Allow: "PUT"; + Allow: "POST"; [name: string]: unknown; }; content: { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description concurrency_conflict for a valid stale version; business_rule_violation for refused lifecycle/last-admin/last-organization rules; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state. */ + /** @description business_rule_violation: errors.$ carries lockey_request_already_active (another closure of the person is still active in the group), lockey_blocked_hold, or lockey_subject_not_admitted (the person's account is closing or closed: nothing is filed); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state. */ 409: { headers: { "Cache-Control": "no-store"; @@ -2383,7 +5848,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies. */ + /** @description payload_too_large; request bodies are at most 4 KiB. */ 413: { headers: { "Cache-Control"?: "no-store"; @@ -2405,7 +5870,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description internal_error without provider, query, identity or submitted-value diagnostics. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; @@ -2415,7 +5880,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; @@ -2427,28 +5892,42 @@ export interface operations { }; }; }; - GetTenantInvitationPolicy: { + CancelRetainedDataRequest: { parameters: { - query?: never; - header?: never; + 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?: never; + requestBody: { + content: { + "application/json": components["schemas"]["RetainedDataRequestTargetInput"]; + }; + }; responses: { - /** @description Successful current projection or retained committed receipt. */ + /** @description Committed receipt, or the retained receipt of a completed exact-key replay. */ 200: { headers: { "Cache-Control": "no-store"; - /** @description Present exactly when the fixed policy setting exists; never emitted for the absent/default policy. */ - ETag?: string; + /** @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"]["InvitationPolicyResponse"]; + "application/json": components["schemas"]["AdministrationVersionReceipt"]; }; }; - /** @description validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition. */ + /** @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"; @@ -2458,7 +5937,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge. */ + /** @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"; @@ -2469,7 +5948,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description forbidden for live coverage without current operation or target disclosure capability. */ + /** @description forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed. */ 403: { headers: { "Cache-Control": "no-store"; @@ -2479,7 +5958,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement. */ + /** @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"; @@ -2493,14 +5972,24 @@ export interface operations { 405: { headers: { "Cache-Control": "no-store"; - Allow: "GET, PUT"; + Allow: "POST"; [name: string]: unknown; }; content: { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies. */ + /** @description concurrency_conflict for a valid stale version; business_rule_violation with errors.$ carrying lockey_data_request_window_ended (an erasure's cancellable window has ended and it runs now) or lockey_data_request_not_cancellable (the request is no longer one a cancellation admits: it already ended, or an export already started); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state. A closure is never window_ended: its not_cancellable means an operator's Begin committed, after which the closure is irreversible. */ + 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"; @@ -2522,7 +6011,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description internal_error without provider, query, identity or submitted-value diagnostics. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; @@ -2532,7 +6021,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; @@ -2544,32 +6033,34 @@ export interface operations { }; }; }; - SetTenantInvitationLifetime: { + RevokeRetainedDataExport: { parameters: { - query?: never; + 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 aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version. */ - "If-Match"?: string; - /** @description Exactly one literal wildcard for conditional creation of the absent fixed policy. Mutually exclusive with If-Match; an existing version-zero setting is not absent. */ - "If-None-Match"?: "*"; + /** @description 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. */ + "If-Match": string; }; path?: never; cookie?: never; }; requestBody: { content: { - "application/json": components["schemas"]["InvitationLifetimeInput"]; + "application/json": components["schemas"]["RetainedDataRequestTargetInput"]; }; }; responses: { - /** @description Successful current projection or retained committed receipt. */ + /** @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-target disclosure audit on a replay. */ + /** @description Present only after fresh original-request disclosure on a replay. */ "Idempotency-Replayed"?: "true"; [name: string]: unknown; }; @@ -2577,7 +6068,7 @@ export interface operations { "application/json": components["schemas"]["AdministrationVersionReceipt"]; }; }; - /** @description validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition. */ + /** @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"; @@ -2587,7 +6078,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge. */ + /** @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"; @@ -2598,7 +6089,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description forbidden for live coverage without current operation or target disclosure capability. */ + /** @description forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed. */ 403: { headers: { "Cache-Control": "no-store"; @@ -2608,7 +6099,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement. */ + /** @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"; @@ -2622,14 +6113,14 @@ export interface operations { 405: { headers: { "Cache-Control": "no-store"; - Allow: "GET, PUT"; + Allow: "POST"; [name: string]: unknown; }; content: { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description concurrency_conflict for a valid stale version; business_rule_violation for refused lifecycle/last-admin/last-organization rules; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state. */ + /** @description concurrency_conflict for a valid stale artifact 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"; @@ -2639,7 +6130,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies. */ + /** @description payload_too_large; request bodies are at most 4 KiB. */ 413: { headers: { "Cache-Control"?: "no-store"; @@ -2661,7 +6152,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description internal_error without provider, query, identity or submitted-value diagnostics. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; @@ -2671,7 +6162,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; @@ -2683,31 +6174,33 @@ export interface operations { }; }; }; - ListOrganizations: { + MintRetainedDataExportTicket: { parameters: { - query?: { - /** @description Opaque canonical current-actor/scope/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; + 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?: never; + requestBody: { + content: { + "application/json": components["schemas"]["RetainedDataRequestTargetInput"]; + }; + }; responses: { - /** @description Successful current projection or retained committed receipt. */ + /** @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"]["OrganizationDirectoryResponse"]; + "application/json": components["schemas"]["DataExportTicketResponse"]; }; }; - /** @description validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition. */ + /** @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"; @@ -2717,7 +6210,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge. */ + /** @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"; @@ -2728,7 +6221,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description forbidden for live coverage without current operation or target disclosure capability. */ + /** @description forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed. */ 403: { headers: { "Cache-Control": "no-store"; @@ -2738,7 +6231,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement. */ + /** @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 gone (revoked, expired, purged, or sealed under a key the export key ring no longer holds) and only a new export helps; with data_export_ticket_limit, a ticket bound is reached (see the mint's 409). */ 404: { headers: { "Cache-Control": "no-store"; @@ -2752,14 +6245,24 @@ export interface operations { 405: { headers: { "Cache-Control": "no-store"; - Allow: "GET, POST"; + Allow: "POST"; [name: string]: unknown; }; content: { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies. */ + /** @description business_rule_violation. errors.artifact carries data_export_unavailable when the request has no available, unexpired artifact or the key it was sealed under is no longer in the export key ring: the artifact is gone and only a new export helps. It carries data_export_ticket_limit when a ticket bound is reached: this session already holds 3 unconsumed, unexpired tickets over the artifact (wait until one is consumed by its final chunk or expires, 15 minutes after it was minted; a ticket of an earlier, refreshed credential does not count), or 20 tickets have been minted over the artifact in all, which is final: file a new export. */ + 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"; @@ -2781,7 +6284,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description internal_error without provider, query, identity or submitted-value diagnostics. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; @@ -2791,7 +6294,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; @@ -2803,38 +6306,33 @@ export interface operations { }; }; }; - CreateManagedOrganization: { + ReadRetainedDataExportChunk: { 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; + 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"]["OrganizationCreateInput"]; + "application/json": components["schemas"]["RetainedDataExportChunkInput"]; }; }; responses: { - /** @description Committed creation receipt. */ - 201: { + /** @description One decrypted chunk: index, count and the base64 of at most 128 KiB of plaintext. 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. */ + 200: { headers: { "Cache-Control": "no-store"; - ETag: string; - /** @description Present only after fresh original-target disclosure audit on a replay. */ - "Idempotency-Replayed"?: "true"; - /** @description Exact same-API relative location of the newly created original resource. */ - Location: string; [name: string]: unknown; }; content: { - "application/json": components["schemas"]["AdministrationVersionReceipt"]; + "application/json": components["schemas"]["DataExportChunkResponse"]; }; }; - /** @description validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition. */ + /** @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"; @@ -2844,7 +6342,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge. */ + /** @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"; @@ -2855,7 +6353,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description forbidden for live coverage without current operation or target disclosure capability. */ + /** @description forbidden when the request carries no retained-entry credential a ticket can bind, or its witness closed. */ 403: { headers: { "Cache-Control": "no-store"; @@ -2865,7 +6363,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement. */ + /** @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 gone (revoked, expired, purged, or sealed under a key the export key ring no longer holds) and only a new export helps; with data_export_ticket_limit, a ticket bound is reached (see the mint's 409). */ 404: { headers: { "Cache-Control": "no-store"; @@ -2879,24 +6377,14 @@ export interface operations { 405: { headers: { "Cache-Control": "no-store"; - Allow: "GET, POST"; - [name: string]: unknown; - }; - content: { - "application/problem+json": components["schemas"]["ProblemDetails"]; - }; - }; - /** @description concurrency_conflict for a valid stale version; business_rule_violation for refused lifecycle/last-admin/last-organization rules; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state. */ - 409: { - headers: { - "Cache-Control": "no-store"; + Allow: "POST"; [name: string]: unknown; }; content: { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies. */ + /** @description payload_too_large; request bodies are at most 4 KiB. */ 413: { headers: { "Cache-Control"?: "no-store"; @@ -2918,7 +6406,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description internal_error without provider, query, identity or submitted-value diagnostics. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; @@ -2928,7 +6416,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; @@ -2940,30 +6428,39 @@ export interface operations { }; }; }; - GetOrganizationDetail: { + CreateOwnDataExport: { parameters: { query?: never; - header?: never; - path: { - /** @description Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority. */ - id: 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?: never; + requestBody: { + content: { + "application/json": components["schemas"]["EmptyAdministrationInput"]; + }; + }; responses: { - /** @description Successful current projection or retained committed receipt. */ - 200: { + /** @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"]["OrganizationResponse"]; + "application/json": components["schemas"]["DataRequestAcceptedResponse"]; }; }; - /** @description validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition. */ + /** @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"; @@ -2973,7 +6470,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge. */ + /** @description unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge. */ 401: { headers: { "Cache-Control": "no-store"; @@ -2984,7 +6481,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description forbidden for live coverage without current operation or target disclosure capability. */ + /** @description forbidden when the request carries no live session the ticket can bind. */ 403: { headers: { "Cache-Control": "no-store"; @@ -2994,7 +6491,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement. */ + /** @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"; @@ -3008,14 +6505,24 @@ export interface operations { 405: { headers: { "Cache-Control": "no-store"; - Allow: "GET, PUT"; + Allow: "POST"; [name: string]: unknown; }; content: { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies. */ + /** @description business_rule_violation: errors.$ carries lockey_request_already_active (a request of this kind is still active in the group), lockey_blocked_hold, or lockey_subject_not_admitted (the person's account is closing or closed: nothing is filed); 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"; @@ -3037,7 +6544,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description internal_error without provider, query, identity or submitted-value diagnostics. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; @@ -3047,7 +6554,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; @@ -3059,41 +6566,39 @@ export interface operations { }; }; }; - RenameOrganization: { + CreateOwnDataErasure: { 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 aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version. */ - "If-Match": string; - }; - path: { - /** @description Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority. */ - id: string; }; + path?: never; cookie?: never; }; requestBody: { content: { - "application/json": components["schemas"]["OrganizationRenameInput"]; + "application/json": components["schemas"]["EmptyAdministrationInput"]; }; }; responses: { - /** @description Successful current projection or retained committed receipt. */ - 200: { + /** @description Accepted: the request's initial resource, scheduled. Its erasure runs as a background job once its 24-hour cancellable window ends; 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-target disclosure audit on a replay. */ + /** @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"]["AdministrationVersionReceipt"]; + "application/json": components["schemas"]["DataErasureAcceptedResponse"]; }; }; - /** @description validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition. */ + /** @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"; @@ -3103,7 +6608,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge. */ + /** @description unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge. */ 401: { headers: { "Cache-Control": "no-store"; @@ -3114,7 +6619,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description forbidden for live coverage without current operation or target disclosure capability. */ + /** @description forbidden when the request carries no live session the ticket can bind. */ 403: { headers: { "Cache-Control": "no-store"; @@ -3124,7 +6629,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement. */ + /** @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"; @@ -3138,14 +6643,14 @@ export interface operations { 405: { headers: { "Cache-Control": "no-store"; - Allow: "GET, PUT"; + Allow: "POST"; [name: string]: unknown; }; content: { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description concurrency_conflict for a valid stale version; business_rule_violation for refused lifecycle/last-admin/last-organization rules; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state. */ + /** @description business_rule_violation: errors.$ carries lockey_request_already_active (an erasure is still active in the group), lockey_blocked_last_administrator (the person is the tenant's only eligible tenant-wide administrator; another must be appointed first), lockey_blocked_hold, or lockey_subject_not_admitted (the person's account is closing or closed: nothing is filed); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state. */ 409: { headers: { "Cache-Control": "no-store"; @@ -3155,7 +6660,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies. */ + /** @description payload_too_large; request bodies are at most 16 KiB. */ 413: { headers: { "Cache-Control"?: "no-store"; @@ -3177,7 +6682,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description internal_error without provider, query, identity or submitted-value diagnostics. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; @@ -3187,7 +6692,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; @@ -3199,19 +6704,14 @@ export interface operations { }; }; }; - ArchiveOrganization: { + CreateOwnAccountClosure: { 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 aggregate version in [0, Int64.MaxValue]. Missing, weak, wildcard, list, repeated and noncanonical values are 400; valid stale versions are 409. Default selection uses the Tenant version. */ - "If-Match": string; - }; - path: { - /** @description Canonical lowercase nonreserved RFC UUIDv7. Another scope never supplies target authority. */ - id: string; + /** @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: { @@ -3220,20 +6720,23 @@ export interface operations { }; }; responses: { - /** @description Successful current projection or retained committed receipt. */ - 200: { + /** @description Accepted: the request's initial resource, scheduled. No job runs it: an operator may Begin it from its executeAt, and until that Begin commits it can be cancelled. Read the Location for its status while the account still works. */ + 202: { headers: { "Cache-Control": "no-store"; + /** @description The request's version. */ ETag: string; - /** @description Present only after fresh original-target disclosure audit on a replay. */ + /** @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"]["AdministrationVersionReceipt"]; + "application/json": components["schemas"]["AccountClosureAcceptedResponse"]; }; }; - /** @description validation_failed for malformed/noncanonical input, extra/repeated query, unexpected body or invalid key/precondition. */ + /** @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"; @@ -3243,7 +6746,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description unauthorized for present invalid/expired or undecidable credentials; bare Bearer challenge. */ + /** @description unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge. */ 401: { headers: { "Cache-Control": "no-store"; @@ -3254,7 +6757,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description forbidden for live coverage without current operation or target disclosure capability. */ + /** @description forbidden when the request carries no live session the ticket can bind. */ 403: { headers: { "Cache-Control": "no-store"; @@ -3264,7 +6767,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description not_found for missing credentials, noncoverage or absent/foreign targets; tenant_mismatch for trusted scope/assertion disagreement. */ + /** @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"; @@ -3285,7 +6788,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description concurrency_conflict for a valid stale version; business_rule_violation for refused lifecycle/last-admin/last-organization rules; request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state. */ + /** @description business_rule_violation: errors.$ carries lockey_request_already_active (another closure of the person is still active in the group), lockey_blocked_hold, or lockey_subject_not_admitted (the person's account is closing or closed: nothing is filed); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state. */ 409: { headers: { "Cache-Control": "no-store"; @@ -3295,7 +6798,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description payload_too_large; administration bodies are at most 16 KiB, including undeclared/chunked bodies. */ + /** @description payload_too_large; request bodies are at most 16 KiB. */ 413: { headers: { "Cache-Control"?: "no-store"; @@ -3317,7 +6820,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description internal_error without provider, query, identity or submitted-value diagnostics. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; @@ -3327,7 +6830,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description dependency_unavailable or audit_unavailable; no successful payload is disclosed on unconfirmed storage, cleanup or MUST audit. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; @@ -3339,12 +6842,13 @@ export interface operations { }; }; }; - GetOwnMembershipFieldConsent: { + ListOwnDataRequests: { parameters: { - query: { - membershipId: string; - definitionId: string; - definitionVersion: number; + 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; 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. */ + limit?: number; }; header?: never; path?: never; @@ -3352,17 +6856,17 @@ export interface operations { }; requestBody?: never; responses: { - /** @description Authorized current projection or minimal committed receipt. */ + /** @description Current receipt-safe projection: status and counts, never content. */ 200: { headers: { "Cache-Control": "no-store"; [name: string]: unknown; }; content: { - "application/json": components["schemas"]["OwnFieldConsentCurrentResponse"]; + "application/json": components["schemas"]["OwnDataRequestPage"]; }; }; - /** @description validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input. */ + /** @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"; @@ -3372,7 +6876,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description unauthorized: invalid credentials. */ + /** @description unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge. */ 401: { headers: { "Cache-Control": "no-store"; @@ -3383,7 +6887,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description forbidden: no current operation authority. */ + /** @description forbidden when the request carries no live session the ticket can bind. */ 403: { headers: { "Cache-Control": "no-store"; @@ -3393,7 +6897,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description not_found: foreign, missing or noncovered exact scope/target. */ + /** @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"; @@ -3403,7 +6907,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description method_not_allowed after earlier admission gates. */ + /** @description method_not_allowed after earlier host, credential and scope gates. */ 405: { headers: { "Cache-Control": "no-store"; @@ -3414,7 +6918,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description payload_too_large: input over the outer byte bound. */ + /** @description payload_too_large; request bodies are at most 16 KiB. */ 413: { headers: { "Cache-Control"?: "no-store"; @@ -3424,7 +6928,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description rate_limited by existing admission. */ + /** @description rate_limited by the existing visitor/subject admission. */ 429: { headers: { "Cache-Control": "no-store"; @@ -3436,7 +6940,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description internal_error with payload-free diagnostics. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; @@ -3446,7 +6950,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description dependency_unavailable or audit_unavailable; no unconfirmed success. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; @@ -3458,33 +6962,31 @@ export interface operations { }; }; }; - GrantOwnMembershipFieldConsent: { + GetOwnDataRequest: { parameters: { query?: never; - header: { - "Idempotency-Key": string; + header?: never; + path: { + /** @description Canonical lowercase RFC UUIDv7 of a request of the context's group. Another group's request is absent. */ + id: string; }; - path?: never; cookie?: never; }; - requestBody: { - content: { - "application/json": components["schemas"]["FieldConsentGrantInput"]; - }; - }; + requestBody?: never; responses: { - /** @description Authorized current projection or minimal committed receipt. */ + /** @description Current receipt-safe projection: status and counts, never content. */ 200: { headers: { - "Idempotency-Replayed"?: "true"; "Cache-Control": "no-store"; + /** @description The request's version. */ + ETag: string; [name: string]: unknown; }; content: { - "application/json": components["schemas"]["FieldConsentReceiptResponse"]; + "application/json": components["schemas"]["OwnDataRequestResponse"]; }; }; - /** @description validation_failed: malformed, duplicate, missing, oversized normalized or noncanonical input. */ + /** @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"; @@ -3494,7 +6996,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description unauthorized: invalid credentials. */ + /** @description unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge. */ 401: { headers: { "Cache-Control": "no-store"; @@ -3505,7 +7007,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description forbidden: no current operation authority. */ + /** @description forbidden when the request carries no live session the ticket can bind. */ 403: { headers: { "Cache-Control": "no-store"; @@ -3515,7 +7017,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description not_found: foreign, missing or noncovered exact scope/target. */ + /** @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"; @@ -3525,28 +7027,18 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description method_not_allowed after earlier admission gates. */ + /** @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, business_rule_violation, limit_exceeded, request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable; no automatic retry. */ - 409: { - headers: { - "Cache-Control": "no-store"; + Allow: "GET"; [name: string]: unknown; }; content: { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description payload_too_large: input over the outer byte bound. */ + /** @description payload_too_large; request bodies are at most 16 KiB. */ 413: { headers: { "Cache-Control"?: "no-store"; @@ -3556,7 +7048,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description rate_limited by existing admission. */ + /** @description rate_limited by the existing visitor/subject admission. */ 429: { headers: { "Cache-Control": "no-store"; @@ -3568,7 +7060,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description internal_error with payload-free diagnostics. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; @@ -3578,7 +7070,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description dependency_unavailable or audit_unavailable; no unconfirmed success. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; @@ -3590,33 +7082,42 @@ export interface operations { }; }; }; - GetPublicCourses: { + CancelOwnDataRequest: { parameters: { - query: { - /** @description Exactly one well-formed locale, canonicalized by case without trimming. Headers do not select content; absent/disabled locales give unsupported_locale. */ - locale: string; - /** @description Canonical unpadded base64url v1 seek cursor, bound to host, scope, locale, endpoint and order. Not authority or a snapshot; malformed or mismatched values give validation_failed. */ - cursor?: string; - /** @description Positive ASCII decimal, including leading zeros. Default 20; values above 100 clamp to 100. Zero, signs, whitespace and repeats are refused. */ - limit?: string; + 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; }; - header?: never; - path?: never; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "application/json": components["schemas"]["EmptyAdministrationInput"]; + }; + }; responses: { - /** @description OK */ + /** @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"]["PublicCourseCatalog"]; + "application/json": components["schemas"]["AdministrationVersionReceipt"]; }; }; - /** @description validation_failed or unsupported_locale; bounded localizable field errors where applicable. */ + /** @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"; @@ -3626,7 +7127,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description unauthorized; present invalid or undecidable credentials on a known host. Bare Bearer challenge; no credential or provider details. */ + /** @description unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge. */ 401: { headers: { "Cache-Control": "no-store"; @@ -3637,7 +7138,17 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description not_found for unavailable host or hidden/untranslated/ineligible resource; tenant_mismatch for authenticated host/claim or header disagreement, without disclosure. */ + /** @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"; @@ -3647,18 +7158,28 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description method_not_allowed from routing. */ + /** @description method_not_allowed after earlier host, credential and scope gates. */ 405: { headers: { "Cache-Control": "no-store"; - Allow: "GET, HEAD"; + Allow: "POST"; [name: string]: unknown; }; content: { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description payload_too_large; the decoded body bound precedes host classification and authentication. Kestrel framing/backstop refusals may occur outside the application response policy and omit these headers/body. */ + /** @description concurrency_conflict for a valid stale version; business_rule_violation with errors.$ carrying lockey_data_request_window_ended (an erasure's cancellable window has ended and it runs now) or lockey_data_request_not_cancellable (the request is no longer one a cancellation admits: it already ended, or an export already started); request_in_progress, idempotency_key_reuse or idempotency_outcome_unavailable for retained-key state. A closure is never window_ended: its not_cancellable means an operator's Begin committed, after which the closure is irreversible. */ + 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"; @@ -3668,7 +7189,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description rate_limited from early visitor/peer admission, validated-subject quota or subject-registry capacity. */ + /** @description rate_limited by the existing visitor/subject admission. */ 429: { headers: { "Cache-Control": "no-store"; @@ -3680,7 +7201,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description internal_error from unexpected failures; no exception or query details. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; @@ -3690,12 +7211,10 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description dependency_unavailable from invalid stored public configuration or a sticky subject-registry cleanup fault. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; - /** @description Suggested dependency retry delay in seconds; not a recovery guarantee. */ - "Retry-After": number; [name: string]: unknown; }; content: { @@ -3704,73 +7223,114 @@ export interface operations { }; }; }; - HeadPublicCourses: { + RevokeOwnDataExport: { parameters: { - query: { - /** @description Exactly one well-formed locale, canonicalized by case without trimming. Headers do not select content; absent/disabled locales give unsupported_locale. */ - locale: string; - /** @description Canonical unpadded base64url v1 seek cursor, bound to host, scope, locale, endpoint and order. Not authority or a snapshot; malformed or mismatched values give validation_failed. */ - cursor?: string; - /** @description Positive ASCII decimal, including leading zeros. Default 20; values above 100 clamp to 100. Zero, signs, whitespace and repeats are refused. */ - limit?: string; + 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, not the request's version. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale artifact 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; }; - header?: never; - path?: never; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "application/json": components["schemas"]["EmptyAdministrationInput"]; + }; + }; responses: { - /** @description OK */ + /** @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 (artifact.version), not the request's. */ + ETag: string; + /** @description Present only after fresh original-request disclosure on a replay. */ + "Idempotency-Replayed"?: "true"; [name: string]: unknown; }; - content?: never; + content: { + "application/json": components["schemas"]["AdministrationVersionReceipt"]; + }; }; - /** @description validation_failed or unsupported_locale; bounded localizable field errors where applicable. */ + /** @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?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description unauthorized; present invalid or undecidable credentials on a known host. Bare Bearer challenge; no credential or provider details. */ + /** @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?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description not_found for unavailable host or hidden/untranslated/ineligible resource; tenant_mismatch for authenticated host/claim or header disagreement, without disclosure. */ + /** @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?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description method_not_allowed from routing. */ + /** @description method_not_allowed after earlier host, credential and scope gates. */ 405: { headers: { "Cache-Control": "no-store"; - Allow: "GET, HEAD"; + Allow: "POST"; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description payload_too_large; the decoded body bound precedes host classification and authentication. Kestrel framing/backstop refusals may occur outside the application response policy and omit these headers/body. */ + /** @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?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description rate_limited from early visitor/peer admission, validated-subject quota or subject-registry capacity. */ + /** @description rate_limited by the existing visitor/subject admission. */ 429: { headers: { "Cache-Control": "no-store"; @@ -3778,58 +7338,59 @@ export interface operations { "Retry-After": number; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description internal_error from unexpected failures; no exception or query details. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description dependency_unavailable from invalid stored public configuration or a sticky subject-registry cleanup fault. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; - /** @description Suggested dependency retry delay in seconds; not a recovery guarantee. */ - "Retry-After": number; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; }; }; - GetPublicCourse: { + MintOwnDataExportTicket: { parameters: { - query: { - /** @description Exactly one well-formed locale, canonicalized by case without trimming. Headers do not select content; absent/disabled locales give unsupported_locale. */ - locale: string; - /** @description Canonical unpadded base64url v1 seek cursor, bound to host, scope, locale, endpoint and order. Not authority or a snapshot; malformed or mismatched values give validation_failed. */ - lessonCursor?: string; - /** @description Positive ASCII decimal, including leading zeros. Default 20; values above 100 clamp to 100. Zero, signs, whitespace and repeats are refused. */ - lessonLimit?: string; - }; + query?: never; header?: never; path: { - /** @description Lowercase ASCII slug with single interior hyphens; UUID-shaped slugs are refused. */ - slug: string; + /** @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"]; }; - cookie?: never; }; - requestBody?: never; responses: { - /** @description OK */ + /** @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"]["PublicCourseDetail"]; + "application/json": components["schemas"]["DataExportTicketResponse"]; }; }; - /** @description validation_failed or unsupported_locale; bounded localizable field errors where applicable. */ + /** @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"; @@ -3839,7 +7400,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description unauthorized; present invalid or undecidable credentials on a known host. Bare Bearer challenge; no credential or provider details. */ + /** @description unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge. */ 401: { headers: { "Cache-Control": "no-store"; @@ -3850,7 +7411,17 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description not_found for unavailable host or hidden/untranslated/ineligible resource; tenant_mismatch for authenticated host/claim or header disagreement, without disclosure. */ + /** @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. 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 gone (revoked, expired, purged, or sealed under a key the export key ring no longer holds) and only a new export helps; with data_export_ticket_limit, a ticket bound is reached (see the mint's 409). */ 404: { headers: { "Cache-Control": "no-store"; @@ -3860,18 +7431,28 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description method_not_allowed from routing. */ + /** @description method_not_allowed after earlier host, credential and scope gates. */ 405: { headers: { "Cache-Control": "no-store"; - Allow: "GET, HEAD"; + Allow: "POST"; [name: string]: unknown; }; content: { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description payload_too_large; the decoded body bound precedes host classification and authentication. Kestrel framing/backstop refusals may occur outside the application response policy and omit these headers/body. */ + /** @description business_rule_violation. errors.artifact carries data_export_unavailable when the request has no available, unexpired artifact or the key it was sealed under is no longer in the export key ring: the artifact is gone and only a new export helps. It carries data_export_ticket_limit when a ticket bound is reached: this session already holds 3 unconsumed, unexpired tickets over the artifact (wait until one is consumed by its final chunk or expires, 15 minutes after it was minted; a ticket of an earlier, refreshed credential does not count), or 20 tickets have been minted over the artifact in all, which is final: file a new export. */ + 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"; @@ -3881,7 +7462,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description rate_limited from early visitor/peer admission, validated-subject quota or subject-registry capacity. */ + /** @description rate_limited by the existing visitor/subject admission. */ 429: { headers: { "Cache-Control": "no-store"; @@ -3893,7 +7474,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description internal_error from unexpected failures; no exception or query details. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; @@ -3903,12 +7484,10 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description dependency_unavailable from invalid stored public configuration or a sticky subject-registry cleanup fault. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; - /** @description Suggested dependency retry delay in seconds; not a recovery guarantee. */ - "Retry-After": number; [name: string]: unknown; }; content: { @@ -3917,76 +7496,95 @@ export interface operations { }; }; }; - HeadPublicCourse: { + ReadOwnDataExportChunk: { parameters: { - query: { - /** @description Exactly one well-formed locale, canonicalized by case without trimming. Headers do not select content; absent/disabled locales give unsupported_locale. */ - locale: string; - /** @description Canonical unpadded base64url v1 seek cursor, bound to host, scope, locale, endpoint and order. Not authority or a snapshot; malformed or mismatched values give validation_failed. */ - lessonCursor?: string; - /** @description Positive ASCII decimal, including leading zeros. Default 20; values above 100 clamp to 100. Zero, signs, whitespace and repeats are refused. */ - lessonLimit?: string; - }; + query?: never; header?: never; path: { - /** @description Lowercase ASCII slug with single interior hyphens; UUID-shaped slugs are refused. */ - slug: string; + /** @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; + requestBody: { + content: { + "application/json": components["schemas"]["DataExportChunkInput"]; + }; + }; responses: { - /** @description OK */ + /** @description One decrypted chunk: index, count and the base64 of at most 128 KiB of plaintext. 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. */ 200: { headers: { "Cache-Control": "no-store"; [name: string]: unknown; }; - content?: never; + content: { + "application/json": components["schemas"]["DataExportChunkResponse"]; + }; }; - /** @description validation_failed or unsupported_locale; bounded localizable field errors where applicable. */ + /** @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?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description unauthorized; present invalid or undecidable credentials on a known host. Bare Bearer challenge; no credential or provider details. */ + /** @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?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description not_found for unavailable host or hidden/untranslated/ineligible resource; tenant_mismatch for authenticated host/claim or header disagreement, without disclosure. */ + /** @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. 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 gone (revoked, expired, purged, or sealed under a key the export key ring no longer holds) and only a new export helps; with data_export_ticket_limit, a ticket bound is reached (see the mint's 409). */ 404: { headers: { "Cache-Control": "no-store"; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description method_not_allowed from routing. */ + /** @description method_not_allowed after earlier host, credential and scope gates. */ 405: { headers: { "Cache-Control": "no-store"; - Allow: "GET, HEAD"; + Allow: "POST"; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description payload_too_large; the decoded body bound precedes host classification and authentication. Kestrel framing/backstop refusals may occur outside the application response policy and omit these headers/body. */ + /** @description payload_too_large; request bodies are at most 16 KiB. */ 413: { headers: { "Cache-Control"?: "no-store"; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description rate_limited from early visitor/peer admission, validated-subject quota or subject-registry capacity. */ + /** @description rate_limited by the existing visitor/subject admission. */ 429: { headers: { "Cache-Control": "no-store"; @@ -3994,56 +7592,65 @@ export interface operations { "Retry-After": number; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description internal_error from unexpected failures; no exception or query details. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description dependency_unavailable from invalid stored public configuration or a sticky subject-registry cleanup fault. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; - /** @description Suggested dependency retry delay in seconds; not a recovery guarantee. */ - "Retry-After": number; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; }; }; - GetPublicLesson: { + CreateDataExportForSubject: { parameters: { - query: { - /** @description Exactly one well-formed locale, canonicalized by case without trimming. Headers do not select content; absent/disabled locales give unsupported_locale. */ - locale: string; - }; - header?: never; - path: { - /** @description Lowercase ASCII slug with single interior hyphens; UUID-shaped slugs are refused. */ - slug: string; - /** @description Lowercase ASCII slug with single interior hyphens; UUID-shaped slugs are refused. */ - lessonSlug: string; + 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?: never; + requestBody: { + content: { + "application/json": components["schemas"]["DataExportForSubjectInput"]; + }; + }; responses: { - /** @description OK */ - 200: { + /** @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"]["PublicLessonDetail"]; + "application/json": components["schemas"]["DataRequestAcceptedResponse"]; }; }; - /** @description validation_failed or unsupported_locale; bounded localizable field errors where applicable. */ + /** @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"; @@ -4053,7 +7660,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description unauthorized; present invalid or undecidable credentials on a known host. Bare Bearer challenge; no credential or provider details. */ + /** @description unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge. */ 401: { headers: { "Cache-Control": "no-store"; @@ -4064,7 +7671,17 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description not_found for unavailable host or hidden/untranslated/ineligible resource; tenant_mismatch for authenticated host/claim or header disagreement, without disclosure. */ + /** @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"; @@ -4074,18 +7691,28 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description method_not_allowed from routing. */ + /** @description method_not_allowed after earlier host, credential and scope gates. */ 405: { headers: { "Cache-Control": "no-store"; - Allow: "GET, HEAD"; + Allow: "POST"; [name: string]: unknown; }; content: { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description payload_too_large; the decoded body bound precedes host classification and authentication. Kestrel framing/backstop refusals may occur outside the application response policy and omit these headers/body. */ + /** @description business_rule_violation: errors.$ carries lockey_request_already_active (a request of this kind is still active in the group), lockey_blocked_hold, lockey_subject_export_available (the person holds a readable export artifact in the group, of any origin, which this export would revoke: it can be filed once that artifact is revoked or has expired), or lockey_subject_not_admitted (the person's account is closing or closed: nothing is filed); 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"; @@ -4095,7 +7722,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description rate_limited from early visitor/peer admission, validated-subject quota or subject-registry capacity. */ + /** @description rate_limited by the existing visitor/subject admission. */ 429: { headers: { "Cache-Control": "no-store"; @@ -4107,7 +7734,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description internal_error from unexpected failures; no exception or query details. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; @@ -4117,12 +7744,10 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description dependency_unavailable from invalid stored public configuration or a sticky subject-registry cleanup fault. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; - /** @description Suggested dependency retry delay in seconds; not a recovery guarantee. */ - "Retry-After": number; [name: string]: unknown; }; content: { @@ -4131,74 +7756,111 @@ export interface operations { }; }; }; - HeadPublicLesson: { + CreateDataErasureForSubject: { parameters: { - query: { - /** @description Exactly one well-formed locale, canonicalized by case without trimming. Headers do not select content; absent/disabled locales give unsupported_locale. */ - locale: string; - }; - header?: never; - path: { - /** @description Lowercase ASCII slug with single interior hyphens; UUID-shaped slugs are refused. */ - slug: string; - /** @description Lowercase ASCII slug with single interior hyphens; UUID-shaped slugs are refused. */ - lessonSlug: string; + 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?: never; + requestBody: { + content: { + "application/json": components["schemas"]["DataExportForSubjectInput"]; + }; + }; responses: { - /** @description OK */ - 200: { + /** @description Accepted: the request's initial resource, scheduled. Its erasure runs as a background job once its 24-hour cancellable window ends; 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?: never; + content: { + "application/json": components["schemas"]["DataErasureAcceptedResponse"]; + }; }; - /** @description validation_failed or unsupported_locale; bounded localizable field errors where applicable. */ + /** @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?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description unauthorized; present invalid or undecidable credentials on a known host. Bare Bearer challenge; no credential or provider details. */ + /** @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?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description not_found for unavailable host or hidden/untranslated/ineligible resource; tenant_mismatch for authenticated host/claim or header disagreement, without disclosure. */ + /** @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?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description method_not_allowed from routing. */ + /** @description method_not_allowed after earlier host, credential and scope gates. */ 405: { headers: { "Cache-Control": "no-store"; - Allow: "GET, HEAD"; + Allow: "POST"; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description payload_too_large; the decoded body bound precedes host classification and authentication. Kestrel framing/backstop refusals may occur outside the application response policy and omit these headers/body. */ + /** @description business_rule_violation: errors.$ carries lockey_request_already_active (an erasure is still active in the group), lockey_blocked_last_administrator (the person is the tenant's only eligible tenant-wide administrator; another must be appointed first), lockey_blocked_hold, lockey_subject_membership_current (the person still holds an Active or Suspended Membership in the group: revoke it first), or lockey_subject_not_admitted (the person's account is closing or closed: nothing is filed); 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?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description rate_limited from early visitor/peer admission, validated-subject quota or subject-registry capacity. */ + /** @description rate_limited by the existing visitor/subject admission. */ 429: { headers: { "Cache-Control": "no-store"; @@ -4206,48 +7868,57 @@ export interface operations { "Retry-After": number; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description internal_error from unexpected failures; no exception or query details. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description dependency_unavailable from invalid stored public configuration or a sticky subject-registry cleanup fault. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; - /** @description Suggested dependency retry delay in seconds; not a recovery guarantee. */ - "Retry-After": number; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; }; }; - GetPublicSignIn: { + ListDataRequests: { parameters: { - query?: never; + 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; 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. */ + limit?: number; + }; header?: never; path?: never; cookie?: never; }; requestBody?: never; responses: { - /** @description OK */ + /** @description Current receipt-safe projection: status and counts, never content. */ 200: { headers: { "Cache-Control": "no-store"; [name: string]: unknown; }; content: { - "application/json": components["schemas"]["PublicSignIn"]; + "application/json": components["schemas"]["DataRequestPage"]; }; }; - /** @description validation_failed; the sign-in read accepts no query parameters, and malformed or repeated assertion headers are refused. */ + /** @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"; @@ -4257,7 +7928,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description unauthorized; present invalid or undecidable credentials on a known host. Bare Bearer challenge; no credential or provider details. */ + /** @description unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge. */ 401: { headers: { "Cache-Control": "no-store"; @@ -4268,7 +7939,17 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description not_found for unavailable host or hidden/untranslated/ineligible resource; tenant_mismatch for authenticated host/claim or header disagreement, without disclosure. */ + /** @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"; @@ -4278,18 +7959,18 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description method_not_allowed from routing. */ + /** @description method_not_allowed after earlier host, credential and scope gates. */ 405: { headers: { "Cache-Control": "no-store"; - Allow: "GET, HEAD"; + Allow: "GET"; [name: string]: unknown; }; content: { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description payload_too_large; the decoded body bound precedes host classification and authentication. Kestrel framing/backstop refusals may occur outside the application response policy and omit these headers/body. */ + /** @description payload_too_large; request bodies are at most 16 KiB. */ 413: { headers: { "Cache-Control"?: "no-store"; @@ -4299,7 +7980,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description rate_limited from early visitor/peer admission, validated-subject quota or subject-registry capacity. */ + /** @description rate_limited by the existing visitor/subject admission. */ 429: { headers: { "Cache-Control": "no-store"; @@ -4311,7 +7992,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description internal_error from unexpected failures; no exception or query details. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; @@ -4321,12 +8002,10 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description dependency_unavailable from invalid stored public configuration or a sticky subject-registry cleanup fault. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; - /** @description Suggested dependency retry delay in seconds; not a recovery guarantee. */ - "Retry-After": number; [name: string]: unknown; }; content: { @@ -4335,66 +8014,93 @@ export interface operations { }; }; }; - HeadPublicSignIn: { + GetDataRequest: { parameters: { query?: never; header?: never; - path?: 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 OK */ + /** @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?: never; + content: { + "application/json": components["schemas"]["DataRequestResponse"]; + }; }; - /** @description validation_failed; the sign-in read accepts no query parameters, and malformed or repeated assertion headers are refused. */ + /** @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?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description unauthorized; present invalid or undecidable credentials on a known host. Bare Bearer challenge; no credential or provider details. */ + /** @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?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description not_found for unavailable host or hidden/untranslated/ineligible resource; tenant_mismatch for authenticated host/claim or header disagreement, without disclosure. */ + /** @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?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description method_not_allowed from routing. */ + /** @description method_not_allowed after earlier host, credential and scope gates. */ 405: { headers: { "Cache-Control": "no-store"; - Allow: "GET, HEAD"; + Allow: "GET"; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description payload_too_large; the decoded body bound precedes host classification and authentication. Kestrel framing/backstop refusals may occur outside the application response policy and omit these headers/body. */ + /** @description payload_too_large; request bodies are at most 16 KiB. */ 413: { headers: { "Cache-Control"?: "no-store"; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description rate_limited from early visitor/peer admission, validated-subject quota or subject-registry capacity. */ + /** @description rate_limited by the existing visitor/subject admission. */ 429: { headers: { "Cache-Control": "no-store"; @@ -4402,48 +8108,68 @@ export interface operations { "Retry-After": number; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description internal_error from unexpected failures; no exception or query details. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description dependency_unavailable from invalid stored public configuration or a sticky subject-registry cleanup fault. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; - /** @description Suggested dependency retry delay in seconds; not a recovery guarantee. */ - "Retry-After": number; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; }; }; - GetPublicSite: { + CancelDataRequest: { parameters: { query?: never; - header?: never; - path?: 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?: never; + requestBody: { + content: { + "application/json": components["schemas"]["EmptyAdministrationInput"]; + }; + }; responses: { - /** @description OK */ + /** @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"]["PublicSite"]; + "application/json": components["schemas"]["AdministrationVersionReceipt"]; }; }; - /** @description validation_failed; the site bootstrap accepts no query parameters, and malformed or repeated assertion headers are refused. */ + /** @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"; @@ -4453,7 +8179,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description unauthorized; present invalid or undecidable credentials on a known host. Bare Bearer challenge; no credential or provider details. */ + /** @description unauthorized for present invalid, expired or undecidable credentials; bare Bearer challenge. */ 401: { headers: { "Cache-Control": "no-store"; @@ -4464,7 +8190,17 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description not_found for unavailable host or hidden/untranslated/ineligible resource; tenant_mismatch for authenticated host/claim or header disagreement, without disclosure. */ + /** @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"; @@ -4474,18 +8210,28 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description method_not_allowed from routing. */ + /** @description method_not_allowed after earlier host, credential and scope gates. */ 405: { headers: { "Cache-Control": "no-store"; - Allow: "GET, HEAD"; + Allow: "POST"; [name: string]: unknown; }; content: { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description payload_too_large; the decoded body bound precedes host classification and authentication. Kestrel framing/backstop refusals may occur outside the application response policy and omit these headers/body. */ + /** @description concurrency_conflict for a valid stale version; business_rule_violation with errors.$ carrying lockey_data_request_window_ended (an erasure's cancellable window has ended and it runs now) or lockey_data_request_not_cancellable (the request is no longer one a cancellation admits: it already ended, or an export already started); 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"; @@ -4495,7 +8241,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description rate_limited from early visitor/peer admission, validated-subject quota or subject-registry capacity. */ + /** @description rate_limited by the existing visitor/subject admission. */ 429: { headers: { "Cache-Control": "no-store"; @@ -4507,7 +8253,7 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description internal_error from unexpected failures; no exception or query details. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; @@ -4517,12 +8263,10 @@ export interface operations { "application/problem+json": components["schemas"]["ProblemDetails"]; }; }; - /** @description dependency_unavailable from invalid stored public configuration or a sticky subject-registry cleanup fault. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; - /** @description Suggested dependency retry delay in seconds; not a recovery guarantee. */ - "Retry-After": number; [name: string]: unknown; }; content: { @@ -4531,66 +8275,114 @@ export interface operations { }; }; }; - HeadPublicSite: { + RevokeDataExport: { parameters: { query?: never; - header?: never; - path?: 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, not the request's version. Missing, weak, wildcard, list and noncanonical values are 400; a valid stale artifact 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?: never; + requestBody: { + content: { + "application/json": components["schemas"]["EmptyAdministrationInput"]; + }; + }; responses: { - /** @description OK */ + /** @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 (artifact.version), not the request's. */ + ETag: string; + /** @description Present only after fresh original-request disclosure on a replay. */ + "Idempotency-Replayed"?: "true"; [name: string]: unknown; }; - content?: never; + content: { + "application/json": components["schemas"]["AdministrationVersionReceipt"]; + }; }; - /** @description validation_failed; the site bootstrap accepts no query parameters, and malformed or repeated assertion headers are refused. */ + /** @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?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description unauthorized; present invalid or undecidable credentials on a known host. Bare Bearer challenge; no credential or provider details. */ + /** @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?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description not_found for unavailable host or hidden/untranslated/ineligible resource; tenant_mismatch for authenticated host/claim or header disagreement, without disclosure. */ + /** @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?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description method_not_allowed from routing. */ + /** @description method_not_allowed after earlier host, credential and scope gates. */ 405: { headers: { "Cache-Control": "no-store"; - Allow: "GET, HEAD"; + Allow: "POST"; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description payload_too_large; the decoded body bound precedes host classification and authentication. Kestrel framing/backstop refusals may occur outside the application response policy and omit these headers/body. */ + /** @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?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description rate_limited from early visitor/peer admission, validated-subject quota or subject-registry capacity. */ + /** @description rate_limited by the existing visitor/subject admission. */ 429: { headers: { "Cache-Control": "no-store"; @@ -4598,25 +8390,29 @@ export interface operations { "Retry-After": number; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description internal_error from unexpected failures; no exception or query details. */ + /** @description internal_error without provider, query, identity, ticket or submitted-value diagnostics. */ 500: { headers: { "Cache-Control": "no-store"; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; - /** @description dependency_unavailable from invalid stored public configuration or a sticky subject-registry cleanup fault. */ + /** @description dependency_unavailable or audit_unavailable; nothing is disclosed or confirmed without its committed MUST audit row. A write that waits for the tenant's identity fence behind another person's running erasure gives up after two seconds with dependency_unavailable: back off at least 30 seconds (the runtime sends Retry-After: 30 although this contract does not declare the header). */ 503: { headers: { "Cache-Control": "no-store"; - /** @description Suggested dependency retry delay in seconds; not a recovery guarantee. */ - "Retry-After": number; [name: string]: unknown; }; - content?: never; + content: { + "application/problem+json": components["schemas"]["ProblemDetails"]; + }; }; }; }; diff --git a/frontend/scripts/public-runtime-control.test.mjs b/frontend/scripts/public-runtime-control.test.mjs index a53998cc9..8687d34ce 100644 --- a/frontend/scripts/public-runtime-control.test.mjs +++ b/frontend/scripts/public-runtime-control.test.mjs @@ -205,7 +205,7 @@ async function fixture(options = {}) { export const loadLocalEnvironment = () => ({}); export const publicServerConfiguration = () => ({certificate: ${JSON.stringify(join(credentials, 'certificate.pem'))}, privateKey: ${JSON.stringify(join(credentials, 'key.pem'))}}); export const admitIncomingRequest = () => { state.event('incoming-admission'); return true; }; - export const verifyProvenance = () => { state.event('provenance'); return {method: 'GET', target: '/', host: 'fixture.invalid'}; }; + export const verifyProvenance = () => { state.event('provenance'); return {method: 'GET', target: state.options.target ?? '/', host: 'fixture.invalid'}; }; export const refuseIngress = (response) => { response.writeHead(503); response.end(); }; `, 'admission.mjs': ` @@ -216,16 +216,28 @@ async function fixture(options = {}) { } `, 'dependencies.mjs': ` + import { state } from './state.mjs'; export const createTenantProvider = () => ({}); export const createAccountSiteCaller = () => ({}); export const createNativeSessionApi = () => ({}); export const createNativeAdministrationCaller = () => ({}); export const createNativeRetainedConsentCaller = () => ({}); + export const createNativeRetainedDataRequestCaller = () => ({}); export const createNativeInvitationApi = () => ({}); export const createNativeFederationTestApi = () => ({}); export const createPublicSignInReader = () => async () => null; export const nativeInvitationTarget = () => false; export const nativeConsentTarget = () => false; + export const nativeDataRequestTarget = (target) => target.split('?', 1)[0] === '/account/data'; + export function createNativeDataRequestHandler({catalogues, store, responseLease}) { + if (catalogues?.en?.fixture !== 'en' || catalogues?.tr?.fixture !== 'tr' + || !store || typeof responseLease !== 'function') throw new Error('Fixture data request wiring failed'); + return (binding, _request, response) => { + state.event('data-request-handler'); + state.dataRequestTargets = [...(state.dataRequestTargets ?? []), binding.target]; + response.end('data-request-control'); + }; + } export function createNativeConsentHandler({catalogues, store, responseLease}) { if (catalogues?.en?.fixture !== 'en' || catalogues?.tr?.fixture !== 'tr' || !store || typeof responseLease !== 'function') throw new Error('Fixture consent wiring failed'); @@ -242,13 +254,15 @@ async function fixture(options = {}) { `, 'invitation-en.json': JSON.stringify({ fixture: 'en' }), 'invitation-tr.json': JSON.stringify({ fixture: 'tr' }), + 'data-en.json': JSON.stringify({ fixture: 'en' }), + 'data-tr.json': JSON.stringify({ fixture: 'tr' }), 'auth-en.json': JSON.stringify({ consents: { fixture: 'en' } }), 'auth-tr.json': JSON.stringify({ consents: { fixture: 'tr' } }), 'requests.mjs': ` import { state } from './state.mjs'; export function installBffRequestRuntime() { state.event('requests-created'); - return {preparation: {}, nativeResponse() { throw new Error('Unused fixture response lease'); }, nativeConsentResponse() { throw new Error('Unused fixture consent response lease'); }, run(_binding, _request, _response, work) { return work(); }, async stop() { state.event('requests-stop'); if (state.options.holdRequests) await state.requestsGate.promise; state.event('requests-joined'); }}; + return {preparation: {}, nativeResponse() { throw new Error('Unused fixture response lease'); }, nativeConsentResponse() { throw new Error('Unused fixture consent response lease'); }, nativeDataRequestResponse() { throw new Error('Unused fixture data request response lease'); }, run(_binding, _request, _response, work) { return work(); }, async stop() { state.event('requests-stop'); if (state.options.holdRequests) await state.requestsGate.promise; state.event('requests-joined'); }}; } `, 'sessions.mjs': ` @@ -329,6 +343,9 @@ async function fixture(options = {}) { ['../.server/auth/native-invitation-client.js', './dependencies.mjs'], ['../.server/auth/native-invitation-http.js', './dependencies.mjs'], ['../.server/auth/native-consent-http.js', './dependencies.mjs'], + ['../.server/auth/native-data-request-http.js', './dependencies.mjs'], + ['../src/i18n/messages/en/data.json', './data-en.json'], + ['../src/i18n/messages/tr/data.json', './data-tr.json'], ['../.server/auth/native-federation-client.js', './dependencies.mjs'], ['../.server/auth/invitation-html.js', './dependencies.mjs'], ['../src/i18n/messages/en/invitation.json', './invitation-en.json'], @@ -641,6 +658,51 @@ try { assert.equal(healthy.state.events.filter((event) => event === 'server-close').length, 1); assert.equal(healthy.state.events.includes('sink-close'), false); + // The data-request document is dispatched to its own handler, in a BFF runtime only, before Next sees it. + const fetchBody = (port) => + new Promise((resolve, reject) => { + const outgoing = request( + { host: '127.0.0.1', port, rejectUnauthorized: false, agent: false }, + (response) => { + let text = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { + text += chunk; + }); + response.on('end', () => resolve(text)); + }, + ); + outgoing.on('error', reject); + outgoing.end(); + }); + for (const [target, handled] of [ + ['/account/data', true], + ['/account/data?group=tenant&result=export', true], + ['/account/database', false], + ['/account', false], + ['/', false], + ]) { + const dispatching = await fixture({ bff: true, target }); + await dispatching.start(); + assert.equal( + await fetchBody(dispatching.port), + handled ? 'data-request-control' : 'native-control', + target, + ); + const count = (event) => dispatching.state.events.filter((value) => value === event).length; + assert.equal(count('data-request-handler'), handled ? 1 : 0, target); + assert.equal(count('next-request'), handled ? 0 : 1, target); + assert.deepEqual(dispatching.state.dataRequestTargets ?? [], handled ? [target] : [], target); + await dispatching.stop(); + } + // Without the BFF there is no data-request handler: the same target belongs to Next. + const withoutBff = await fixture({ target: '/account/data' }); + await withoutBff.start(); + assert.equal(await fetchBody(withoutBff.port), 'native-control'); + assert.equal(withoutBff.state.events.includes('data-request-handler'), false); + assert.equal(withoutBff.state.events.includes('next-request'), true); + await withoutBff.stop(); + const upgraded = await fixture({ development: true, holdUpgrade: true }); await upgraded.start(); const peer = connect({ host: '127.0.0.1', port: upgraded.port, rejectUnauthorized: false }); diff --git a/infra/compose/README.md b/infra/compose/README.md index 3863d8b80..87189361b 100644 --- a/infra/compose/README.md +++ b/infra/compose/README.md @@ -10,11 +10,15 @@ eventing → secrets → Dapr sidecar → gateway). Bring it up with `make dev` from the repo root (the orchestrator copies `.env.example` → a private `.env` on first run). Before starting Keycloak, -prepare `KEYCLOAK_WEB_CLIENT_SECRET` and `KEYCLOAK_FEDERATION_ADMIN_SECRET` in that +prepare `KEYCLOAK_WEB_CLIENT_SECRET`, `KEYCLOAK_FEDERATION_ADMIN_SECRET` and +`KEYCLOAK_ACCOUNT_REMOVAL_SECRET` in that selected private source; Compose refuses a missing value instead of importing a published fallback. The federation secret is the [confined federation admin client](../keycloak/README.md#federation-administration-client)'s -(ADR-0099); the API reads the same value as `Federation__ClientSecret`. Preserve an +(ADR-0099); the API reads the same value as `Federation__ClientSecret`. The account +removal secret is the +[confined account-removal client](../keycloak/README.md#account-removal-client)'s +(ADR-0107); the API reads the same value as `AccountRemoval__ClientSecret`. Preserve an existing confidential secret and follow the [recovery procedure](../keycloak/README.md#secret-continuity-and-recovery) on mismatch. Existing file permissions require explicit operator correction. diff --git a/infra/compose/dev.yml b/infra/compose/dev.yml index a6be328d6..2534f2961 100644 --- a/infra/compose/dev.yml +++ b/infra/compose/dev.yml @@ -230,6 +230,8 @@ services: KEYCLOAK_WEB_CLIENT_SECRET: ${KEYCLOAK_WEB_CLIENT_SECRET:?Add the retained confidential web client secret to the selected private environment} # ADR-0099: the confined federation admin client (manage-identity-providers only). Retained like the web secret. KEYCLOAK_FEDERATION_ADMIN_SECRET: ${KEYCLOAK_FEDERATION_ADMIN_SECRET:?Add the retained federation admin client secret to the selected private environment} + # ADR-0107 section 7: the confined account-removal client (manage-users only). Retained like the web secret. + KEYCLOAK_ACCOUNT_REMOVAL_SECRET: ${KEYCLOAK_ACCOUNT_REMOVAL_SECRET:?Add the retained account removal client secret to the selected private environment} KC_DB: postgres KC_DB_URL: jdbc:postgresql://postgres:5432/keycloak KC_DB_USERNAME: ${POSTGRES_USER:-learnstack} diff --git a/infra/keycloak/README.md b/infra/keycloak/README.md index 3d76c3011..a9631c0c2 100644 --- a/infra/keycloak/README.md +++ b/infra/keycloak/README.md @@ -185,7 +185,7 @@ manual ledger deletion, history reset, reduced retention or tenant-copy purge. | Realm | Population | Clients | |-------|------------|---------| -| `learnstack` | Tenant users; four declared development accounts | `learnstack-web`: confidential code/S256 BFF; `learnstack-api`: resource and legacy service account; `learnstack-event-reader`: confined history reader; `learnstack-federation-admin`: confined federation adapter ([below](#federation-administration-client)); `account` and `account-console`: retired, disabled | +| `learnstack` | Tenant users; four declared development accounts | `learnstack-web`: confidential code/S256 BFF; `learnstack-api`: resource and legacy service account; `learnstack-event-reader`: confined history reader; `learnstack-federation-admin`: confined federation adapter ([below](#federation-administration-client)); `learnstack-account-removal`: confined closure account deletion ([below](#account-removal-client)); `account` and `account-console`: retired, disabled | | `learnstack-hub` | Platform operators | `learnstack-hub-web`: public PKCE, the portal's; `learnstack-operator`: public PKCE for LearnStack's platform surface, audience `learnstack-platform`, 15-minute access tokens, MFA step-up | The `learnstack-hub` realm's browser flow is `browser-loa`: password at level 1, a @@ -939,6 +939,52 @@ refuses; enter its ASCII (punycode) form Keycloak's own later calls to the configured token and JWKS endpoints follow DNS; production egress policy for the Keycloak process belongs to Phase 11. +## Account removal client + +[ADR-0107 § 7](../../docs/decisions/0107-data-request-fulfillment-and-account-closure.md) +adds `learnstack-account-removal`, the confidential service client the API's confined +account-removal adapter alone uses, and only in the last step of a global account +closure. It has the same shape as the +[federation administration client](#federation-administration-client): no browser, +password, implicit or full-scope flow, no default or optional client scopes, one local +mapper that emits only `realm-management` roles into access tokens, and exactly the +`realm-management/manage-users` role as its role and scope binding. The pinned +provider's automatic `service_account` scope, default realm-role assignment and +default-group memberships are removed from a newly created client only. + +**That role is realm-wide and is not only deletion.** `manage-users` can create and +update users, set their attributes and required actions, and reset their credentials, +in the one realm every tenant shares. A leaked secret therefore reaches every tenant's +users. The adapter confines what LearnStack sends (one DELETE of one validated user +identifier), not what the credential could do. The +[runbook](../../docs/runbooks/account-removal-client.md) owns the blast radius, +rotation and leak response. + +- **Secret.** The export carries only the placeholder + `${KEYCLOAK_ACCOUNT_REMOVAL_SECRET}`. Compose requires the variable (`:?`), and the + selected private environment must declare `KEYCLOAK_ACCOUNT_REMOVAL_SECRET` exactly + once: 16 to 1,024 bytes, not the provider's mask literal `**********`, not beginning + `${`, and distinct from the web, admin, event-reader and federation admin secrets. + Reconciliation refuses with `missing_account_removal_secret` when it is absent. + An existing private `.env` must add it before `make dev` will start: compose's `:?` + guard stops the provider without it. It should also add the same value as + `AccountRemoval__ClientSecret`; nothing stops `make dev` without it, but the API then + keeps the refusing default and refuses every first Begin of a closure. Reconciliation + refuses a different value. +- **API.** The API reads the same value as `AccountRemoval__ClientSecret`. When the + private file declares both, they must be identical. Without the API value the port + keeps its fail-closed default and refuses every call; nothing reaches the provider. + The managed launcher behind `make public-api` and `make demo` hands the API a closed + inventory that carries no `AccountRemoval__*`, so under it no closure can begin; + the real-provider proof runs against the test fixtures. +- **Continuity.** Reconciliation creates the client on a realm that lacks it and + verifies an existing one exactly. An existing secret that differs refuses with + `secret_conflict`; an extra role, scope, mapper or flow refuses too. Nothing is + rotated, repaired or deleted. A partial client left by a fault is deleted by hand + in the Admin Console and recreated by the next run, as for the federation client. +- **Token.** The adapter refuses any token that is not from this client, this realm + and exactly `manage-users`, before any Admin call. + ## What does not live here - Production realm configuration: Phase 11 provisioning owns it; these JSONs are diff --git a/infra/keycloak/realms/learnstack.json b/infra/keycloak/realms/learnstack.json index adf894f71..715543f4a 100644 --- a/infra/keycloak/realms/learnstack.json +++ b/infra/keycloak/realms/learnstack.json @@ -385,6 +385,47 @@ } ] }, + { + "clientId": "learnstack-account-removal", + "name": "LearnStack account removal (confidential service)", + "description": "API-only machine client for the closure's account deletion (ADR-0107 section 7). manage-users only. See infra/keycloak/README.md.", + "enabled": true, + "publicClient": false, + "bearerOnly": false, + "clientAuthenticatorType": "client-secret", + "secret": "${KEYCLOAK_ACCOUNT_REMOVAL_SECRET}", + "standardFlowEnabled": false, + "implicitFlowEnabled": false, + "directAccessGrantsEnabled": false, + "serviceAccountsEnabled": true, + "consentRequired": false, + "frontchannelLogout": false, + "fullScopeAllowed": false, + "redirectUris": [], + "webOrigins": [], + "protocol": "openid-connect", + "attributes": {}, + "defaultClientScopes": [], + "optionalClientScopes": [], + "protocolMappers": [ + { + "name": "learnstack-account-removal-roles", + "protocol": "openid-connect", + "protocolMapper": "oidc-usermodel-client-role-mapper", + "consentRequired": false, + "config": { + "usermodel.clientRoleMapping.clientId": "realm-management", + "claim.name": "resource_access.realm-management.roles", + "jsonType.label": "String", + "multivalued": "true", + "access.token.claim": "true", + "id.token.claim": "false", + "userinfo.token.claim": "false", + "introspection.token.claim": "false" + } + } + ] + }, { "clientId": "account", "name": "${client_account}", @@ -587,6 +628,16 @@ "manage-identity-providers" ] } + }, + { + "username": "service-account-learnstack-account-removal", + "enabled": true, + "serviceAccountClientId": "learnstack-account-removal", + "clientRoles": { + "realm-management": [ + "manage-users" + ] + } } ], "smtpServer": { @@ -1403,6 +1454,12 @@ "roles": [ "manage-identity-providers" ] + }, + { + "client": "learnstack-account-removal", + "roles": [ + "manage-users" + ] } ] }, diff --git a/scripts/ci-test-shards-plan.json b/scripts/ci-test-shards-plan.json index 8aae8089d..349665f93 100644 --- a/scripts/ci-test-shards-plan.json +++ b/scripts/ci-test-shards-plan.json @@ -33,12 +33,18 @@ "LearnStack.Tests.Integration.AuthorityCeilingHttpTests", "LearnStack.Tests.Integration.CompositionRootCatalogueTests", "LearnStack.Tests.Integration.CrossCuttingFoundationHttpTests", + "LearnStack.Tests.Integration.Database.AccountClosureAdministratorParityTests", + "LearnStack.Tests.Integration.Database.AccountClosureBeginTests", + "LearnStack.Tests.Integration.Database.AccountClosureEndToEndTests", + "LearnStack.Tests.Integration.Database.AccountClosureFinalizeTests", + "LearnStack.Tests.Integration.Database.AccountClosureStorageTests", "LearnStack.Tests.Integration.Database.AccountSiteHttpTests", "LearnStack.Tests.Integration.Database.AccountSiteQueryTests", "LearnStack.Tests.Integration.Database.AmbientUnitOfWorkTests", "LearnStack.Tests.Integration.Database.AuditCaptureWiringTests", "LearnStack.Tests.Integration.Database.AuditConfigServiceTests", "LearnStack.Tests.Integration.Database.AuditPipelineTests", + "LearnStack.Tests.Integration.Database.AuditRedactionCanaryTests", "LearnStack.Tests.Integration.Database.AuditSchemaTests", "LearnStack.Tests.Integration.Database.AuditStoreTests", "LearnStack.Tests.Integration.Database.AuditWorkflowTests", @@ -64,6 +70,8 @@ "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests", "LearnStack.Tests.Integration.Database.BackgroundJobSubmissionTests", "LearnStack.Tests.Integration.Database.BoundedAdministrationHttpTests", + "LearnStack.Tests.Integration.Database.ClosureAuditRedactionTests", + "LearnStack.Tests.Integration.Database.ClosureFanOutTests", "LearnStack.Tests.Integration.Database.ConsentSubjectCapturedOwnerTests", "LearnStack.Tests.Integration.Database.ConsentSubjectPipelineAuditTests", "LearnStack.Tests.Integration.Database.CourseContentAccessMigrationTests", @@ -79,6 +87,17 @@ "LearnStack.Tests.Integration.Database.CustomizationProjectionTests", "LearnStack.Tests.Integration.Database.CustomizationPublicationConcurrencyTests", "LearnStack.Tests.Integration.Database.CustomizationSchemaTests", + "LearnStack.Tests.Integration.Database.DataErasureExecutionTests", + "LearnStack.Tests.Integration.Database.DataErasureGuardTests", + "LearnStack.Tests.Integration.Database.DataErasureReplayFloorTests", + "LearnStack.Tests.Integration.Database.DataExportArtifactStoreTests", + "LearnStack.Tests.Integration.Database.DataExportExecutionTests", + "LearnStack.Tests.Integration.Database.DataExportParticipantTests", + "LearnStack.Tests.Integration.Database.DataRequestHttpTests", + "LearnStack.Tests.Integration.Database.DataRequestOperatorOperationsTests", + "LearnStack.Tests.Integration.Database.DataRequestServiceStorageTests", + "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", @@ -122,6 +141,7 @@ "LearnStack.Tests.Integration.Database.IdentityOwnNavigationTests", "LearnStack.Tests.Integration.Database.IdentityReadDiagnosticSinkTests", "LearnStack.Tests.Integration.Database.IdentityRebindAuditStoreTests", + "LearnStack.Tests.Integration.Database.IdentityScopeLifecyclePlatformTests", "LearnStack.Tests.Integration.Database.IdentityScopeLifecycleTests", "LearnStack.Tests.Integration.Database.IdentitySeederTests", "LearnStack.Tests.Integration.Database.IdentitySelfDiscoveryOwnerTests", @@ -158,6 +178,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", @@ -219,6 +240,7 @@ "LearnStack.Tests.Integration.RateLimitForwardedForTests", "LearnStack.Tests.Integration.RateLimitingHttpTests", "LearnStack.Tests.Integration.SmokeTests", + "LearnStack.Tests.Integration.TenancyIdentity.AccountRemovalProviderTests", "LearnStack.Tests.Integration.TenancyIdentity.FederationProviderTests", "LearnStack.Tests.Integration.TenancyIdentity.ProviderEventAdapterTests", "LearnStack.Tests.Integration.TenancyIdentity.TenantBffSessionTests", diff --git a/scripts/compose.mjs b/scripts/compose.mjs index 06aba197b..827cfd539 100644 --- a/scripts/compose.mjs +++ b/scripts/compose.mjs @@ -130,6 +130,7 @@ export function composeSelection(mode, environment = process.env, root = reposit if (lifecycleOnly(commandArgs)) { env.KEYCLOAK_WEB_CLIENT_SECRET = 'learnstack-lifecycle-placeholder'; env.KEYCLOAK_FEDERATION_ADMIN_SECRET = 'learnstack-lifecycle-placeholder'; + env.KEYCLOAK_ACCOUNT_REMOVAL_SECRET = 'learnstack-lifecycle-placeholder'; } const files = [resolve(root, 'infra/compose/dev.yml')]; if (mode === 'e2e') files.push(resolve(root, 'infra/compose/e2e.yml')); diff --git a/scripts/demo.mjs b/scripts/demo.mjs index 55bc81da1..ea5130619 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/development-event-reader-test-fixture.mjs b/scripts/development-event-reader-test-fixture.mjs index ef0d2bc66..d2a1e84db 100644 --- a/scripts/development-event-reader-test-fixture.mjs +++ b/scripts/development-event-reader-test-fixture.mjs @@ -19,12 +19,26 @@ export function providerWithoutFederationAdmin() { return providerWithServiceClient(fixture, 'learnstack-federation-admin', 'manage-identity-providers'); } +/** + * A warm realm without ADR-0107's account-removal client: the committed import's client and its + * service account are removed, so reconciliation must create them. + */ +export function providerWithoutAccountRemoval() { + const fixture = provider(); + const { state } = fixture; + state.clients = state.clients.filter(client => client.clientId !== 'learnstack-account-removal'); + state.accountRemoval.client = { id: 'retired-account-removal-client' }; + state.accountRemoval.user = { id: 'retired-account-removal-user' }; + return providerWithServiceClient(fixture, 'learnstack-account-removal', 'manage-users'); +} + function providerWithServiceClient(fixture, name, roleName) { const { state, reads, writes } = fixture; const original = fixture.admin; // One realm-management client, shared with the committed import's federation admin client. const management = state.federation.management; const role = roleName === 'manage-identity-providers' ? state.federation.role + : roleName === 'manage-users' ? state.accountRemoval.role : { id: 'owned-view-events-role', containerId: management.id, clientRole: true, composite: false, name: roleName }; let reader; let user; diff --git a/scripts/development-event-reader.mjs b/scripts/development-event-reader.mjs index 14509e165..361d0ea62 100644 --- a/scripts/development-event-reader.mjs +++ b/scripts/development-event-reader.mjs @@ -22,6 +22,8 @@ function serviceClient(name, role, mapperName) { export const eventReaderClient = serviceClient('learnstack-event-reader', 'view-events', 'learnstack-event-reader-roles'); export const federationAdminClient = serviceClient('learnstack-federation-admin', 'manage-identity-providers', 'learnstack-federation-admin-roles'); +export const accountRemovalClient = serviceClient('learnstack-account-removal', 'manage-users', + 'learnstack-account-removal-roles'); const list = value => { if (!Array.isArray(value) || value.length > 256) refuse('plan', 'unsupported'); return value; }; const plain = value => Object.fromEntries(Object.entries(value).filter(([key]) => key !== 'id')); const sameRole = (a, b) => a.id === b.id && a.name === b.name && a.containerId === b.containerId && a.clientRole === true; @@ -43,6 +45,11 @@ export function planFederationAdmin(admin, secret) { return planServiceClient(admin, secret, federationAdminClient); } +/** ADR-0107 section 7's account-removal client: manage-users only, the same refusal rules. */ +export function planAccountRemoval(admin, secret) { + return planServiceClient(admin, secret, accountRemovalClient); +} + async function planServiceClient(admin, secret, { name, role: roleName, mapper, fields }) { if (typeof secret !== 'string' || secret.length < 16 || /[\r\n]/.test(secret)) refuse('plan', 'configuration'); const management = list(await admin.get('clients?clientId=realm-management&max=2')); diff --git a/scripts/development-realm-account-removal.test.mjs b/scripts/development-realm-account-removal.test.mjs new file mode 100644 index 000000000..d8c3702cf --- /dev/null +++ b/scripts/development-realm-account-removal.test.mjs @@ -0,0 +1,113 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { planAccountRemoval, planFederationAdmin, accountRemovalClient, federationAdminClient } from './development-event-reader.mjs'; +import { reconcileRealm } from './development-realm-core.mjs'; +import { desired, manifest, secret, federationSecret, accountRemovalSecret, provider, providerTransport } from './development-realm-test-fixture.mjs'; +import { providerWithoutAccountRemoval } from './development-event-reader-test-fixture.mjs'; + +const clone = value => structuredClone(value); +const refusal = (stage, reason) => error => error.stage === stage && error.reason === reason; +const input = (transport, extra = {}) => ({ baseUrl: 'http://localhost:8080/', expectedIssuer: 'http://localhost:8080/realms/learnstack', + adminUsername: 'fixture-admin', adminPassword: 'fixture-password', webSecret: secret, manifest: clone(manifest), desired: clone(desired), + transport, ...extra }); + +// ADR-0107 section 7: the closure's account-removal client holds manage-users alone, confined like the federation client. + +test('the committed import declares the account-removal client with manage-users alone and a placeholder secret', () => { + const client = desired.clients.find(value => value.clientId === 'learnstack-account-removal'); + assert.equal(client.secret, '${KEYCLOAK_ACCOUNT_REMOVAL_SECRET}'); + assert.deepEqual(Object.entries(accountRemovalClient.fields).filter(([key, value]) => client[key] !== value + && JSON.stringify(client[key]) !== JSON.stringify(value)), [], 'every declared field the planner verifies matches the export'); + assert.deepEqual(client.protocolMappers.map(mapper => mapper.name), ['learnstack-account-removal-roles']); + const account = desired.users.find(user => user.serviceAccountClientId === 'learnstack-account-removal'); + assert.deepEqual(account.clientRoles, { 'realm-management': ['manage-users'] }); + assert.deepEqual(desired.clientScopeMappings['realm-management'].find(entry => entry.client === 'learnstack-account-removal').roles, ['manage-users']); + assert.equal(accountRemovalClient.role, 'manage-users'); + assert.notEqual(accountRemovalClient.role, federationAdminClient.role); +}); + +test('the committed import already carries the client and plans no write', async () => { + const fixture = provider(); + const plan = await planAccountRemoval(fixture.admin, accountRemovalSecret); + assert.equal(plan.changed, false); + await plan.verify(); + assert.deepEqual(fixture.writes, []); + // The three machine clients are planned independently: the federation plan is unchanged. + assert.equal((await planFederationAdmin(fixture.admin, federationSecret)).changed, false); +}); + +test('the account-removal client is created with only manage-users on a warm realm and then verifies', async () => { + const fixture = providerWithoutAccountRemoval(); + const plan = await planAccountRemoval(fixture.admin, accountRemovalSecret); + assert.equal(plan.changed, true); + assert.deepEqual(fixture.writes, [], 'planning is read only'); + await plan.apply(); + await plan.verify(); + const grant = fixture.writes.filter(write => write.path.includes('role-mappings/clients') || write.path.includes('scope-mappings')); + assert.deepEqual(grant.map(write => write.body.map(role => role.name)), [['manage-users'], ['manage-users']]); + const created = fixture.writes.find(write => write.path === 'clients'); + assert.equal(created.body.secret, accountRemovalSecret); + assert.equal(created.body.clientId, 'learnstack-account-removal'); + assert.equal(created.body.serviceAccountsEnabled, true); + assert.equal(created.body.fullScopeAllowed, false); + assert.equal(created.body.standardFlowEnabled, false); + assert.deepEqual(created.body.protocolMappers.map(mapper => mapper.name), ['learnstack-account-removal-roles']); + assert.equal((await planAccountRemoval(fixture.admin, accountRemovalSecret)).changed, false); +}); + +test('the full core creates the client, verifies it and makes the next pass zero-write', async () => { + const fixture = providerWithoutAccountRemoval(); + const recording = providerTransport(fixture); + const first = await reconcileRealm(input(recording.transport, { federationSecret, accountRemovalSecret })); + assert.ok(first.mutations > 0); + const created = fixture.state.clients.find(client => client.clientId === 'learnstack-account-removal'); + assert.equal(created.secret, accountRemovalSecret); + assert.deepEqual(created.protocolMappers.map(mapper => mapper.name), ['learnstack-account-removal-roles']); + assert.deepEqual(await reconcileRealm(input(recording.transport, { federationSecret, accountRemovalSecret })), { mutations: 0 }); +}); + +test('without a secret the core plans no account-removal client at all, which is how a federation-only caller runs', async () => { + const fixture = providerWithoutAccountRemoval(); + const recording = providerTransport(fixture); + await reconcileRealm(input(recording.transport, { federationSecret })); + assert.ok(!fixture.state.clients.some(client => client.clientId === 'learnstack-account-removal')); +}); + +for (const [name, mutate, reason] of [ + ['a different secret', fixture => { fixture.state.accountRemoval.client.secret = 'another-removal-secret-value'; }, 'secret_conflict'], + ['full scope', fixture => { fixture.state.accountRemoval.client.fullScopeAllowed = true; }, 'readback_conflict'], + ['a browser flow', fixture => { fixture.state.accountRemoval.client.standardFlowEnabled = true; }, 'readback_conflict'], + ['direct grants', fixture => { fixture.state.accountRemoval.client.directAccessGrantsEnabled = true; }, 'readback_conflict'], + ['a public client', fixture => { fixture.state.accountRemoval.client.publicClient = true; }, 'readback_conflict'], + ['an extra mapper', fixture => { fixture.state.accountRemoval.client.protocolMappers.push({ ...fixture.state.accountRemoval.client.protocolMappers[0], + id: 'extra', name: 'extra' }); }, 'mapper_conflict'], + ['the federation role as a second grant', fixture => { fixture.state.accountRemoval.user.roles.clientMappings['realm-management'].mappings.push({ + ...fixture.state.federation.role }); }, 'unsupported'], + ['a realm grant', fixture => { fixture.state.accountRemoval.user.roles.realmMappings = [{ name: 'admin' }]; }, 'unsupported'], + ['a group membership', fixture => { + const get = fixture.admin.get; + fixture.admin.get = async path => path === `users/${fixture.state.accountRemoval.user.id}/groups?first=0&max=1` + ? [{ id: 'g', name: 'g' }] : get(path); + }, 'unsupported'], +]) test(`an existing account-removal client with ${name} refuses without a repair write`, async () => { + const fixture = provider(); + mutate(fixture); + await assert.rejects(planAccountRemoval(fixture.admin, accountRemovalSecret), refusal('plan', reason)); + assert.deepEqual(fixture.writes, []); +}); + +test('the federation client holding manage-users refuses, so neither client can drift into the other', async () => { + const fixture = provider(); + fixture.state.federation.user.roles.clientMappings['realm-management'].mappings.push({ ...fixture.state.accountRemoval.role }); + await assert.rejects(planFederationAdmin(fixture.admin, federationSecret), refusal('plan', 'unsupported')); + assert.deepEqual(fixture.writes, []); +}); + +for (const bad of [undefined, null, '', 'short', 'a-secret\nwith-a-newline-0123456789']) { + test(`an unusable account-removal secret ${JSON.stringify(bad)} refuses before any read of the client`, async () => { + const fixture = provider(); + await assert.rejects(planAccountRemoval(fixture.admin, bad), refusal('plan', 'configuration')); + assert.deepEqual(fixture.reads.filter(path => path.includes('learnstack-account-removal')), []); + assert.deepEqual(fixture.writes, []); + }); +} diff --git a/scripts/development-realm-core.mjs b/scripts/development-realm-core.mjs index 05faa9644..6348fc633 100644 --- a/scripts/development-realm-core.mjs +++ b/scripts/development-realm-core.mjs @@ -1,7 +1,7 @@ import { buildRealmPlan, buildRealmPreparation, nativeWebScopeDetachmentPath } from './development-realm-plan.mjs'; import { realmJson, realmRequest } from './development-realm-http.mjs'; import { RealmError, refuse } from './development-realm-errors.mjs'; -import { planEventReader, planFederationAdmin, eventReaderDefaultRoleDetachment } from './development-event-reader.mjs'; +import { planEventReader, planFederationAdmin, planAccountRemoval, eventReaderDefaultRoleDetachment } from './development-event-reader.mjs'; import { planFederationRealm } from './development-realm-federation.mjs'; import { accountRetirementDetachment } from './development-realm-account.mjs'; @@ -9,7 +9,7 @@ export const realmPassMilliseconds = 120000; /** Internal core for the owned launcher and isolated provider tests; no CLI overrides. */ export async function reconcileRealm({ baseUrl, expectedIssuer, adminUsername, adminPassword, - webSecret, eventReaderSecret, federationSecret, manifest, desired, backchannel, signal, ca, transport = realmRequest, afterVerified }) { + webSecret, eventReaderSecret, federationSecret, accountRemovalSecret, manifest, desired, backchannel, signal, ca, transport = realmRequest, afterVerified }) { let base; try { base = new URL(baseUrl); } catch { refuse('preflight', 'configuration'); } @@ -132,6 +132,8 @@ export async function reconcileRealm({ baseUrl, expectedIssuer, adminUsername, a // ADR-0099 realm invariants and the federation admin client: read-only plans, completed // before the first ordinary write and applied after the main plan's own readback. const federationAdmin = federationSecret === undefined ? null : await planFederationAdmin(admin, federationSecret); + // ADR-0107 section 7: the closure's account-removal client, planned and applied the same way. + const accountRemoval = accountRemovalSecret === undefined ? null : await planAccountRemoval(admin, accountRemovalSecret); const federation = await planFederationRealm(admin, desired); stage = 'apply'; for (const action of plan.actions) { @@ -140,7 +142,7 @@ export async function reconcileRealm({ baseUrl, expectedIssuer, adminUsername, a } stage = 'readback'; await plan.verify(); - for (const owned of [reader, federationAdmin, federation]) { + for (const owned of [reader, federationAdmin, accountRemoval, federation]) { if (!owned) continue; stage = 'apply'; await owned.apply(); @@ -151,7 +153,8 @@ export async function reconcileRealm({ baseUrl, expectedIssuer, adminUsername, a if (remaining.actions.length !== 0) refuse(stage, 'readback_conflict'); stage = 'readback'; if ((await planFederationRealm(admin, desired)).changed - || federationSecret !== undefined && (await planFederationAdmin(admin, federationSecret)).changed) + || federationSecret !== undefined && (await planFederationAdmin(admin, federationSecret)).changed + || accountRemovalSecret !== undefined && (await planAccountRemoval(admin, accountRemovalSecret)).changed) refuse(stage, 'readback_conflict'); if (afterVerified) { stage = 'identity'; diff --git a/scripts/development-realm-errors.mjs b/scripts/development-realm-errors.mjs index 57176f285..a647888e1 100644 --- a/scripts/development-realm-errors.mjs +++ b/scripts/development-realm-errors.mjs @@ -7,7 +7,7 @@ const reasons = new Set([ 'unsupported', 'response', 'status', 'redirect', 'deadline', 'cancelled', 'transport', 'lock_busy', 'body_limit', 'readback_conflict', 'cleanup', 'missing_web_secret', 'private_file', 'event_policy_conflict', 'seed_refused', - 'backchannel_configuration', 'backchannel_conflict', 'missing_federation_secret', 'flow_conflict', + 'backchannel_configuration', 'backchannel_conflict', 'missing_federation_secret', 'missing_account_removal_secret', 'flow_conflict', ]); /** Neither upstream objects nor arbitrary caller text can become a diagnostic. */ @@ -40,6 +40,8 @@ export function realmFailureNotice(error) { message += '\nrealm: add KEYCLOAK_WEB_CLIENT_SECRET explicitly to the selected private file; see infra/keycloak/README.md'; else if (error.reason === 'missing_federation_secret') message += '\nrealm: add KEYCLOAK_FEDERATION_ADMIN_SECRET explicitly to the selected private file; see infra/keycloak/README.md#federation-administration-client'; + else if (error.reason === 'missing_account_removal_secret') + message += '\nrealm: add KEYCLOAK_ACCOUNT_REMOVAL_SECRET explicitly to the selected private file; see infra/keycloak/README.md#account-removal-client'; else if (error.reason === 'flow_conflict') message += '\nrealm: inspect the learnstack-first-broker-login flow; it is never overwritten; see infra/keycloak/README.md#federation-realm-invariants'; else if (error.reason === 'secret_conflict') diff --git a/scripts/development-realm-owner.mjs b/scripts/development-realm-owner.mjs index b6dd7405a..bda9a44b9 100644 --- a/scripts/development-realm-owner.mjs +++ b/scripts/development-realm-owner.mjs @@ -77,12 +77,35 @@ export function federationAdminEnvironment(source, ambient = process.env) { if (exact.length !== 1 || aliases.length !== 1 || typeof value !== 'string' || !value.trim() || value.length < 16 || Buffer.byteLength(value, 'utf8') > 1024 || value === '**********' || value.startsWith('${') || /[\r\n\0]/.test(value) || [values.KEYCLOAK_WEB_CLIENT_SECRET, values.KEYCLOAK_ADMIN_PASSWORD, - values.IdentityEvents__ClientSecret].includes(value) + values.IdentityEvents__ClientSecret, values.KEYCLOAK_ACCOUNT_REMOVAL_SECRET].includes(value) || values.Federation__ClientSecret !== undefined && values.Federation__ClientSecret !== value || ambient[key] !== undefined && ambient[key] !== value) refuse('preflight', 'configuration'); return value; } +/** + * ADR-0107 section 7's account-removal client secret (manage-users only): required, one assignment, and + * refused by the same rule the API applies (empty, over 1,024 bytes, the mask literal or a `${` vault + * reference). It is distinct from every other private credential, the federation admin secret + * included; the API's `AccountRemoval__ClientSecret`, when the same file carries it, must be the + * identical value. + */ +export function accountRemovalEnvironment(source, ambient = process.env) { + const values = parseEnv(source); + const key = 'KEYCLOAK_ACCOUNT_REMOVAL_SECRET'; + const exact = [...source.matchAll(/^KEYCLOAK_ACCOUNT_REMOVAL_SECRET=/gm)]; + const aliases = [...source.matchAll(/^[ \t]*(?:export[ \t]+)?KEYCLOAK_ACCOUNT_REMOVAL_SECRET[ \t]*=/gm)]; + const value = values[key]; + if (exact.length === 0 && aliases.length === 0) refuse('preflight', 'missing_account_removal_secret'); + if (exact.length !== 1 || aliases.length !== 1 || typeof value !== 'string' || !value.trim() + || value.length < 16 || Buffer.byteLength(value, 'utf8') > 1024 || value === '**********' || value.startsWith('${') + || /[\r\n\0]/.test(value) || [values.KEYCLOAK_WEB_CLIENT_SECRET, values.KEYCLOAK_ADMIN_PASSWORD, + values.IdentityEvents__ClientSecret, values.KEYCLOAK_FEDERATION_ADMIN_SECRET].includes(value) + || values.AccountRemoval__ClientSecret !== undefined && values.AccountRemoval__ClientSecret !== value + || ambient[key] !== undefined && ambient[key] !== value) refuse('preflight', 'configuration'); + return value; +} + /** Require the selected deployment's explicit immutable pair before migrations. */ export function seedAuthorityEnvironment(source, ambient = process.env) { const values = parseEnv(source); diff --git a/scripts/development-realm-owner.test.mjs b/scripts/development-realm-owner.test.mjs index 39e469e87..065e8e349 100644 --- a/scripts/development-realm-owner.test.mjs +++ b/scripts/development-realm-owner.test.mjs @@ -10,7 +10,7 @@ import { fileURLToPath } from 'node:url'; import test from 'node:test'; import { RealmError, realmFailure } from './development-realm-errors.mjs'; import { - acquireRealmLock, federationAdminEnvironment, readRealmEnvironmentFile, realmEnvironment, seedAuthorityEnvironment, validateLocalDockerContext, validateRealmTarget, + accountRemovalEnvironment, acquireRealmLock, federationAdminEnvironment, readRealmEnvironmentFile, realmEnvironment, seedAuthorityEnvironment, validateLocalDockerContext, validateRealmTarget, } from './development-realm-owner.mjs'; const keys = ['KEYCLOAK_ADMIN', 'KEYCLOAK_ADMIN_PASSWORD', 'KEYCLOAK_WEB_CLIENT_SECRET']; @@ -157,6 +157,91 @@ test('an inherited federation admin secret may only repeat the selected file val assert.equal(federationAdminEnvironment(withFederation(federationValue), { [federationKey]: federationValue }), federationValue); }); +const removalKey = 'KEYCLOAK_ACCOUNT_REMOVAL_SECRET'; +const removalValue = 'synthetic-account-removal-secret-82b1'; +const withRemoval = value => federationFile(source, `${removalKey}=${value}`); + +// A removal refusal must never echo a private value, whichever credential it concerns. +function removalRefusal(reason = 'configuration', ...secretsToHide) { + return error => { + assert.ok(error instanceof RealmError); + assert.equal(error.stage, 'preflight'); + assert.equal(error.reason, reason); + assert.equal(realmFailure(error), `realm: preflight/${reason}`); + for (const value of [...Object.values(values), removalValue, ...secretsToHide]) + assert.ok(!error.message.includes(value)); + return true; + }; +} + +test('the account removal secret is returned when it is the one distinct, valid assignment', () => { + assert.equal(accountRemovalEnvironment(withRemoval(removalValue), {}), removalValue); + assert.equal(accountRemovalEnvironment(withRemoval(removalValue), { [removalKey]: removalValue }), removalValue); +}); + +test('a missing account removal secret refuses with the dedicated code at preflight', () => { + assert.throws(() => accountRemovalEnvironment(source, {}), removalRefusal('missing_account_removal_secret')); + assert.throws(() => accountRemovalEnvironment('', {}), removalRefusal('missing_account_removal_secret')); + assert.throws(() => accountRemovalEnvironment(source, { [removalKey]: removalValue }), removalRefusal('missing_account_removal_secret')); + // The federation secret alone never stands in for it. + assert.throws(() => accountRemovalEnvironment(withFederation(federationValue), {}), removalRefusal('missing_account_removal_secret')); +}); + +test('a duplicated, exported or indented account removal assignment refuses configuration', () => { + const other = 'synthetic-removal-other-82b1'; + for (const second of [`${removalKey}=${other}`, `export ${removalKey}=${other}`, ` ${removalKey}=${other}`, + `${removalKey} = ${other}`, `\texport\t${removalKey}=${other}`]) + assert.throws(() => accountRemovalEnvironment(federationFile(withRemoval(removalValue), second), {}), + removalRefusal('configuration', other), second); + for (const alias of [`export ${removalKey}=${removalValue}`, ` ${removalKey}=${removalValue}`, `${removalKey} = ${removalValue}`]) + assert.throws(() => accountRemovalEnvironment(federationFile(source, alias), {}), removalRefusal(), alias); +}); + +test('an empty, short, masked, vault-reference or control-character account removal secret refuses', () => { + for (const value of ['', ' ', '""', '" "', 'r'.repeat(15), '**********', '${vault.removal-secret-value}', + "'${vault.removal-secret-value}'", '"synthetic-removal\nsecret-82b1"', 'synthetic-removal\0secret-82b1']) + assert.throws(() => accountRemovalEnvironment(withRemoval(value), {}), removalRefusal(), JSON.stringify(value)); + assert.equal(accountRemovalEnvironment(withRemoval('r'.repeat(16)), {}), 'r'.repeat(16)); + assert.equal(accountRemovalEnvironment(withRemoval('prefix-**********-suffix'), {}), 'prefix-**********-suffix'); +}); + +test('the account removal secret is bounded at 1,024 UTF-8 bytes, not characters', () => { + assert.equal(accountRemovalEnvironment(withRemoval('r'.repeat(1024)), {}), 'r'.repeat(1024)); + assert.throws(() => accountRemovalEnvironment(withRemoval('r'.repeat(1025)), {}), removalRefusal()); + const edge = '\u00e9'.repeat(512); + assert.equal(accountRemovalEnvironment(withRemoval(edge), {}), edge); + assert.throws(() => accountRemovalEnvironment(withRemoval('\u00e9'.repeat(513)), {}), removalRefusal()); +}); + +test('the account removal secret is distinct from every other private credential, the federation admin secret included', () => { + const events = 'synthetic-event-reader-secret-82b1'; + for (const [name, value] of [['KEYCLOAK_WEB_CLIENT_SECRET', values.KEYCLOAK_WEB_CLIENT_SECRET], + ['KEYCLOAK_ADMIN_PASSWORD', values.KEYCLOAK_ADMIN_PASSWORD], ['IdentityEvents__ClientSecret', events], + [federationKey, federationValue]]) { + assert.throws(() => accountRemovalEnvironment(federationFile(source, `IdentityEvents__ClientSecret=${events}`, + `${federationKey}=${federationValue}`, `${removalKey}=${value}`), {}), removalRefusal('configuration', events, federationValue), name); + } + assert.equal(accountRemovalEnvironment(federationFile(source, `IdentityEvents__ClientSecret=${events}`, + `${federationKey}=${federationValue}`, `${removalKey}=${removalValue}`), {}), removalValue); + // Symmetric: the federation secret refuses to equal the removal secret too. + assert.throws(() => federationAdminEnvironment(federationFile(source, `${removalKey}=${removalValue}`, + `${federationKey}=${removalValue}`), {}), federationRefusal('configuration', removalValue)); +}); + +test('AccountRemoval__ClientSecret in the same file must equal the account removal secret', () => { + const api = 'synthetic-api-removal-secret-82b1'; + assert.throws(() => accountRemovalEnvironment(federationFile(withRemoval(removalValue), `AccountRemoval__ClientSecret=${api}`), {}), + removalRefusal('configuration', api)); + assert.equal(accountRemovalEnvironment(federationFile(withRemoval(removalValue), + `AccountRemoval__ClientSecret=${removalValue}`), {}), removalValue); +}); + +test('an inherited account removal secret may only repeat the selected file value', () => { + const ambient = 'synthetic-ambient-removal-82b1'; + assert.throws(() => accountRemovalEnvironment(withRemoval(removalValue), { [removalKey]: ambient }), removalRefusal('configuration', ambient)); + assert.equal(accountRemovalEnvironment(withRemoval(removalValue), { [removalKey]: removalValue }), removalValue); +}); + function target() { const id = 'a'.repeat(64); return { diff --git a/scripts/development-realm-test-fixture.mjs b/scripts/development-realm-test-fixture.mjs index d983651f3..02357dc10 100644 --- a/scripts/development-realm-test-fixture.mjs +++ b/scripts/development-realm-test-fixture.mjs @@ -7,6 +7,7 @@ import { accountRetirementDetachment } from './development-realm-account.mjs'; export const desired = JSON.parse(await readFile(new URL('../infra/keycloak/realms/learnstack.json', import.meta.url), 'utf8')); export const secret = 'private-test-source'; export const federationSecret = 'private-federation-test-source'; +export const accountRemovalSecret = 'private-account-removal-test-source'; const clone = value => structuredClone(value); const omit = (value, keys) => Object.fromEntries(Object.entries(value).filter(([key]) => !keys.includes(key))); // Pinned RepresentationToModel.toModel/removeEmptyString, independently modeled @@ -97,6 +98,14 @@ export function provider() { const federationUser = { id: id(), username: 'service-account-learnstack-federation-admin', enabled: true, serviceAccountClientId: 'learnstack-federation-admin', roles: clone(federationMapping) }; state.federation = { management, role: federationRole, client: federationClient, user: federationUser }; + // The committed import's account-removal client (ADR-0107 section 7): the same shape, its own manage-users role. + const removalRole = { id: id(), name: 'manage-users', containerId: management.id, clientRole: true, composite: false }; + const removalClient = state.clients.find(client => client.clientId === 'learnstack-account-removal'); + removalClient.secret = accountRemovalSecret; + const removalMapping = { clientMappings: { 'realm-management': { id: management.id, client: 'realm-management', mappings: [clone(removalRole)] } } }; + const removalUser = { id: id(), username: 'service-account-learnstack-account-removal', enabled: true, + serviceAccountClientId: 'learnstack-account-removal', roles: clone(removalMapping) }; + state.accountRemoval = { management, role: removalRole, client: removalClient, user: removalUser }; state.scopeMappings ??= {}; const writes = []; const reads = []; @@ -138,6 +147,15 @@ export function provider() { else if (path === `users/${federation.user.id}/role-mappings`) value = federation.user.roles; else if (path === `users/${federation.user.id}/role-mappings/clients/${federation.management.id}/composite`) value = federation.user.roles.clientMappings?.['realm-management']?.mappings ?? []; + else if (path === `clients/${federation.management.id}/roles/manage-users`) value = state.accountRemoval.role; + else if (path === `clients/${state.accountRemoval.client.id}`) value = omit(state.accountRemoval.client, ['protocolMappers', 'secret']); + else if (path === `clients/${state.accountRemoval.client.id}/scope-mappings`) value = clone(state.accountRemoval.user.roles); + else if (path === `clients/${state.accountRemoval.client.id}/service-account-user`) + value = omit(state.accountRemoval.user, ['roles', 'serviceAccountClientId']); + else if (path === `users/${state.accountRemoval.user.id}/groups?first=0&max=1`) value = []; + else if (path === `users/${state.accountRemoval.user.id}/role-mappings`) value = state.accountRemoval.user.roles; + else if (path === `users/${state.accountRemoval.user.id}/role-mappings/clients/${federation.management.id}/composite`) + value = state.accountRemoval.user.roles.clientMappings?.['realm-management']?.mappings ?? []; else if (path === '') value = state.realm; else if (path === 'events/config') value = state.eventsConfig; else if (path === 'events?first=0&max=1') value = state.eventHistory.slice(0, 1); diff --git a/scripts/public-runtime.mjs b/scripts/public-runtime.mjs index 445ba764c..67bf16d40 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. diff --git a/scripts/reconcile-development-realm.mjs b/scripts/reconcile-development-realm.mjs index 798d0db7a..0034f16aa 100644 --- a/scripts/reconcile-development-realm.mjs +++ b/scripts/reconcile-development-realm.mjs @@ -6,7 +6,7 @@ import { composeSelection, repositoryRoot } from './compose.mjs'; import { DemoCommandError, DemoProcesses, installDemoCancellation } from './demo-process.mjs'; import { publicSeederEnvironment, developmentSeederRuntimeEnvironment } from './demo-database.mjs'; import { reconcileRealm, realmPassMilliseconds } from './development-realm-core.mjs'; -import { acquireRealmLock, eventReaderEnvironment, federationAdminEnvironment, isLocalDockerEndpoint, readRealmEnvironmentFile, realmEnvironment, seedAuthorityEnvironment, validateRealmTarget } from './development-realm-owner.mjs'; +import { accountRemovalEnvironment, acquireRealmLock, eventReaderEnvironment, federationAdminEnvironment, isLocalDockerEndpoint, readRealmEnvironmentFile, realmEnvironment, seedAuthorityEnvironment, validateRealmTarget } from './development-realm-owner.mjs'; import { RealmError, realmFailureNotice, refuse } from './development-realm-errors.mjs'; import { developmentBackchannelConfiguration, validateKeycloakBackchannelTrust } from './development-backchannel.mjs'; @@ -31,6 +31,7 @@ export async function reconcileDevelopmentRealm({ selected, signal, seedIdentity const values = realmEnvironment(source); const eventReaderSecret = eventReaderEnvironment(source); const federationSecret = federationAdminEnvironment(source); + const accountRemovalSecret = accountRemovalEnvironment(source); const identityEnvironment = seedIdentityFoundation ? seedAuthorityEnvironment(source) : undefined; const context = JSON.parse(await run(['context', 'inspect'])); const model = JSON.parse(await run([...selected.args, 'config', '--format', 'json'])); @@ -48,7 +49,7 @@ export async function reconcileDevelopmentRealm({ selected, signal, seedIdentity })); const desired = JSON.parse(await readFile(join(repositoryRoot, 'infra/keycloak/realms/learnstack.json'), 'utf8')); result = await reconcileRealm({ ...target, adminUsername: values.KEYCLOAK_ADMIN, - adminPassword: values.KEYCLOAK_ADMIN_PASSWORD, webSecret: values.KEYCLOAK_WEB_CLIENT_SECRET, eventReaderSecret, federationSecret, + adminPassword: values.KEYCLOAK_ADMIN_PASSWORD, webSecret: values.KEYCLOAK_WEB_CLIENT_SECRET, eventReaderSecret, federationSecret, accountRemovalSecret, manifest, desired, backchannel, signal: active, afterVerified: !seedIdentityFoundation ? undefined : async witness => { const applicationConnection = parseEnv(source).ConnectionStrings__Default; diff --git a/scripts/reconcile-development-realm.test.mjs b/scripts/reconcile-development-realm.test.mjs index 7ec145265..c64a8366d 100644 --- a/scripts/reconcile-development-realm.test.mjs +++ b/scripts/reconcile-development-realm.test.mjs @@ -122,9 +122,10 @@ async function ownedEntryFixture(t, scenario) { join(root, 'frontend/apps/web/scripts/stop-test-child.mjs')); await copyFile(new URL('../infra/keycloak/realms/learnstack.json', import.meta.url), join(root, 'infra/keycloak/realms/learnstack.json')); await writeFile(join(root, 'package.json'), '{"type":"module"}\n'); - const { secret, federationSecret } = await import('./development-realm-test-fixture.mjs'); + const { secret, federationSecret, accountRemovalSecret } = await import('./development-realm-test-fixture.mjs'); const values = { KEYCLOAK_ADMIN: 'synthetic-admin', KEYCLOAK_ADMIN_PASSWORD: canary, KEYCLOAK_WEB_CLIENT_SECRET: secret, KEYCLOAK_FEDERATION_ADMIN_SECRET: federationSecret, + KEYCLOAK_ACCOUNT_REMOVAL_SECRET: accountRemovalSecret, IdentityEvents__ClientSecret: 'owned-event-reader-fixture-secret', ...(scenario.startsWith('foundation-') ? { ConnectionStrings__Default: canary, Identity__AuthorityId: '01930000-0000-7000-8000-000000009001', diff --git a/scripts/run-realm-node-tests.py b/scripts/run-realm-node-tests.py index 1f295eee2..b8fce2878 100644 --- a/scripts/run-realm-node-tests.py +++ b/scripts/run-realm-node-tests.py @@ -18,9 +18,10 @@ 'development-event-reader.test.mjs': 16, 'development-realm-core.test.mjs': 66, 'development-realm-http.test.mjs': 42, - 'development-realm-owner.test.mjs': 77, + 'development-realm-owner.test.mjs': 85, 'development-realm-plan.test.mjs': 93, 'development-realm-federation.test.mjs': 33, + 'development-realm-account-removal.test.mjs': 20, 'development-realm-native-session.test.mjs': 6, 'development-realm-preparation.test.mjs': 28, 'development-realm-stock-console.test.mjs': 26,