diff --git a/.claude/skills/local-dev-setup/SKILL.md b/.claude/skills/local-dev-setup/SKILL.md index 67795a5e4..2538d8a8c 100644 --- a/.claude/skills/local-dev-setup/SKILL.md +++ b/.claude/skills/local-dev-setup/SKILL.md @@ -126,6 +126,11 @@ session, supply `ConnectionStrings:Default` (`learnstack_app`) and `ConnectionStrings:OutboxDispatcher` (`learnstack_outbox_admin`) through environment or the project's `learnstack-api-dev` user-secrets store. The mandatory API worker resolves its guarded source and verifies dispatcher connectivity at startup. +Also supply `Identity:AuthorityId` (`Identity__AuthorityId`) and +`Authentication:Tenant:Issuer` (`Authentication__Tenant__Issuer`) matching the +installed deployment authority, following +[Identity deployment](../../../docs/modules/identity/README.md#global-implementation-and-deployment). +Authority qualification is mandatory before the API accepts requests. The dispatcher credential belongs only to the API; every Seeder invocation uses an explicit application-only environment, and the web launcher receives neither database credential. Both empty hop lists remain diff --git a/.claude/skills/run-tests-locally/SKILL.md b/.claude/skills/run-tests-locally/SKILL.md index 592487aac..7c1e179b7 100644 --- a/.claude/skills/run-tests-locally/SKILL.md +++ b/.claude/skills/run-tests-locally/SKILL.md @@ -79,10 +79,16 @@ frontend/apps/web/scripts/ ### Step 3: Run unit tests +Use `--configuration Release` for repository qualification, matching CI. The +architecture suite includes exact compiled ownership/opcode controls; a Debug +build is not interchangeable with that qualified population. Run heavy .NET and +native frontend qualification sequentially on a workstation so cold development +compilation does not compete with the architecture mutation census. + Fastest; no Docker required. ```bash -dotnet test backend/tests/LearnStack.Tests.Unit \ +dotnet test --configuration Release backend/tests/LearnStack.Tests.Unit \ --no-restore \ --logger "console;verbosity=normal" ``` @@ -91,11 +97,12 @@ Typical runtime: < 30 s. Failures here are almost always domain-logic bugs. ### Step 4: Run architecture tests -Also fast; no Docker. Failures here mean **structural drift** — the code violates -a documented rule. +No Docker. The full IL mutation census can take tens of minutes on a workstation; +CI runs it in bounded shards. Failures here mean **structural drift** — the code +violates a documented rule. ```bash -dotnet test backend/tests/LearnStack.Tests.Architecture \ +dotnet test --configuration Release backend/tests/LearnStack.Tests.Architecture \ --no-restore ``` @@ -134,7 +141,7 @@ into native/ordinary execution jobs behind the required integration aggregate. L `--filter "Requires!=Docker"` gives you the Docker-free half. ```bash -dotnet test backend/tests/LearnStack.Tests.Integration \ +dotnet test --configuration Release backend/tests/LearnStack.Tests.Integration \ --no-restore \ --logger "console;verbosity=normal" \ --filter "FullyQualifiedName~Enrollment" # subset @@ -273,17 +280,17 @@ processes on Ctrl+C; it does not run the CI browser/audit proof. ### Step 7: Single-test focus -`dotnet test --filter`: +`dotnet test --configuration Release --filter`: ```bash # Class -dotnet test --filter "FullyQualifiedName~EnrollmentCreateTests" +dotnet test --configuration Release --filter "FullyQualifiedName~EnrollmentCreateTests" # Method -dotnet test --filter "FullyQualifiedName~EnrollmentCreateTests.Create_succeeds" +dotnet test --configuration Release --filter "FullyQualifiedName~EnrollmentCreateTests.Create_succeeds" # Docker trait — native CI additionally uses NativeCrashProof=true and its complement -dotnet test --filter "Requires=Docker" +dotnet test --configuration Release --filter "Requires=Docker" ``` `vitest`: @@ -298,11 +305,11 @@ pnpm --filter @learnstack/web test -t "shows danger tone" # name filter ```bash # From the repository root; collect behavioral suites separately. -dotnet test backend/tests/LearnStack.Tests.Unit \ +dotnet test --configuration Release backend/tests/LearnStack.Tests.Unit \ --collect:"XPlat Code Coverage" --results-directory coverage/unit -dotnet test backend/tests/LearnStack.Tests.Integration \ +dotnet test --configuration Release backend/tests/LearnStack.Tests.Integration \ --collect:"XPlat Code Coverage" --results-directory coverage/integration -dotnet test backend/tests/LearnStack.Tests.Architecture +dotnet test --configuration Release backend/tests/LearnStack.Tests.Architecture reportgenerator -reports:"coverage/**/coverage.cobertura.xml" \ -targetdir:"coverage/html" \ -reporttypes:Html @@ -337,12 +344,12 @@ make install # The `backend` job — build with warnings as errors, then the Docker-free half (cd backend && CI=true dotnet build LearnStack.slnx --no-restore --configuration Release) -(cd backend && dotnet test LearnStack.slnx \ +(cd backend && dotnet test --configuration Release LearnStack.slnx \ --no-restore --no-build --configuration Release \ --filter "Requires!=Docker" --logger trx) # The complete Docker complement; CI requires both native/ordinary partitions -(cd backend && dotnet test LearnStack.slnx \ +(cd backend && dotnet test --configuration Release LearnStack.slnx \ --no-restore --no-build --configuration Release \ --filter "Requires=Docker" --logger trx) ``` diff --git a/.env.example b/.env.example index 9be57c6d5..75fe86e85 100644 --- a/.env.example +++ b/.env.example @@ -65,8 +65,12 @@ ConnectionStrings__OutboxDispatcher='Host=localhost;Port=5432;Database=learnstac # ─── Keycloak (two realms per ADR-0004 Amendment 1) ────────────────────── # The Development API defaults to the loopback tenant issuer declared in # backend/src/LearnStack.Api/appsettings.Development.json. Other deployment modes -# require an explicit canonical HTTPS issuer; this override goes only to the API. -# Authentication__Tenant__Issuer=https://identity.example/realms/learnstack +# require an explicit canonical HTTPS issuer; the API and authority installer use it. +Authentication__Tenant__Issuer=http://localhost:8080/realms/learnstack +# Global identity uses an explicit stable deployment ID, not a hash of the issuer. +# `make migrate` installs/verifies BOTH explicit keys as one immutable registration. +# This fixed ID is local development data; deployment owners choose their stable ID. +Identity__AuthorityId=019a1929-5450-7bbb-8df1-516e8e002501 KEYCLOAK_ADMIN=admin KEYCLOAK_ADMIN_PASSWORD=admin-dev-secret # Server-only BFF client source. Old local .env files must add it explicitly; diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 78a24d05b..44996e7a8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -242,7 +242,7 @@ jobs: backend-integration-tests: name: backend ordinary-${{ matrix.index }} runs-on: ubuntu-24.04 - timeout-minutes: 20 + timeout-minutes: 25 strategy: fail-fast: false matrix: @@ -295,7 +295,23 @@ jobs: - name: Prepare pinned provider fixture images within the whole-job budget timeout-minutes: 2 - run: python3 scripts/ci-test-shards.py prepare-fixtures + env: + LEARNSTACK_NATIVE_RUNNER_CONTEXT: ${{ runner.environment }} + LEARNSTACK_NATIVE_RUNNER_OS: ${{ runner.os }} + LEARNSTACK_NATIVE_RUNNER_ARCH: ${{ runner.arch }} + LEARNSTACK_NATIVE_RUNNER_LABEL: ubuntu-24.04 + LEARNSTACK_NATIVE_JOB_CONTAINER: ${{ toJSON(job.container) }} + LEARNSTACK_NATIVE_JOB_SERVICES: ${{ toJSON(job.services) }} + LEARNSTACK_CI_HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + LEARNSTACK_NATIVE_RUN_ID: ${{ github.run_id }} + LEARNSTACK_NATIVE_ATTEMPT: ${{ github.run_attempt }} + LEARNSTACK_NATIVE_JOB: ${{ github.job }} + LEARNSTACK_NATIVE_SHA: ${{ github.sha }} + LEARNSTACK_NATIVE_REPOSITORY: ${{ github.repository }} + LEARNSTACK_NATIVE_WORKFLOW_REF: ${{ github.workflow_ref }} + LEARNSTACK_NATIVE_WORKFLOW_SHA: ${{ github.workflow_sha }} + LEARNSTACK_NATIVE_WORKSPACE: ${{ github.workspace }} + run: python3 scripts/ci-test-shards.py prepare-fixtures ordinary-${{ matrix.index }} - name: Verify stock browser for admission navigation proof run: | diff --git a/CLAUDE.md b/CLAUDE.md index d0c790923..68deedb0f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -39,10 +39,12 @@ repository holds only LearnStack's side of the boundary, in ## What state this is in -**Phase 01, Phase 02a and Phase 02d are complete; Phase 02b is the live phase.** +**Phase 01, Phase 02a, Phase 02d and Phase 02b are complete; Phase 03 is in progress.** [Phase 02d](docs/roadmap/phase-02d-walking-skeleton.md) owns the two-tenant walking -skeleton. [Phase 02b](docs/roadmap/phase-02b-events-auth.md) owns current packet -and decision state for events, background jobs, identity and sessions. +skeleton. [Phase 02b](docs/roadmap/phase-02b-events-auth.md) owns the delivered +events, background jobs, API authentication and session baseline. +[Phase 03](docs/roadmap/phase-03-identity-admin.md) owns identity, membership and authorization work; its Status block records +current packet state. Acceptance of a contract does not complete its implementation. [Phase 06](docs/roadmap/phase-06-renderer-admin-studio.md) owns the full renderer/Studio expansion. @@ -61,8 +63,8 @@ the foundation ports — is recorded packet by packet in frozen history, together with the 2026-08-08 restructure that moved correctness earlier, additive infrastructure later and proof earlier. -**Four modules hold domain code:** Tenancy, Customization, Audit and Education. -Content, Identity and Media remain scaffolded. Module-level references in the docs +**Five modules hold domain code:** Tenancy, Customization, Audit, Education and +Identity. Content and Media remain scaffolded. Module-level references in the docs to types such as `ILiveClassProvider` or `ITenantSearch` describe intended shape owned by their named phases. @@ -77,10 +79,13 @@ For any task, read in this order: 5. [docs/standards/00-principles.md](docs/standards/00-principles.md) — the beliefs every other standard descends from. 6. [docs/glossary.md](docs/glossary.md) — terminology; the single source of truth for project-specific terms. -Then read the phase that is live and the one it stands on: +Then read the current phase and the completed baselines it stands on: +- [docs/roadmap/phase-03-identity-admin.md](docs/roadmap/phase-03-identity-admin.md) — + **the current phase**. Read its identity, + membership, authorization and first-writer decisions before planning code. - [docs/roadmap/phase-02b-events-auth.md](docs/roadmap/phase-02b-events-auth.md) — - **the live phase**. Its Status block owns packet state; its decision register owns + complete. Its Status block owns packet state; its decision register owns gate state and links each Accepted decision package in the delivery log, which is normative — read it before writing the code its gate governs. Navigate a delivery log by the generated index at its top; never read the whole file. @@ -177,6 +182,8 @@ rules: - OpenTelemetry + correlation id end to end ([10](docs/standards/10-observability.md)). - WCAG 2.2 AA across all surfaces ([16](docs/standards/16-accessibility.md)). - Audit-coverage matrix required per module ([18](docs/standards/18-audit-coverage.md)). +- Global User identity consumes the existing typed `UserId`; global and tenant + transaction owners never join or retarget each other ([ADR-0072](docs/decisions/0072-application-owned-identity-bootstrap.md)). - Permission keys `{module}.{resource}.{action}` with closed action set + scope (Platform / Tenant / Organization) ([19](docs/standards/19-permissions.md)). - Infrastructure-stack rules (foundation ports and their default @@ -294,9 +301,12 @@ rules: and every module's `IAuditCatalogSource` names the first two. Declaring them in the module is a project cycle. `AuditEntry` consumes them; it does not declare them. -- **Announce `TenantId.PlatformSentinel` as a request's tenant.** Exactly one - class of row carries it — a platform-scope operation with no resolvable - tenant, written standalone — and Packet 9 puts the guard where the value +- **Announce `TenantId.PlatformSentinel` as a request's tenant.** Exactly two named + classes of audit row may carry it: platform-scope standalone operations and + ADR-0072 global `identity.user.create` attempts under its confined common + owner. Neither class grants tenant authority or permits a tenant setter to + announce the sentinel. + Packet 9 puts the guard where the value enters: `SetProvisioningTenantContextAsync` refuses the sentinel exactly as it already refuses `Guid.Empty`, and `Tenant.Create` refuses it in the factory ([ADR-0044 Amendment 3](docs/decisions/0044-audit-write-path.md)). The diff --git a/Makefile b/Makefile index 62e032771..7c886e4bf 100644 --- a/Makefile +++ b/Makefile @@ -120,106 +120,15 @@ build-frontend: ## `pnpm -r build` the frontend monorepo. .PHONY: migrate migrate: ## Apply every EF migration chain (platform + each module) as `learnstack_migration` (the ONLY sanctioned carrier of that credential). - @# Every dotnet command in this recipe runs from `backend/`, because that is where - @# the SDK pin lives (`backend/global.json`). Run from the repository root there is - @# no global.json above them, so whichever SDK is newest on the machine answers — - @# and the pin exists precisely so this target and CI apply the same EF version. - @# - @# Standards 05 § Database roles: ConnectionStrings:Migration must never appear - @# in API or worker runtime configuration. The role OWNS every table it creates, - @# and a runtime that is the owner is precisely the arrangement FORCE ROW LEVEL - @# SECURITY exists to defeat — every isolation test would then pass against - @# policies that constrain nothing. This target is where the credential lives. - @# - @# Every design-time factory reads only ConnectionStrings__Migration, never - @# the startup application's Default connection. Export to that confined - @# factory; do not duplicate the credential on the process command line. - @# Four things this recipe does that a naive version does not, each because the - @# naive version was measured doing the wrong thing: - @# - @# 1. `.env` is read one key at a time, NOT shell-sourced. A connection string - @# contains semicolons, and `. ./.env` on an unquoted row parses them as - @# statement separators: `ConnectionStrings__Migration` arrived as - @# `Host=localhost`, and `Port`, `Database`, `Username`, `Password` leaked - @# into the environment as bare variables. `tr -d '\r'` as well, because a - @# CRLF row otherwise leaves the closing quote and the carriage return - @# inside the credential. - @# 2. The role is compared EXACTLY. An unanchored `*Username=learnstack_migration*` - @# accepted `learnstack_migration_readonly` and would have run migrations as - @# it. Splitting on `;` and comparing the whole token has no neighbourhood. - @# 3. The error path prints a REDACTED string. An earlier version echoed the - @# whole value, password included — in the one target whose entire purpose - @# is keeping that credential in one place. - @# 4. The loop carries its own status. `-e` does not abort on a failure inside - @# a for-loop body that is part of a compound list: both iterations ran - @# after `false` and the recipe still exited 0, so a migration target - @# reported success after every migration failed. - @# 5. The loop covers `LearnStack.Infrastructure` as well as the modules. The - @# platform chain (outbox_messages, idempotency_keys) lives outside - @# `src/Modules`, and a glob that only walked the modules left the two - @# tables no module owns unmigrated on every documented path. - @# 6. Tenancy is named BEFORE the glob. From Phase 02a Packet 9 the chains are - @# no longer independent: `audit_config` carries the schema's only - @# cross-chain foreign key, to `tenants`, which the Tenancy chain creates. - @# The glob expands alphabetically and `Modules/Audit` sorts first, so the - @# naive order fails on a fresh database. `applied` is what keeps the named - @# project from being visited twice when the glob reaches it — a second - @# `database update` is a no-op, but a recipe that prints the same chain - @# twice reads like a bug in the recipe. - @# 7. Build the startup graph once in Release, with restore for standalone use. - @# Every EF invocation uses that fresh output; the demo launches the same API. - @# Explicit failures also stop old Make versions without shell errexit. - @# 8. Save and unexport the migration credential before restore/build; only - @# the no-build EF child receives it, through its process environment. - @migration_cs="$${ConnectionStrings__Migration:-}"; \ - unset ConnectionStrings__Migration; \ - migration_env="$${LEARNSTACK_COMPOSE_ENV_FILE:-.env}"; \ - if [ -z "$$migration_cs" ] && [ -f "$$migration_env" ]; then \ - migration_cs=$$(sed -n "s/^ConnectionStrings__Migration=//p" "$$migration_env" \ - | tail -1 | tr -d "\r" | sed "s/^['\"]//; s/['\"]$$//"); \ - fi; \ - role=$$(printf '%s' "$$migration_cs" | awk -f scripts/connection-string.awk -v field=user); \ - redacted=$$(printf '%s' "$$migration_cs" | awk -f scripts/connection-string.awk -v field=redacted); \ - if [ -z "$$migration_cs" ]; then \ - echo "ConnectionStrings__Migration is not set."; \ - echo "It arrives with the four-role model in Phase 02a Packet 6: copy the"; \ - echo "'four database roles' and 'four connection strings' blocks out of"; \ - echo ".env.example into your .env and re-run. A .env written before that"; \ - echo "packet has neither."; \ - exit 1; \ - fi; \ - if [ "$$role" != "learnstack_migration" ]; then \ - echo "ConnectionStrings__Migration names Username='$$role', not learnstack_migration:"; \ - echo " $$redacted"; \ - echo "Migrations must run as the role that OWNS every table. Running them as"; \ - echo "the runtime role is the arrangement FORCE ROW LEVEL SECURITY defeats."; \ - echo "If the value looks truncated at the first ';', quote it in .env. A"; \ - echo "URI-style DSN (postgres://...) is not a form Npgsql parses at all; the"; \ - echo "expected shape is the key/value list in .env.example."; \ - exit 1; \ - fi; \ - (cd backend && dotnet tool restore >/dev/null) || exit $$?; \ - (cd backend && dotnet build src/LearnStack.Api --configuration Release --nologo) || exit $$?; \ - found=0; \ - failed=0; \ - applied=" "; \ - for proj in backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure \ - backend/src/LearnStack.Infrastructure \ - backend/src/Modules/*/LearnStack.Modules.*.Infrastructure; do \ - test -d "$$proj/Persistence/Migrations" || continue; \ - case "$$applied" in *" $$proj "*) continue;; esac; \ - applied="$$applied$$proj "; \ - found=1; \ - echo "==> $$(basename $$proj)"; \ - (cd backend && ConnectionStrings__Migration="$$migration_cs" dotnet ef database update \ - --project "../$$proj" \ - --startup-project src/LearnStack.Api \ - --configuration Release --no-build) || failed=1; \ - done; \ - if [ "$$found" = "0" ]; then \ - echo "No project carries Persistence/Migrations yet — the first lands with the Tenancy schema in Phase 02a Packet 6."; \ - fi; \ - exit "$$failed" + @# The Node owner selects one deployment source, validates the migration role, + @# and confines credentials to EF/authority children after fresh Release builds. + @# Keep dependency order explicit and cover future module chains with the glob. + @node scripts/migrate.mjs \ + backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure \ + backend/src/LearnStack.Infrastructure \ + backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure \ + backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure \ + backend/src/Modules/*/LearnStack.Modules.*.Infrastructure .PHONY: sdk sdk: ## Regenerate @learnstack/sdk types from the committed v1 snapshot. diff --git a/README.md b/README.md index d4e229e44..87ec91ed0 100644 --- a/README.md +++ b/README.md @@ -65,10 +65,12 @@ items, rules, custom fields and notification templates; their delivery is tracke ## Where it is today -**Phase 01, Phase 02a and Phase 02d are complete; Phase 02b is in progress.** +**Phase 01, Phase 02a, Phase 02d and Phase 02b are complete; Phase 03 is in progress.** [Phase 02d](docs/roadmap/phase-02d-walking-skeleton.md) owns the two-tenant walking -skeleton. Current packet state lives in the -[Phase 02b](docs/roadmap/phase-02b-events-auth.md) document's Status block; the +skeleton. [Phase 02b](docs/roadmap/phase-02b-events-auth.md) owns the delivered +events, jobs, authentication and session baseline. The +[Phase 03](docs/roadmap/phase-03-identity-admin.md) Status block owns current state +for identity, membership and authorization work; the [roadmap](docs/roadmap/README.md) lists every phase. | Area | Delivered now | Next milestone | @@ -80,8 +82,10 @@ skeleton. Current packet state lives in the | **API foundation** | Error contracts, validation, tenancy, concurrency, observability, durable events/subscriber delivery, background jobs, the closed tenant bearer/AccountSite boundary and development realm reconciliation | Membership and permissions in [Phase 03](docs/roadmap/phase-03-identity-admin.md); current exit state in [Phase 02b](docs/roadmap/phase-02b-events-auth.md) | | **Frontend** | Native TLS ingress, live locale entry, trusted server caller, localized catalog/course/lesson pages, safe themes, accessibility controls/manual smoke, generated typed SDK and optional bounded native BFF session scaffolds | Full renderer/Studio and Playwright Test/axe in [Phase 06](docs/roadmap/phase-06-renderer-admin-studio.md) | -**Four modules contain domain implementations:** Tenancy, Customization, Audit and -Education. Identity, Content and Media remain scaffolded. +**Five modules contain domain implementations:** Tenancy, Customization, Audit, +Education and Identity. Identity's [module specification](docs/modules/identity/README.md) +distinguishes implemented global/contextual foundations and seed admission from +remaining API activation and live authorization. Content and Media remain scaffolded. The subsequent product milestones are CMS and media ([04](docs/roadmap/phase-04-cms-media-pages.md)), the full course catalog ([05](docs/roadmap/phase-05-education-learning-content.md)), @@ -116,7 +120,8 @@ make hooks # optional: install the repository Git hooks Continue with the manual HTTPS prerequisites below, then run `make demo`. It creates missing private configuration and restores dependencies without changing Git hooks. `make seed` converges application data and the development identity -realm without starting the API or web. Direct .NET Seeder remains data-only. +realm and its application-owned identity foundation without starting the API or +web. The argument-free direct .NET Seeder remains data-only. The seed provisions `demo-english` and `demo-yoga`, their organizations and host mappings, enabled locales, distinct branding, built-in and tenant-authored definitions, @@ -124,7 +129,8 @@ and eight scoped courses, ten lessons and twenty-seven translations. It uses the ordinary authoring pipeline and verifies completed acts before skipping them on rerun. [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`; existing +Older private files must explicitly add `KEYCLOAK_WEB_CLIENT_SECRET` and the +stable authority/issuer pair described in the realm guide; existing passwords/MFA and provider IDs are preserved. Prepare this secret before the first `make dev` import, and retain it across reruns. Older files also need explicit private permissions after verifying their ownership/type; Makefile @@ -191,7 +197,12 @@ no-hop API startup remains supported outside this paired renderer recipe; supply both `ConnectionStrings:Default` (`learnstack_app`) and `ConnectionStrings:OutboxDispatcher` (`learnstack_outbox_admin`). The mandatory API worker verifies dispatcher connectivity at startup. -Supply `Authentication:Tenant:Issuer` too: the canonical HTTPS tenant-realm URL, +Supply `Identity:AuthorityId` (`Identity__AuthorityId`) and +`Authentication:Tenant:Issuer` (`Authentication__Tenant__Issuer`) matching the +installed deployment authority, following +[Identity deployment](docs/modules/identity/README.md#global-implementation-and-deployment). +Direct API startup reads process/.NET configuration, not the root `.env`. +The issuer is the canonical HTTPS tenant-realm URL, with loopback HTTP allowed only in `Development`. The development configuration defaults to `http://localhost:8080/realms/learnstack`; issuer configuration is validated without contacting Keycloak at startup. Credential-free public reads @@ -213,7 +224,7 @@ the closed authenticated hop. See | `make help` | List available tasks. | | `make demo` | Build/start the seeded production sites; Ctrl+C preserves local data. | | `make dev` | Start the default local infrastructure. | -| `make migrate` | Apply platform and module migration chains. | +| `make migrate` | Apply platform/module migrations and install or verify an explicitly configured [identity authority](docs/modules/identity/README.md#global-implementation-and-deployment). | | `make test` | Restore dependencies and run backend and frontend suites; Docker is required. | | `make lint` | Check backend formatting and frontend lint rules. | | `make down` | Stop infrastructure while preserving its data volumes. | @@ -231,7 +242,7 @@ three product surfaces. See the | Layer | Choice | Current scope | |---|---|---| -| Backend | .NET 10 · ASP.NET Core · EF Core · MediatR | Foundation and four domain modules implemented | +| Backend | .NET 10 · ASP.NET Core · EF Core · MediatR | Foundation and domain modules implemented | | Database | PostgreSQL 18 | Migrations, tenant / organization RLS and integration proofs | | Frontend | Next.js 15 · React 19 · TypeScript | App/UI scaffolds; generated SDK and injected transport implemented | | Observability | OpenTelemetry · Serilog → OTLP | Cross-cutting backend instrumentation implemented | @@ -290,7 +301,7 @@ docs/ Architecture, decisions, standards, roadmap and module specs | Your question | Start here | |---|---| | What are we building, and for whom? | [Platform vision](docs/architecture/01-platform-vision.md) · [MVP scope](docs/architecture/05-mvp-scope.md) | -| What works today, and what comes next? | [Roadmap](docs/roadmap/README.md) · [Current phase](docs/roadmap/phase-02b-events-auth.md) | +| What works today, and what comes next? | [Roadmap](docs/roadmap/README.md) · [Next phase](docs/roadmap/phase-03-identity-admin.md) | | How do I contribute? | [Contributing](.github/CONTRIBUTING.md) · [Working agreement](CLAUDE.md) · [Engineering standards](docs/standards/README.md) | | Why was a decision made? | [ADR index](docs/decisions/README.md) | | How are institutions isolated? | [Tenant isolation](docs/architecture/09-tenant-isolation.md) · [Tenancy module](docs/modules/tenancy/README.md) | diff --git a/backend/LearnStack.slnx b/backend/LearnStack.slnx index 8f89d16c1..b322621e7 100644 --- a/backend/LearnStack.slnx +++ b/backend/LearnStack.slnx @@ -12,6 +12,7 @@ + diff --git a/backend/README.md b/backend/README.md index d927e0c0c..e3f3386ab 100644 --- a/backend/README.md +++ b/backend/README.md @@ -2,7 +2,7 @@ .NET 10 modular monolith — see [docs/standards/01-architecture-standards.md](../docs/standards/01-architecture-standards.md) for the module-layout rules and [docs/architecture/03-module-boundaries.md](../docs/architecture/03-module-boundaries.md) -for the dependency direction this scaffold enforces. +for the dependency direction the source enforces. ## Layout @@ -21,10 +21,12 @@ backend/ LearnStack.Infrastructure/ # EF + cross-cutting infra LearnStack.Infrastructure.Audit/ # ADR-0033 audit pipeline plumbing LearnStack.Api/ # ASP.NET host + LearnStack.Tools.IdentityAuthorityInstaller/ # deployment-only identity anchor + LearnStack.Tools.Seeder/ # finite development data/adoption Modules/ Tenancy/ # 4-package layout per module - Identity/ + Identity/ # global binding + scoped foundation Customization/ # ADR-0018 tenant customization aggregates Audit/ # AuditEntry aggregate (ADR-0033) Content/ @@ -37,7 +39,7 @@ backend/ tests/ LearnStack.Tests.Unit/ - LearnStack.Tests.Integration/ # Testcontainers (Postgres/Valkey) + LearnStack.Tests.Integration/ # offline HTTP + real Postgres/Keycloak LearnStack.Tests.Architecture/ # NetArchTest + filesystem invariants LearnStack.Tests.Contract/ ``` @@ -56,6 +58,9 @@ backend/ the .NET 10 SDK from before `dotnet build`. - A local infrastructure stack — see [../infra/compose/dev.yml](../infra/compose/dev.yml). +- Install the matching identity authority before API startup, following + [Identity deployment](../docs/modules/identity/README.md#global-implementation-and-deployment). + Runtime uses application credentials; the migration credential stays deploy-only. ## Common Commands @@ -63,7 +68,8 @@ backend/ # Restore + build dotnet build LearnStack.slnx -# Run the API (defaults to http://localhost:5080) +# Run the API with its runtime configuration already supplied +# (defaults to http://localhost:5080) dotnet run --project src/LearnStack.Api # Tests by suite @@ -73,4 +79,8 @@ dotnet test tests/LearnStack.Tests.Integration # needs docker for Testcont dotnet test tests/LearnStack.Tests.Contract ``` -The `make` orchestrator and CI workflow land in a later Phase 01 package. +The direct API command reads process/.NET configuration, not the root `.env`. +For the owned local API and native HTTPS web lifecycle, run `make demo` from +the repository root; it projects the selected private environment. The +[root quick start](../README.md#quickstart) owns setup, and +[test guidance](../.claude/skills/run-tests-locally/SKILL.md) owns suite selection. diff --git a/backend/src/LearnStack.Api/Authentication/TenantAuthenticationDiagnostics.cs b/backend/src/LearnStack.Api/Authentication/TenantAuthenticationDiagnostics.cs index fe5a407fc..dee771a1e 100644 --- a/backend/src/LearnStack.Api/Authentication/TenantAuthenticationDiagnostics.cs +++ b/backend/src/LearnStack.Api/Authentication/TenantAuthenticationDiagnostics.cs @@ -9,6 +9,7 @@ internal enum TenantAuthenticationOutcome ProfileRejected, ValidationAccepted, ValidationRejected, + BindingStoreUnavailable, } /// Suppress vendor failure text before sinks; emit closed outcomes instead. @@ -29,6 +30,7 @@ internal static void Outcome(ILogger logger, TenantAuthenticationOutcome outcome TenantAuthenticationOutcome.ProfileRejected => ("profile", "rejected"), TenantAuthenticationOutcome.ValidationAccepted => ("validation", "accepted"), TenantAuthenticationOutcome.ValidationRejected => ("validation", "rejected"), + TenantAuthenticationOutcome.BindingStoreUnavailable => ("binding", "binding_store_unavailable"), _ => throw new ArgumentOutOfRangeException(nameof(outcome)), }; AuthenticationOutcome(logger, stage, reason, null); diff --git a/backend/src/LearnStack.Api/Authentication/TenantAuthenticationRegistration.cs b/backend/src/LearnStack.Api/Authentication/TenantAuthenticationRegistration.cs index 6a64d1c5b..02906c3e4 100644 --- a/backend/src/LearnStack.Api/Authentication/TenantAuthenticationRegistration.cs +++ b/backend/src/LearnStack.Api/Authentication/TenantAuthenticationRegistration.cs @@ -81,7 +81,7 @@ internal static IServiceCollection AddLearnStackTenantAuthentication( } } -/// Only a cryptographically validated token can publish its typed identity. +/// Only stock cryptographic validation publishes typed provider-subject evidence. internal sealed class TenantAuthenticationEvents( TenantAuthenticationOptions settings, IClock clock, @@ -129,7 +129,7 @@ public override Task TokenValidated(TokenValidatedContext context) } else { - feature.Identity = identity; + feature.VerifiedSubject = identity; TenantAuthenticationDiagnostics.Outcome(logger, TenantAuthenticationOutcome.ValidationAccepted); } @@ -141,6 +141,7 @@ public override Task AuthenticationFailed(AuthenticationFailedContext context) if (context.HttpContext.Features.Get() is { } feature) { feature.Identity = null; + feature.VerifiedSubject = null; } TenantAuthenticationDiagnostics.Outcome(logger, TenantAuthenticationOutcome.ValidationRejected); diff --git a/backend/src/LearnStack.Api/Authentication/TenantCredentialAdmissionMiddleware.cs b/backend/src/LearnStack.Api/Authentication/TenantCredentialAdmissionMiddleware.cs index ce29a67c2..a0c4c3c98 100644 --- a/backend/src/LearnStack.Api/Authentication/TenantCredentialAdmissionMiddleware.cs +++ b/backend/src/LearnStack.Api/Authentication/TenantCredentialAdmissionMiddleware.cs @@ -9,9 +9,10 @@ internal sealed class TenantCredentialAdmissionMiddleware(RequestDelegate next) public Task InvokeAsync(HttpContext context) { ArgumentNullException.ThrowIfNull(context); + if (context.Features.Get() is { } feature) feature.Identity = null; if (context.Features.Get() is not null && context.Request.Headers.ContainsKey("Authorization") - && context.Features.Get()?.Identity is null) + && context.Features.Get()?.VerifiedSubject is null) { PublicResponsePolicy.Apply(context.Response); context.Response.Headers.WWWAuthenticate = "Bearer"; diff --git a/backend/src/LearnStack.Api/Authentication/TenantCredentialFeature.cs b/backend/src/LearnStack.Api/Authentication/TenantCredentialFeature.cs index 48c7c8bdc..55546938c 100644 --- a/backend/src/LearnStack.Api/Authentication/TenantCredentialFeature.cs +++ b/backend/src/LearnStack.Api/Authentication/TenantCredentialFeature.cs @@ -1,7 +1,8 @@ namespace LearnStack.Api.Authentication; -/// Request-local outcome; only a validated profile carries identity. +/// Separates verified credentials from the existing binding's normalized identity. internal sealed class TenantCredentialFeature { + public VerifiedProviderSubject? VerifiedSubject { get; set; } public ValidatedTenantIdentity? Identity { get; set; } } diff --git a/backend/src/LearnStack.Api/Authentication/TenantIdentityBindingAdmissionMiddleware.cs b/backend/src/LearnStack.Api/Authentication/TenantIdentityBindingAdmissionMiddleware.cs new file mode 100644 index 000000000..5146edd4a --- /dev/null +++ b/backend/src/LearnStack.Api/Authentication/TenantIdentityBindingAdmissionMiddleware.cs @@ -0,0 +1,135 @@ +using LearnStack.Api.PublicReads; +using LearnStack.Api.Tenancy; +using LearnStack.Modules.Identity.Application.Contracts.Bindings; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Identity; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Npgsql; + +namespace LearnStack.Api.Authentication; + +/// The API's read-only existing-binding seam; it grants no creation capability. +internal interface ITenantIdentityBindingResolver +{ + Task ResolveExistingAsync(VerifiedProviderSubject subject, + CancellationToken cancellationToken = default); +} + +internal sealed class TenantIdentityBindingResolver( + IdentityAuthorityQualification qualification, + Func reader) : ITenantIdentityBindingResolver +{ + public Task ResolveExistingAsync(VerifiedProviderSubject subject, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(subject); + var authority = qualification.Current; + if (authority is null || !string.Equals(authority.Issuer, subject.Issuer, StringComparison.Ordinal)) + return Task.FromResult(IdentityBindingResult.Refused(IdentityBindingOutcome.AuthorityUnavailable)); + return reader().ResolveExistingAsync(new GlobalIdentitySubject(authority.AuthorityId, authority.Issuer, subject.Subject), + subject.ClaimedActor, cancellationToken); + } +} + +/// Normalizes only a quota-admitted existing binding before ordinary tenant reconciliation. +internal sealed class TenantIdentityBindingAdmissionMiddleware(RequestDelegate next, + ILogger logger) +{ + public async Task InvokeAsync(HttpContext context, ITenantIdentityBindingResolver resolver) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(resolver); + var feature = context.Features.Get(); + if (feature is not null) feature.Identity = null; + if (context.Features.Get() is null) + { + await next(context); + return; + } + + var provenance = context.Features.Get(); + if (feature?.VerifiedSubject is not { } subject) + { + if (provenance is not null || context.Features.Get() is not null) Refuse(context); + else await next(context); + return; + } + + if (provenance?.Matches(subject) is not true + || context.Features.Get()?.IsAcquired is not true) + { + Refuse(context); + return; + } + + IdentityBindingResult binding; + try + { + context.RequestAborted.ThrowIfCancellationRequested(); + binding = await resolver.ResolveExistingAsync(subject, context.RequestAborted); + context.RequestAborted.ThrowIfCancellationRequested(); + } + catch (NpgsqlException) + { + StoreUnavailable(context); + return; + } + catch (TimeoutException) + { + StoreUnavailable(context); + return; + } + + if (binding.Outcome != IdentityBindingOutcome.Existing || binding.Actor is not { } actor) + { + if (binding.Outcome is IdentityBindingOutcome.StorageUnavailable or IdentityBindingOutcome.AuthorityUnavailable) + StoreUnavailable(context); + else Refuse(context); + return; + } + + feature.Identity = new ValidatedTenantIdentity(subject.Issuer, subject.Subject, actor, + subject.TenantId, subject.OrganizationId); + await next(context); + } + + private void StoreUnavailable(HttpContext context) + { + context.RequestAborted.ThrowIfCancellationRequested(); + TenantAuthenticationDiagnostics.Outcome(logger, TenantAuthenticationOutcome.BindingStoreUnavailable); + Refuse(context); + } + + internal static void Refuse(HttpContext context) + { + if (context.Features.Get() is { } feature) feature.Identity = null; + PublicResponsePolicy.Apply(context.Response); + context.Response.Headers.WWWAuthenticate = "Bearer"; + context.Response.StatusCode = StatusCodes.Status401Unauthorized; + } +} + +/// Qualifies the immutable deployment pair before the HTTP host accepts requests. +public sealed class TenantIdentityAuthorityStartupService(IdentityAuthorityQualification qualification) : IHostedService +{ + public Task StartAsync(CancellationToken cancellationToken) => qualification.QualifyAsync(cancellationToken); + public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; +} + +internal static class TenantIdentityBindingAdmissionExtensions +{ + internal static IServiceCollection AddLearnStackTenantIdentityBindingAdmission(this IServiceCollection services) + { + ArgumentNullException.ThrowIfNull(services); + services.TryAddScoped>(provider => () => provider.GetRequiredService()); + services.TryAddScoped(); + services.AddHostedService(); + return services; + } + + internal static IApplicationBuilder UseLearnStackTenantIdentityBindingAdmission(this IApplicationBuilder app) + { + ArgumentNullException.ThrowIfNull(app); + return app.UseMiddleware(); + } +} diff --git a/backend/src/LearnStack.Api/Authentication/TenantSubjectAdmissionMiddleware.cs b/backend/src/LearnStack.Api/Authentication/TenantSubjectAdmissionMiddleware.cs index 42e9e48d6..60ce16585 100644 --- a/backend/src/LearnStack.Api/Authentication/TenantSubjectAdmissionMiddleware.cs +++ b/backend/src/LearnStack.Api/Authentication/TenantSubjectAdmissionMiddleware.cs @@ -12,17 +12,33 @@ internal sealed class TenantSubjectAdmissionMiddleware(RequestDelegate next, Ten public async Task InvokeAsync(HttpContext context) { ArgumentNullException.ThrowIfNull(context); - if (context.Features.Get() is null - || context.Features.Get()?.Identity is not { } identity) + var feature = context.Features.Get(); + if (feature is not null) feature.Identity = null; + if (context.Features.Get() is null) { await next(context); return; } + var provenance = context.Features.Get(); var outcome = context.Features.Get(); + if (feature?.VerifiedSubject is not { } identity) + { + if (provenance is not null || outcome is not null) TenantIdentityBindingAdmissionMiddleware.Refuse(context); + else await next(context); + return; + } + if ((provenance is null) != (outcome is null) + || provenance is not null && !provenance.Matches(identity)) + { + TenantIdentityBindingAdmissionMiddleware.Refuse(context); + return; + } + if (outcome is null) { outcome = limiter.AttemptAcquire(identity); + context.Features.Set(new TenantSubjectAdmissionProvenance(identity)); context.Features.Set(outcome); if (!outcome.IsAcquired) TenantSubjectAdmissionMetrics.RecordRejected(outcome.Outcome); @@ -53,6 +69,16 @@ public async Task InvokeAsync(HttpContext context) } +/// A cached subject decision can be reused only with its original immutable verified evidence. +internal sealed class TenantSubjectAdmissionProvenance +{ + private readonly VerifiedProviderSubject _subject; + + internal TenantSubjectAdmissionProvenance(VerifiedProviderSubject subject) => _subject = subject; + + internal bool Matches(VerifiedProviderSubject candidate) => ReferenceEquals(_subject, candidate); +} + /// Registers the owned additional subject budget used by the closed tenant HTTP boundary. internal static class TenantSubjectAdmissionExtensions { diff --git a/backend/src/LearnStack.Api/Authentication/TenantSubjectRateLimiter.cs b/backend/src/LearnStack.Api/Authentication/TenantSubjectRateLimiter.cs index b195be8d8..111795dda 100644 --- a/backend/src/LearnStack.Api/Authentication/TenantSubjectRateLimiter.cs +++ b/backend/src/LearnStack.Api/Authentication/TenantSubjectRateLimiter.cs @@ -54,7 +54,7 @@ internal static FixedWindowRateLimiter CreateBudget( QueueProcessingOrder = QueueProcessingOrder.OldestFirst, }); - internal SubjectAdmissionDecision AttemptAcquire(ValidatedTenantIdentity identity) + internal SubjectAdmissionDecision AttemptAcquire(VerifiedProviderSubject identity) { ArgumentNullException.ThrowIfNull(identity); var key = new SubjectKey(identity.Issuer, identity.Subject); diff --git a/backend/src/LearnStack.Api/Authentication/TenantTokenProfile.cs b/backend/src/LearnStack.Api/Authentication/TenantTokenProfile.cs index d6875d5ca..f9a9538e2 100644 --- a/backend/src/LearnStack.Api/Authentication/TenantTokenProfile.cs +++ b/backend/src/LearnStack.Api/Authentication/TenantTokenProfile.cs @@ -1,4 +1,5 @@ using System.Text.Json; +using LearnStack.SharedKernel.Domain; using LearnStack.SharedKernel.Identifiers; namespace LearnStack.Api.Authentication; @@ -73,7 +74,7 @@ public static bool TryReadValidated( string token, TenantAuthenticationOptions settings, DateTimeOffset now, - out ValidatedTenantIdentity? identity, + out VerifiedProviderSubject? identity, out TenantTokenFailure failure ) { @@ -132,18 +133,26 @@ out TenantTokenFailure failure if ( !TryReadNonemptyString(claims, "sub", out var subject) || subject.Length > 255 - || !TryReadUuid(claims, "user_id", out var actor) - || actor == UserId.SystemActor.Value + || !JsonValue.IsStorableText(subject) || !TryReadTenantScope(claims, out var tenantId, out var organizationId) ) { return false; } - identity = new ValidatedTenantIdentity( + UserId? actor = null; + if (claims.ContainsKey("user_id")) + { + if (!TryReadUuid(claims, "user_id", out var actorValue) + || actorValue == UserId.SystemActor.Value) + return false; + actor = UserId.From(actorValue); + } + + identity = new VerifiedProviderSubject( issuer, subject, - UserId.From(actor), + actor, tenantId, organizationId ); diff --git a/backend/src/LearnStack.Api/Authentication/VerifiedProviderSubject.cs b/backend/src/LearnStack.Api/Authentication/VerifiedProviderSubject.cs new file mode 100644 index 000000000..c728b8cc0 --- /dev/null +++ b/backend/src/LearnStack.Api/Authentication/VerifiedProviderSubject.cs @@ -0,0 +1,15 @@ +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.Api.Authentication; + +/// Stock-validated provider evidence; it grants no application actor or tenant authority. +internal sealed record VerifiedProviderSubject( + string Issuer, + string Subject, + UserId? ClaimedActor, + TenantId? TenantId, + OrganizationId? OrganizationId +) +{ + public override string ToString() => nameof(VerifiedProviderSubject); +} diff --git a/backend/src/LearnStack.Api/Composition/CrossCuttingFoundationExtensions.cs b/backend/src/LearnStack.Api/Composition/CrossCuttingFoundationExtensions.cs index 0cf015c80..bd23791c7 100644 --- a/backend/src/LearnStack.Api/Composition/CrossCuttingFoundationExtensions.cs +++ b/backend/src/LearnStack.Api/Composition/CrossCuttingFoundationExtensions.cs @@ -242,6 +242,7 @@ private static void WireOpenTelemetry(WebApplicationBuilder builder, DeploymentM t.AddEntityFrameworkCoreInstrumentation(); t.AddSource("learnstack.*"); t.AddProcessor(); + t.AddProcessor(new IdentityStorageSpanProcessor()); if (exportOverNetwork) { t.AddOtlpExporter(o => o.Endpoint = new Uri(otlpEndpoint!)); diff --git a/backend/src/LearnStack.Api/Composition/IdentityStorageSpanProcessor.cs b/backend/src/LearnStack.Api/Composition/IdentityStorageSpanProcessor.cs new file mode 100644 index 000000000..2fb317136 --- /dev/null +++ b/backend/src/LearnStack.Api/Composition/IdentityStorageSpanProcessor.cs @@ -0,0 +1,11 @@ +using System.Diagnostics; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using OpenTelemetry; + +namespace LearnStack.Api.Composition; + +/// G19's named Identity boundary runs before any trace exporter. +internal sealed class IdentityStorageSpanProcessor : BaseProcessor +{ + public override void OnEnd(Activity data) => IdentityStorageTraceBoundary.ApplyBeforeExport(data); +} diff --git a/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs b/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs index d5fdd895d..44a9191b9 100644 --- a/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs +++ b/backend/src/LearnStack.Api/Composition/PersistenceCompositionExtensions.cs @@ -17,6 +17,8 @@ using LearnStack.Modules.Education.Infrastructure.Persistence; using LearnStack.Modules.Tenancy.Infrastructure; using LearnStack.Modules.Tenancy.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Identifiers; using LearnStack.SharedKernel.Audit; using LearnStack.SharedKernel.Entitlements; using LearnStack.SharedKernel.Persistence; @@ -160,6 +162,9 @@ public static IServiceCollection AddLearnStackPersistence( // Scoped: one connection per request, owned by this, shared by every // context resolved in the scope (ADR-0040). + services.TryAddScoped(); + services.TryAddScoped(provider => + provider.GetRequiredService()); services.TryAddScoped(CreateUnitOfWork); // Every module context goes through the helper. A registration that built @@ -167,6 +172,8 @@ public static IServiceCollection AddLearnStackPersistence( // which never sees SET LOCAL and reads zero rows from every tenant-owned // table — silently. services.AddModuleDbContext(); + services.TryAddScoped(); services.AddTenantSettingsReads(); services.AddTenantSiteReads(); services.AddModuleDbContext(); @@ -180,6 +187,18 @@ public static IServiceCollection AddLearnStackPersistence( // through the same helper is what keeps it on the ambient connection — a context // that opened its own would never see the SET LOCAL the audit insert depends on. services.AddModuleDbContext(); + IdentityAuthorityRegistration? identityAuthority = null; + if (configuration["Identity:AuthorityId"] is { } authority) + { + if (!Guid.TryParseExact(authority, "D", out var authorityId) || authorityId == Guid.Empty) + throw new InvalidOperationException("Identity:AuthorityId requires an explicit nonempty authority UUID."); + identityAuthority = new IdentityAuthorityRegistration(IdentityAuthorityId.From(authorityId), + configuration["Authentication:Tenant:Issuer"] ?? ""); + } + // The API-owned startup service qualifies this immutable pair before + // ordinary existing-binding admission. Internal consumers qualify explicitly. + services.AddIdentityGlobalFoundation(identityAuthority); + services.AddIdentityContextualFoundation(); // ── The audit write path ───────────────────────────────────────────── // @@ -326,7 +345,8 @@ public static IServiceCollection AddLearnStackPersistence( private static IUnitOfWork CreateUnitOfWork(IServiceProvider services) => new NpgsqlUnitOfWork( services.GetRequiredService>().Value, - services.GetRequiredService>()); + services.GetRequiredService>(), + services.GetRequiredService()); /// /// Validates ConnectionStrings:Default and builds the application data diff --git a/backend/src/LearnStack.Api/Program.cs b/backend/src/LearnStack.Api/Program.cs index 98c167cd6..8240b30c7 100644 --- a/backend/src/LearnStack.Api/Program.cs +++ b/backend/src/LearnStack.Api/Program.cs @@ -42,7 +42,8 @@ deploymentMode, typeof(LearnStack.Modules.Tenancy.Application.AssemblyMarker).Assembly, typeof(LearnStack.Modules.Customization.Application.AssemblyMarker).Assembly, - typeof(LearnStack.Modules.Education.Application.AssemblyMarker).Assembly); + typeof(LearnStack.Modules.Education.Application.AssemblyMarker).Assembly, + typeof(LearnStack.Modules.Identity.Application.AssemblyMarker).Assembly); builder.Services.AddLearnStackTenancyEdge(builder.Configuration); builder.Services.AddLearnStackPersistence(builder.Configuration); builder.Services.AddLearnStackRateLimiting(); @@ -53,6 +54,7 @@ builder.Services.AddLearnStackTenantAuthentication( TenantAuthenticationOptions.FromConfiguration(builder.Configuration, deploymentMode)); builder.Services.AddLearnStackTenantSubjectAdmission(); +builder.Services.AddLearnStackTenantIdentityBindingAdmission(); builder.Services.AddAuthorization(); builder.Services.AddSingleton(); @@ -124,8 +126,9 @@ app.UseAuthentication(); app.UseLearnStackTenantCredentialAdmission(); app.UseLearnStackTenantSubjectAdmission(); +app.UseLearnStackTenantIdentityBindingAdmission(); -// Reconcile both trusted signals once, after credential/subject admission. +// Reconcile both trusted signals once, after credential/quota/binding admission. // Authentication precedes resolution; authorization follows header assertions. // Keeping these insertions separate preserves ADR-0036/ADR-0064's order. app.UseLearnStackTenantResolution(); diff --git a/backend/src/LearnStack.Application/Audit/AuditExecutionCoordinator.cs b/backend/src/LearnStack.Application/Audit/AuditExecutionCoordinator.cs index f8a9a9f27..a487d6f1a 100644 --- a/backend/src/LearnStack.Application/Audit/AuditExecutionCoordinator.cs +++ b/backend/src/LearnStack.Application/Audit/AuditExecutionCoordinator.cs @@ -5,6 +5,8 @@ using LearnStack.SharedKernel.Results; using LearnStack.SharedKernel.Tenancy; using LearnStack.SharedKernel.Time; +using LearnStack.SharedKernel.Persistence; +using LearnStack.Application.Persistence; using Microsoft.Extensions.Logging; namespace LearnStack.Application.Audit; @@ -35,7 +37,8 @@ public sealed class AuditExecutionCoordinator( ITenantContext tenantContext, IClock clock, IGuidFactory guidFactory, - ILogger logger) + ILogger logger, + IUnitOfWork unitOfWork) { /// /// Classifies the declared operation before invoking its deferred work. A direct @@ -51,7 +54,7 @@ public async Task ExecuteAsync( { ArgumentNullException.ThrowIfNull(operationType); ArgumentNullException.ThrowIfNull(next); - var jobSourceOwner = JobApplicationSourceOwner.Current; + TransactionExecutionCoordinator.RefuseGlobalIdentityEntry(unitOfWork); // Unregistered is the rejection, and it happens BEFORE the handler runs: an // operation nobody classified is a deployment defect, and letting it commit while @@ -70,6 +73,68 @@ public async Task ExecuteAsync( return Result.FailFor(AuditErrors.UnclassifiedOperation); } + return await ExecuteDeclaredAsync( + () => DeclareAsync(provisioning, registration, cancellationToken), next, false).ConfigureAwait(false); + } + + /// Declares the one central MUST intent only after the prepared owner admitted serialized absence. + public async Task ExecuteGlobalIdentityAsync( + TransactionExecutionCoordinator.PreparedGlobalIdentityOwner owner, + Func> next, + CancellationToken cancellationToken = default) where TResponse : IResultBase + { + ArgumentNullException.ThrowIfNull(owner); + ArgumentNullException.ThrowIfNull(next); + cancellationToken.ThrowIfCancellationRequested(); + owner.RequireCreationEntry(capture); + if (!ReferenceEquals(owner.Unit, unitOfWork) || tenantContext.IsResolved + || tenantContext is EventTenantContext or JobTenantContext || JobApplicationSourceOwner.Current is not null) + throw new InvalidOperationException("Global audit requires its fresh identity owner and unresolved context."); + if (!catalog.TryGetOffPath(GlobalIdentityCreationReference.Operation, out var entry) + || entry.ModuleName != "identity" || entry.OperationClass != OperationClass.Must + || entry.OperationType != OperationType.SecurityEvent || entry.EntityType != owner.Descriptor.EntityType) + { + await owner.DisposeAsync().ConfigureAwait(false); + return Result.FailFor(AuditErrors.UnclassifiedOperation); + } + + GlobalIdentityCreationReference? creation = null; + return await ExecuteDeclaredAsync(() => + { + creation = GlobalCreationSource.Create(owner.Unit, owner.Announcement, + owner.Descriptor.SeedActor ?? UserId.From(guidFactory.NewUuidV7()), + AuditEntryId.From(guidFactory.NewUuidV7()), clock.UtcNow); + capture.DeclareIntent(new AuditIntent(creation.AuditId, TenantId.PlatformSentinel, null, + creation.ActorUserId, tenantContext.CorrelationId, entry.ModuleName, entry.Operation, + entry.OperationType, entry.OperationClass, entry.EntityType, creation.Timestamp) + { + GlobalIdentity = creation, + SubjectId = creation.TargetUserId.Value.ToString("D"), + }); + return Task.CompletedTask; + }, async () => + { + try + { + var response = await next(creation!).ConfigureAwait(false); + if (!owner.HasBeenConsumed) + throw new InvalidOperationException("Global creation must consume its prepared common owner."); + return response; + } + finally + { + if (!owner.HasBeenConsumed) + { + try { await owner.FailBeforeConsumptionAsync().ConfigureAwait(false); } + catch { /* Preserve the original deferred-entry failure; cleanup must not replace it. */ } + } + } + }, true).ConfigureAwait(false); + } + + private async Task ExecuteDeclaredAsync(Func declare, Func> next, + bool globalIdentity) where TResponse : IResultBase + { var outermost = !capture.HasOpenFrame; // A frame per invocation, outermost or nested, so each intent belongs to the @@ -84,8 +149,8 @@ public async Task ExecuteAsync( try { - await DeclareAsync(provisioning, registration, cancellationToken).ConfigureAwait(false); - jobSourceOwner?.RequireBusinessReady(); + await declare().ConfigureAwait(false); + JobApplicationSourceOwner.Current?.RequireBusinessReady(); var response = await next().ConfigureAwait(false); @@ -94,7 +159,7 @@ public async Task ExecuteAsync( // cancelled COMMIT, which reaches neither the catch nor this line, is covered // by the same code as the other two (ADR-0033 Amendment 4 § 2). result = response.IsFailure - ? AuditIntentResult.Refused(OutcomeOf(response.Error!), response.Error!.Message.Key) + ? AuditIntentResult.Refused(globalIdentity ? AuditOutcome.Failed : OutcomeOf(response.Error!), response.Error!.Message.Key) : AuditIntentResult.Succeeded; return response; @@ -205,8 +270,8 @@ private async Task ReconcileAsync() // A FRESH clock reading, not the intent's DeclaredAt: the in-transaction row // that may already exist under this id carries that, and the composite // primary key is what makes the pair legal rather than a 23505. - draft = AuditDraftComposer.Reconciled( - intent, capture.ChangesOf(intent), state, clock.UtcNow); + draft = AuditDraftComposer.Reconciled(intent, capture.ChangesOf(intent), state, + intent.GlobalIdentity?.ReconciliationTimestamp(clock.UtcNow) ?? clock.UtcNow); } catch (Exception refused) { @@ -237,7 +302,12 @@ private async Task ReconcileAsync() // abandoned by what it is cleaning up after. Unbounded only in the sense // that this token is — Npgsql's own connection and command timeouts still // bound the write, so a wedged database cannot hold the request forever. - if (intent.OperationClass == OperationClass.Must) + if (intent.GlobalIdentity is not null) + { + await store.ReconcileGlobalIdentityAsync(intent, capture.ChangesOf(intent), state, + draft.Timestamp, CancellationToken.None).ConfigureAwait(false); + } + else if (intent.OperationClass == OperationClass.Must) { await store.WriteStandaloneAsync(draft, CancellationToken.None).ConfigureAwait(false); } @@ -272,7 +342,8 @@ private async Task ReconcileAsync() // A nested command shares this context, so its failure cannot leak payloads // through a provider/composer exception before the transport sees the fault. private Exception? DiagnosticException(Exception failure) => - AsyncExecutionDiagnostics.IsTrusted(tenantContext) ? null : failure; + capture.Intents.Any(intent => intent.GlobalIdentity is not null) + || AsyncExecutionDiagnostics.IsTrusted(tenantContext) ? null : failure; /// /// Parks one intent per audited (resource, operation). @@ -385,6 +456,13 @@ private async Task DeclareAsync( _ => AuditOutcome.Failed, }; + private sealed class GlobalCreationSource : GlobalIdentityCreationReference.MintingSource + { + internal static GlobalIdentityCreationReference Create(IGlobalIdentityUnitOfWork unit, + LearnStack.SharedKernel.Identity.GlobalIdentityContextAnnouncement announcement, + UserId target, AuditEntryId id, DateTimeOffset timestamp) => Mint(unit, announcement, target, id, timestamp); + } + private static readonly Action LogUnclassified = LoggerMessage.Define( LogLevel.Error, diff --git a/backend/src/LearnStack.Application/Persistence/TransactionExecutionCoordinator.GlobalIdentity.cs b/backend/src/LearnStack.Application/Persistence/TransactionExecutionCoordinator.GlobalIdentity.cs new file mode 100644 index 000000000..f3aaa78d2 --- /dev/null +++ b/backend/src/LearnStack.Application/Persistence/TransactionExecutionCoordinator.GlobalIdentity.cs @@ -0,0 +1,174 @@ +using System.Data.Common; +using LearnStack.Application.Jobs; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; + +namespace LearnStack.Application.Persistence; + +public sealed partial class TransactionExecutionCoordinator +{ + public static Task PrepareGlobalIdentityOwnerAsync( + IUnitOfWork unit, IAuditStateCapture capture, ITenantContext tenantContext, GlobalIdentityOwnerDescriptor descriptor, + CancellationToken cancellationToken = default) + { + BackgroundJobExecutionAdmission.RefusePrivilegedEntry(); + ArgumentNullException.ThrowIfNull(tenantContext); + if (tenantContext.IsResolved || tenantContext is EventTenantContext or JobTenantContext) + throw new InvalidOperationException("Global identity preparation cannot inherit tenant execution."); + return PreparedGlobalIdentityOwner.CreateAsync(unit, capture, descriptor, cancellationToken); + } + + public Task ExecutePreparedGlobalIdentityAsync(PreparedGlobalIdentityOwner owner, + GlobalIdentityCreationReference creation, Func> next, + CancellationToken cancellationToken = default) where TResponse : IResultBase + { + ArgumentNullException.ThrowIfNull(owner); + ArgumentNullException.ThrowIfNull(creation); + ArgumentNullException.ThrowIfNull(next); + BackgroundJobExecutionAdmission.RefusePrivilegedEntry(); + if (tenantContext.IsResolved || capture.Intents.Count != 1 + || !ReferenceEquals(capture.Intents[0].GlobalIdentity, creation) + || !ReferenceEquals(creation.Descriptor, owner.Descriptor)) + throw new InvalidOperationException("Global creation requires its one central intent and unresolved context."); + creation.RequireLive(unitOfWork); + var frame = owner.Consume(unitOfWork, capture); + return ExecuteFrameAsync(frame, null, GlobalIdentityCreationReference.Operation, next, + null, null, null, null, null, null, null, null, null, cancellationToken, owner, creation); + } + +#pragma warning disable CA1034 // Private construction retains the original common owner frame without friend assemblies. + public sealed class PreparedGlobalIdentityOwner : IAsyncDisposable +#pragma warning restore CA1034 + { + private readonly IGlobalIdentityUnitOfWork _unit; + private readonly IAuditStateCapture _capture; + private readonly IUnitOfWorkScope _frame; + private readonly DbConnection _connection; + private readonly DbTransaction _transaction; + private readonly GlobalIdentityContextAnnouncement _announcement; + private bool _absenceAdmitted; + private bool _consumed; + private bool _disposed; + + private PreparedGlobalIdentityOwner(IGlobalIdentityUnitOfWork unit, IAuditStateCapture capture, + IUnitOfWorkScope frame, GlobalIdentityContextAnnouncement announcement) + { + _unit = unit; + _capture = capture; + _frame = frame; + _connection = unit.Connection; + _transaction = unit.Transaction!; + _announcement = announcement; + } + + public GlobalIdentityOwnerDescriptor Descriptor => _announcement.Descriptor; + public AuditIntentState RecordedOutcome { get; private set; } + internal IGlobalIdentityUnitOfWork Unit => _unit; + internal GlobalIdentityContextAnnouncement Announcement => _announcement; + internal bool HasBeenConsumed => _consumed; + + internal static async Task CreateAsync(IUnitOfWork unit, + IAuditStateCapture capture, GlobalIdentityOwnerDescriptor descriptor, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(capture); + ArgumentNullException.ThrowIfNull(descriptor); + if (unit is not IGlobalIdentityUnitOfWork global || unit.HasActiveTransaction || unit.IsRollbackOnly + || capture.HasOpenFrame || capture.Intents.Count != 0 || capture.Changes.Count != 0 + || capture.State != AuditIntentState.None || descriptor.Kind == GlobalIdentityOwnerKind.Lookup) + throw new InvalidOperationException("Global creation preparation requires a fresh unit and capture."); + var frame = await global.BeginGlobalIdentityTransactionAsync(descriptor, TransactionMode.ReadWrite, cancellationToken); + try + { + await global.AcquireGlobalIdentitySubjectLockAsync(descriptor, cancellationToken); + var announcement = global.GetGlobalIdentityAnnouncement(global.Transaction) + ?? throw new InvalidOperationException("Global preparation requires its successful announcement."); + var owner = new PreparedGlobalIdentityOwner(global, capture, frame, announcement); + owner.RequireLive(unit, capture); + return owner; + } + catch + { + unit.MarkRollbackOnly(); + try { await frame.FailAsync(CancellationToken.None); } + catch { /* Preserve preparation failure. */ } + try { await frame.DisposeAsync(); } + catch { /* The owning scope retains connection cleanup. */ } + throw; + } + } + + /// Only the censused internal lock-and-fresh-read path admits serialized absence. + public void AdmitSerializedAbsence() + { + RequireLive(_unit, _capture); + if (_absenceAdmitted || _consumed || _capture.HasOpenFrame || _capture.Intents.Count != 0) + throw new InvalidOperationException("Serialized absence can be admitted only once before audit entry."); + _absenceAdmitted = true; + } + + /// Completes an existing-binding lookup without declaring a creation intent. + public async Task CompleteExistingAsync(CancellationToken cancellationToken = default) + { + RequireLive(_unit, _capture); + if (_absenceAdmitted || _consumed || _capture.HasOpenFrame || _capture.Intents.Count != 0 + || _capture.Changes.Count != 0 || _capture.State != AuditIntentState.None) + throw new InvalidOperationException("An absent binding cannot complete as an existing binding."); + await _unit.ValidateGlobalIdentityConstraintsAsync(Descriptor, cancellationToken); + await _frame.CompleteAsync(cancellationToken); + _disposed = true; + await _frame.DisposeAsync(); + } + + internal void RequireCreationEntry(IAuditStateCapture capture) + { + RequireLive(_unit, capture); + if (!_absenceAdmitted || _consumed || capture.HasOpenFrame || capture.Intents.Count != 0 + || capture.Changes.Count != 0 || capture.State != AuditIntentState.None) + throw new InvalidOperationException("Global audit entry requires this owner's serialized absence."); + } + + internal void RequireLive(IUnitOfWork unit, IAuditStateCapture capture) + { + if (_disposed || !ReferenceEquals(unit, _unit) || !ReferenceEquals(capture, _capture) || !_frame.IsOwner + || !unit.HasActiveTransaction || unit.IsRollbackOnly || unit.Mode != TransactionMode.ReadWrite + || !ReferenceEquals(unit.Connection, _connection) || !ReferenceEquals(unit.Transaction, _transaction) + || _announcement.Generation <= 0 || _unit.GetGlobalIdentityAnnouncement(_transaction) != _announcement) + throw new InvalidOperationException("The prepared global owner no longer matches its live transaction and capture."); + } + + internal IUnitOfWorkScope Consume(IUnitOfWork unit, IAuditStateCapture capture) + { + RequireLive(unit, capture); + if (!_absenceAdmitted || _consumed) + throw new InvalidOperationException("An admitted global owner can be consumed only once."); + _consumed = true; + return _frame; + } + + internal void RecordOutcome(AuditIntentState state) => RecordedOutcome = state; + + internal async Task FailBeforeConsumptionAsync() + { + if (_consumed || _disposed) return; + _unit.MarkRollbackOnly(); + try { await _frame.FailAsync(CancellationToken.None); } + finally + { + RecordedOutcome = AuditIntentState.RolledBack; + _capture.MarkRolledBack(); + _disposed = true; + await _frame.DisposeAsync(); + } + } + + public async ValueTask DisposeAsync() + { + if (_disposed) return; + _disposed = true; + if (!_consumed) await _frame.DisposeAsync(); + } + } +} diff --git a/backend/src/LearnStack.Application/Persistence/TransactionExecutionCoordinator.cs b/backend/src/LearnStack.Application/Persistence/TransactionExecutionCoordinator.cs index acba23556..1e3ad19c9 100644 --- a/backend/src/LearnStack.Application/Persistence/TransactionExecutionCoordinator.cs +++ b/backend/src/LearnStack.Application/Persistence/TransactionExecutionCoordinator.cs @@ -2,8 +2,11 @@ using System.Data.Common; using LearnStack.Application.Messaging; using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Errors; using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Permissions; using LearnStack.SharedKernel.Results; using LearnStack.SharedKernel.Tenancy; using Microsoft.Extensions.Logging; @@ -14,7 +17,7 @@ namespace LearnStack.Application.Persistence; /// Shared transaction entry and owner completion for requests and direct work. /// The outer audit coordinator retains classification/reconciliation ownership. /// -public sealed class TransactionExecutionCoordinator( +public sealed partial class TransactionExecutionCoordinator( IUnitOfWork unitOfWork, ITenantContext tenantContext, IAuditStore auditStore, @@ -52,6 +55,7 @@ private async Task ExecuteCoreAsync( { ArgumentNullException.ThrowIfNull(next); ArgumentException.ThrowIfNullOrWhiteSpace(operationName); + RefuseGlobalIdentityEntry(unitOfWork); BackgroundJobExecutionAdmission.RequireContext(tenantContext, provisioning); BackgroundJobExecutionAdmission.RequireOperation(operationType); var jobCompletion = BackgroundJobExecutionAdmission.RequireOwnerEntry(unitOfWork, mode, operationType, tenantContext); @@ -92,6 +96,7 @@ public static Task PrepareDeliveryOwnerAsync( CancellationToken cancellationToken = default) { BackgroundJobExecutionAdmission.RefusePrivilegedEntry(); + RefuseGlobalIdentityEntry(unitOfWork); return PreparedDeliveryOwner.CreateAsync(unitOfWork, routingContext, cancellationToken); } @@ -105,6 +110,7 @@ public Task ExecutePreparedDeliveryAsync( where TResponse : IResultBase { BackgroundJobExecutionAdmission.RefusePrivilegedEntry(); + RefuseGlobalIdentityEntry(unitOfWork); ArgumentNullException.ThrowIfNull(owner); ArgumentNullException.ThrowIfNull(completion); ArgumentNullException.ThrowIfNull(next); @@ -131,7 +137,9 @@ private async Task ExecuteFrameAsync( RecordBackgroundJobCapacityCleanupCommand? capacityCleanup, BackgroundJobExternalCheckpointOwner? externalCheckpoint, SubmitBackgroundJobRecipientCommand? recipient, - CancellationToken cancellationToken) + CancellationToken cancellationToken, + PreparedGlobalIdentityOwner? globalOwner = null, + GlobalIdentityCreationReference? creation = null) where TResponse : IResultBase { var committing = false; @@ -142,7 +150,13 @@ private async Task ExecuteFrameAsync( BackgroundJobExecutionAdmission.RequireContext(tenantContext, provisioning); // Provisioning changes SQL authority only; the ambient accessor stays // unresolved. A resolved caller cannot announce another tenant here. - if (preparedOwner is not null) + if (globalOwner is not null) + { + globalOwner.RequireLive(unitOfWork, capture); + creation!.RequireLive(unitOfWork); + collector.RefreshTrackedSources(); + } + else if (preparedOwner is not null) { preparedOwner.RequireLive(unitOfWork, tenantContext); collector.RefreshTrackedSources(); @@ -204,7 +218,16 @@ await BackgroundJobExecutionAdmission.BindOwnerAsync(jobCompletion, unitOfWork, await collector.DrainAsync(invocation, cancellationToken); if (invocation.HasProducedWork) _ = producer.RequireAnnouncement(); - await auditStore.WritePendingAsync(unitOfWork, cancellationToken); + if (globalOwner is not null) + { + await auditStore.WriteGlobalIdentityPendingAsync(unitOfWork, creation!, cancellationToken); + await ((IGlobalIdentityUnitOfWork)unitOfWork).ValidateGlobalIdentityConstraintsAsync( + globalOwner.Descriptor, cancellationToken); + } + else + { + await auditStore.WritePendingAsync(unitOfWork, cancellationToken); + } } if (recipient is not null) @@ -276,7 +299,7 @@ await BackgroundJobExecutionAdmission.FenceOwnerAsync(jobCompletion, unitOfWork, } return response; } - catch when (!committing) + catch (Exception dispatchFailure) when (!committing) { failed = true; unitOfWork.MarkRollbackOnly(); @@ -294,7 +317,9 @@ await BackgroundJobExecutionAdmission.FenceOwnerAsync(jobCompletion, unitOfWork, catch (Exception rollbackFailure) { LogRollbackFailure(logger, operationName, - AsyncExecutionDiagnostics.IsTrusted(tenantContext) ? null : rollbackFailure); + globalOwner is not null || typeof(IIdentityPermissionRequest).IsAssignableFrom(operationType) + || dispatchFailure is ProviderException { ProviderName: "identity-storage" } + || AsyncExecutionDiagnostics.IsTrusted(tenantContext) ? null : rollbackFailure); } if (scope.IsOwner && capture.State != AuditIntentState.Indeterminate) @@ -311,10 +336,17 @@ await BackgroundJobExecutionAdmission.FenceOwnerAsync(jobCompletion, unitOfWork, } finally { + globalOwner?.RecordOutcome(capture.State); await CleanupFrameAsync(scope, failed); } } + internal static void RefuseGlobalIdentityEntry(IUnitOfWork unit) + { + if (unit is IGlobalIdentityUnitOfWork { IsGlobalIdentityTransaction: true }) + throw new InvalidOperationException("A global identity owner cannot enter an ordinary execution."); + } + private async ValueTask CleanupFrameAsync(IUnitOfWorkScope scope, bool failed) { // Announcement/setup failures also reach here. Child completion never diff --git a/backend/src/LearnStack.Application/Pipeline/MediatRPipelineRegistration.cs b/backend/src/LearnStack.Application/Pipeline/MediatRPipelineRegistration.cs index 0a7f706fd..41dc64674 100644 --- a/backend/src/LearnStack.Application/Pipeline/MediatRPipelineRegistration.cs +++ b/backend/src/LearnStack.Application/Pipeline/MediatRPipelineRegistration.cs @@ -54,9 +54,15 @@ public static IServiceCollection AddLearnStackMediatRPipeline( // One scoped lifecycle for every entry and both API/Seeder compositions. // Behaviors adapt requests; direct owners reuse these same coordinators. services.TryAddScoped(); + // A pre-context binding reader must not construct creation-only owners + // and pin their transient tenant context before ordinary resolution. + services.TryAddScoped>(provider => + () => provider.GetRequiredService()); services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); + services.TryAddScoped>(provider => + () => provider.GetRequiredService()); services.TryAddSingleton(); // MediatR 12.x throws if no assemblies are registered for handler diff --git a/backend/src/LearnStack.Infrastructure.Audit/AuditStateCapture.cs b/backend/src/LearnStack.Infrastructure.Audit/AuditStateCapture.cs index ff343881d..1daf2dd25 100644 --- a/backend/src/LearnStack.Infrastructure.Audit/AuditStateCapture.cs +++ b/backend/src/LearnStack.Infrastructure.Audit/AuditStateCapture.cs @@ -87,6 +87,11 @@ public void Add(CapturedEntityChange change) { ArgumentNullException.ThrowIfNull(change); + var identity = _intents.SingleOrDefault(intent => intent.GlobalIdentity is not null)?.GlobalIdentity; + if (identity is not null && (change.EntityType != identity.Descriptor.EntityType.Name + || change.EntityId != identity.TargetUserId.Value.ToString("D") || change.BeforeJson is not null)) + throw new InvalidOperationException("Global capture admits only its one new identity target."); + _changes.Add(change); _changeFrames.Add(CurrentFrame); } @@ -121,7 +126,12 @@ public IReadOnlyList ChangesOf(AuditIntent intent) } /// - public void OpenFrame() => _openFrames.Add(++_framesOpened); + public void OpenFrame() + { + if (_intents.Any(intent => intent.GlobalIdentity is not null)) + throw new InvalidOperationException("A global creation capture cannot contain a nested audit frame."); + _openFrames.Add(++_framesOpened); + } /// public void CloseFrame(AuditIntentResult result) @@ -152,6 +162,15 @@ public void DeclareIntent(AuditIntent intent) { ArgumentNullException.ThrowIfNull(intent); + if (intent.GlobalIdentity is { } identity) + { + identity.RequireIntent(intent); + if (_openFrames.Count != 1 || _intents.Count != 0 || _changes.Count != 0 || State != AuditIntentState.None) + throw new InvalidOperationException("Global creation requires one fresh central audit frame."); + } + else if (_intents.Any(existing => existing.GlobalIdentity is not null)) + throw new InvalidOperationException("An ordinary intent cannot join global identity creation."); + _intents.Add(intent); _intentFrames.Add(CurrentFrame); diff --git a/backend/src/LearnStack.Infrastructure.Audit/Capture/AuditChangeTrackerInterceptor.cs b/backend/src/LearnStack.Infrastructure.Audit/Capture/AuditChangeTrackerInterceptor.cs index 4b81bda64..3fa359f71 100644 --- a/backend/src/LearnStack.Infrastructure.Audit/Capture/AuditChangeTrackerInterceptor.cs +++ b/backend/src/LearnStack.Infrastructure.Audit/Capture/AuditChangeTrackerInterceptor.cs @@ -9,6 +9,7 @@ using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace LearnStack.Infrastructure.Audit.Capture; @@ -49,7 +50,8 @@ namespace LearnStack.Infrastructure.Audit.Capture; /// changed — which is the fact a reviewer is usually asking about. /// /// -public sealed class AuditChangeTrackerInterceptor(IAuditStateCapture capture) +public sealed class AuditChangeTrackerInterceptor(IAuditStateCapture capture, + LearnStack.SharedKernel.Persistence.IUnitOfWork unitOfWork) : SaveChangesInterceptor { /// @@ -240,6 +242,27 @@ public void Capture(DbContext? context) return; } + var identity = capture.Intents.SingleOrDefault(intent => intent.GlobalIdentity is not null)?.GlobalIdentity; + if (unitOfWork is LearnStack.SharedKernel.Persistence.IGlobalIdentityUnitOfWork { IsGlobalIdentityTransaction: true } global) + { + if (identity is null || !global.IsGlobalIdentityContextEnrolled(context, unitOfWork.Transaction) + || context.GetType() != identity.Descriptor.ContextType) + throw new InvalidOperationException("Global identity capture requires its enrolled context and central creation intent."); + if (!ReferenceEquals(context.Database.CurrentTransaction?.GetDbTransaction(), unitOfWork.Transaction) + || !ReferenceEquals(context.Database.GetDbConnection(), unitOfWork.Connection)) + throw new InvalidOperationException("Global identity capture requires its original physical transaction and connection."); + identity.RequireLive(unitOfWork); + var changed = context.ChangeTracker.Entries() + .Where(entry => entry.State is EntityState.Added or EntityState.Modified or EntityState.Deleted).ToArray(); + if (changed.Length != 1 || changed[0].State != EntityState.Added + || changed[0].Metadata.ClrType != identity.Descriptor.EntityType + || changed[0].Entity is not IAggregateRoot target + || target.Id != identity.TargetUserId) + throw new InvalidOperationException("Global identity capture admits only its one new User."); + } + else if (identity is not null) + throw new InvalidOperationException("Global identity capture lost its physical owner."); + // BEFORE the save, which is the only moment both states exist: after it, EF has // accepted the changes and OriginalValues equals CurrentValues. Every tracked entry // and not only the changed ones, because the root a changed band belongs to may be diff --git a/backend/src/LearnStack.Infrastructure.Audit/IdentityCreationWitnessInstaller.cs b/backend/src/LearnStack.Infrastructure.Audit/IdentityCreationWitnessInstaller.cs new file mode 100644 index 000000000..2cd564ba8 --- /dev/null +++ b/backend/src/LearnStack.Infrastructure.Audit/IdentityCreationWitnessInstaller.cs @@ -0,0 +1,170 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Infrastructure.Audit; + +/// ADR-0072's exact migration-only witness installer; it owns all global audit SQL. +public static class IdentityCreationWitnessInstaller +{ + public static void Install(MigrationBuilder migrationBuilder) + { + ArgumentNullException.ThrowIfNull(migrationBuilder); + migrationBuilder.Sql(InstallSql); + } + + public static void Remove(MigrationBuilder migrationBuilder) + { + ArgumentNullException.ThrowIfNull(migrationBuilder); + migrationBuilder.Sql(""" + DROP TRIGGER IF EXISTS tg_users_creation_audit ON public.users; + DROP TRIGGER IF EXISTS tg_audit_log_identity_creation ON public.audit_log; + DROP TRIGGER IF EXISTS tg_audit_log_identity_insert ON public.audit_log; + DROP FUNCTION IF EXISTS public.fn_identity_user_creation_audit_guard(); + DROP FUNCTION IF EXISTS public.fn_identity_audit_creation_guard(); + DROP FUNCTION IF EXISTS public.fn_identity_audit_insert_guard(); + DROP FUNCTION IF EXISTS public.fn_identity_audit_evidence(uuid,timestamptz,uuid,bytea,uuid,text,text); + ALTER POLICY audit_log_isolation ON public.audit_log + 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 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)); + """); + } + + private const string InstallSql = """ + DO $$ BEGIN + IF to_regclass('public.audit_log') IS NULL OR to_regclass('public.users') IS NULL THEN + RAISE EXCEPTION 'Identity creation requires the existing Audit and User schema.' USING ERRCODE='23514'; + END IF; + END $$; + + ALTER POLICY audit_log_isolation ON public.audit_log + 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 current_setting('app.scope',true)='tenant')) + OR (current_user='learnstack_migration' + AND tenant_id='00000000-0000-7000-8000-000000000002'::uuid + AND organization_id IS NULL AND module='identity' AND operation='identity.user.create' + AND operation_class='Must' AND operation_type='SecurityEvent' AND entity_type='User' + AND outcome IN ('success','failed','indeterminate') + AND metadata->>'identity_source' IN ('identity-bootstrap','identity-seed-adoption') + AND metadata->>'identity_authority_id'=NULLIF(current_setting('app.identity_authority_id',true),'') + AND metadata->>'identity_subject_key'=NULLIF(current_setting('app.identity_subject_key',true),''))) + WITH CHECK ( + (tenant_id = NULLIF(current_setting('app.tenant_id',true),'')::uuid + AND ((organization_id IS NULL AND NULLIF(current_setting('app.organization_id',true),'') IS NULL) + OR organization_id = NULLIF(current_setting('app.organization_id',true),'')::uuid)) + OR (current_user='learnstack_app' + AND tenant_id='00000000-0000-7000-8000-000000000002'::uuid + AND organization_id IS NULL AND module='identity' AND operation='identity.user.create' + AND operation_class='Must' AND operation_type='SecurityEvent' AND entity_type='User' + AND outcome IN ('success','failed','indeterminate') + AND metadata->>'identity_source' IN ('identity-bootstrap','identity-seed-adoption') + AND metadata->>'identity_authority_id'=NULLIF(current_setting('app.identity_authority_id',true),'') + AND metadata->>'identity_subject_key'=NULLIF(current_setting('app.identity_subject_key',true),''))); + + CREATE FUNCTION public.fn_identity_audit_insert_guard() RETURNS trigger + LANGUAGE plpgsql SECURITY INVOKER SET search_path=pg_catalog AS $$ + BEGIN + IF NEW.operation='identity.user.create' + OR (NEW.tenant_id='00000000-0000-7000-8000-000000000002'::uuid AND current_user='learnstack_app') THEN + IF current_user<>'learnstack_app' + OR NEW.tenant_id<>'00000000-0000-7000-8000-000000000002'::uuid + OR NEW.organization_id IS NOT NULL OR NEW.module<>'identity' + OR NEW.operation<>'identity.user.create' OR NEW.operation_class<>'Must' + OR NEW.operation_type<>'SecurityEvent' OR NEW.entity_type IS DISTINCT FROM 'User' + OR NEW.entity_id IS NULL OR NEW.entity_id !~ '^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$' + OR NEW.outcome NOT IN ('success','failed','indeterminate') + OR NEW.reason IS NOT NULL OR NEW.actor_email IS NOT NULL OR NEW.ip_address IS NOT NULL OR NEW.user_agent IS NOT NULL + OR NEW.metadata IS NULL OR jsonb_typeof(NEW.metadata)<>'object' + OR (NEW.metadata - ARRAY['identity_authority_id','identity_subject_key','identity_source'])<>'{}'::jsonb + OR NEW.metadata->>'identity_authority_id' IS DISTINCT FROM NULLIF(current_setting('app.identity_authority_id',true),'') + OR NEW.metadata->>'identity_subject_key' IS DISTINCT FROM NULLIF(current_setting('app.identity_subject_key',true),'') + OR COALESCE(NEW.metadata->>'identity_authority_id','') !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + OR COALESCE(NEW.metadata->>'identity_subject_key','') !~ '^[0-9a-f]{64}$' + OR NOT COALESCE((NEW.metadata->>'identity_source'='identity-bootstrap' AND NEW.actor_user_id IS NULL) + OR (NEW.metadata->>'identity_source'='identity-seed-adoption' + AND NEW.actor_user_id='00000000-0000-7000-8000-000000000001'::uuid),false) THEN + RAISE EXCEPTION 'Global identity audit attribution is invalid.' USING ERRCODE='23514'; + END IF; + END IF; + RETURN NEW; + END $$; + REVOKE ALL ON FUNCTION public.fn_identity_audit_insert_guard() FROM PUBLIC; + CREATE TRIGGER tg_audit_log_identity_insert BEFORE INSERT ON public.audit_log + FOR EACH ROW EXECUTE FUNCTION public.fn_identity_audit_insert_guard(); + + CREATE FUNCTION public.fn_identity_user_creation_audit_guard() RETURNS trigger + LANGUAGE plpgsql SECURITY DEFINER VOLATILE SET search_path=pg_catalog AS $$ + BEGIN + IF TG_TABLE_SCHEMA<>'public' OR TG_TABLE_NAME<>'users' OR TG_OP<>'INSERT' + OR NEW.authority_id::text IS DISTINCT FROM NULLIF(current_setting('app.identity_authority_id',true),'') + OR encode(NEW.subject_key,'hex') IS DISTINCT FROM NULLIF(current_setting('app.identity_subject_key',true),'') + OR NOT EXISTS (SELECT 1 FROM public.audit_log a + WHERE a.id=NEW.creation_audit_id AND a.timestamp=NEW.creation_audit_timestamp + AND a.tenant_id='00000000-0000-7000-8000-000000000002'::uuid AND a.organization_id IS NULL + AND a.module='identity' AND a.operation='identity.user.create' + AND a.operation_class='Must' AND a.operation_type='SecurityEvent' + AND a.entity_type='User' AND a.entity_id=NEW.id::text AND a.outcome='success' + AND a.metadata->>'identity_authority_id'=NEW.authority_id::text + AND a.metadata->>'identity_subject_key'=encode(NEW.subject_key,'hex') + AND a.metadata->>'identity_source' IN ('identity-bootstrap','identity-seed-adoption')) THEN + RAISE EXCEPTION 'User creation requires its matching durable audit.' USING ERRCODE='23514'; + END IF; + RETURN NULL; + END $$; + REVOKE ALL ON FUNCTION public.fn_identity_user_creation_audit_guard() FROM PUBLIC; + CREATE CONSTRAINT TRIGGER tg_users_creation_audit AFTER INSERT ON public.users + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION public.fn_identity_user_creation_audit_guard(); + + CREATE FUNCTION public.fn_identity_audit_creation_guard() RETURNS trigger + LANGUAGE plpgsql SECURITY DEFINER VOLATILE SET search_path=pg_catalog AS $$ + BEGIN + IF NEW.operation<>'identity.user.create' THEN RETURN NULL; END IF; + IF NEW.metadata->>'identity_authority_id' IS DISTINCT FROM NULLIF(current_setting('app.identity_authority_id',true),'') + OR NEW.metadata->>'identity_subject_key' IS DISTINCT FROM NULLIF(current_setting('app.identity_subject_key',true),'') + OR (NEW.outcome='success' AND NOT EXISTS (SELECT 1 FROM public.users u + WHERE u.id::text=NEW.entity_id AND u.creation_audit_id=NEW.id + AND u.creation_audit_timestamp=NEW.timestamp + AND u.authority_id::text=NEW.metadata->>'identity_authority_id' + AND encode(u.subject_key,'hex')=NEW.metadata->>'identity_subject_key')) THEN + RAISE EXCEPTION 'Global creation audit requires its exact creation witness.' USING ERRCODE='23514'; + END IF; + RETURN NULL; + END $$; + REVOKE ALL ON FUNCTION public.fn_identity_audit_creation_guard() FROM PUBLIC; + CREATE CONSTRAINT TRIGGER tg_audit_log_identity_creation AFTER INSERT ON public.audit_log + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW + EXECUTE FUNCTION public.fn_identity_audit_creation_guard(); + + CREATE FUNCTION public.fn_identity_audit_evidence(p_id uuid,p_timestamp timestamptz, + p_authority_id uuid,p_subject_key bytea,p_target_id uuid,p_source text,p_outcome text) + RETURNS boolean LANGUAGE plpgsql SECURITY DEFINER VOLATILE SET search_path=pg_catalog AS $$ + BEGIN + IF p_authority_id::text IS DISTINCT FROM NULLIF(current_setting('app.identity_authority_id',true),'') + OR encode(p_subject_key,'hex') IS DISTINCT FROM NULLIF(current_setting('app.identity_subject_key',true),'') + OR octet_length(p_subject_key) IS DISTINCT FROM 32 + OR p_source IS NULL OR p_source NOT IN ('identity-bootstrap','identity-seed-adoption') + OR p_outcome IS NULL OR p_outcome NOT IN ('success','failed','indeterminate') THEN RETURN false; END IF; + RETURN EXISTS (SELECT 1 FROM public.audit_log a + WHERE a.id=p_id AND a.timestamp=p_timestamp + AND a.tenant_id='00000000-0000-7000-8000-000000000002'::uuid AND a.organization_id IS NULL + AND a.module='identity' AND a.operation='identity.user.create' + AND a.operation_class='Must' AND a.operation_type='SecurityEvent' + AND a.entity_type='User' AND a.entity_id=p_target_id::text AND a.outcome=p_outcome + AND a.metadata->>'identity_authority_id'=p_authority_id::text + AND a.metadata->>'identity_subject_key'=encode(p_subject_key,'hex') + AND a.metadata->>'identity_source'=p_source + AND ((p_source='identity-bootstrap' AND a.actor_user_id IS NULL) + OR (p_source='identity-seed-adoption' AND a.actor_user_id='00000000-0000-7000-8000-000000000001'::uuid)) + AND (p_outcome<>'success' OR EXISTS (SELECT 1 FROM public.users u + WHERE u.id=p_target_id AND u.authority_id=p_authority_id AND u.subject_key=p_subject_key + AND u.creation_audit_id=p_id AND u.creation_audit_timestamp=p_timestamp))); + END $$; + REVOKE ALL ON FUNCTION public.fn_identity_audit_evidence(uuid,timestamptz,uuid,bytea,uuid,text,text) FROM PUBLIC; + GRANT EXECUTE ON FUNCTION public.fn_identity_audit_evidence(uuid,timestamptz,uuid,bytea,uuid,text,text) TO learnstack_app; + """; +} diff --git a/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.GlobalIdentity.cs b/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.GlobalIdentity.cs new file mode 100644 index 000000000..18dcf93fa --- /dev/null +++ b/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.GlobalIdentity.cs @@ -0,0 +1,164 @@ +using System.Data; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Persistence; +using Microsoft.Extensions.Logging; +using Npgsql; + +namespace LearnStack.Infrastructure.Audit; + +public sealed partial class PostgresAuditStore +{ + public async Task WriteGlobalIdentityPendingAsync(IUnitOfWork unitOfWork, + GlobalIdentityCreationReference creation, CancellationToken cancellationToken = default) + { + JobApplicationSourceOwner.RefuseExternalEntry(); + ArgumentNullException.ThrowIfNull(creation); + creation.RequireLive(unitOfWork); + if (!_capture.HasOpenFrame || _capture.Intents.Count != 1 + || !ReferenceEquals(_capture.Intents[0].GlobalIdentity, creation) + || _capture.State != AuditIntentState.Pending) + throw new ArgumentException("Global pending audit requires its single captured creation intent.", nameof(creation)); + RequireGlobalCatalog(creation); + var intent = _capture.Intents[0]; + var draft = AuditDraftComposer.InTransaction(intent, _capture.ChangesOf(intent)); + if (draft.Outcome != AuditOutcome.Success) + throw new ArgumentException("Only successful creation can use the global pending seam.", nameof(creation)); + try + { + await using var command = unitOfWork.Connection.CreateCommand(); + command.CommandTimeout = 10; + command.Transaction = unitOfWork.Transaction; + command.CommandText = InsertSql; + Bind(command.Parameters, draft); + await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + _capture.MarkWrittenInTransaction(); + } + catch (System.Data.Common.DbException failure) + { + throw new AuditWriteFailedException("The global creation audit could not be written on its owner.", failure); + } + } + + public async Task ReconcileGlobalIdentityAsync(AuditIntent intent, IReadOnlyList changes, + AuditIntentState state, DateTimeOffset timestamp, CancellationToken cancellationToken = default) + { + JobApplicationSourceOwner.RefuseExternalEntry(); + ArgumentNullException.ThrowIfNull(intent); + var creation = intent.GlobalIdentity + ?? throw new ArgumentException("Global reconciliation requires captured creation attribution.", nameof(intent)); + creation.RequireIntent(intent); + if (_globalEnrollment.IsActive || _capture.HasOpenFrame || _capture.Intents.Count != 1 || !ReferenceEquals(_capture.Intents[0], intent) + || state != _capture.State || state is not (AuditIntentState.RolledBack or AuditIntentState.Indeterminate) + || intent.Result is null || timestamp == creation.Timestamp + || timestamp != GlobalIdentityCreationReference.NormalizeTimestamp(timestamp) + || !changes.SequenceEqual(_capture.ChangesOf(intent))) + throw new ArgumentException("Global reconciliation requires this capture's closed non-success attempt.", nameof(intent)); + RequireGlobalCatalog(creation); + var draft = AuditDraftComposer.Reconciled(intent, changes, state, timestamp); + if (draft.Outcome is not (AuditOutcome.Failed or AuditOutcome.Indeterminate)) + throw new ArgumentException("Global reconciliation cannot assert creation success.", nameof(intent)); + + using var budget = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + budget.CancelAfter(TimeSpan.FromSeconds(10)); + try + { + try + { + await WriteGlobalIdentityTransactionAsync(creation, draft, budget.Token).ConfigureAwait(false); + } + catch (PostgresException duplicate) when (duplicate.SqlState == PostgresErrorCodes.UniqueViolation) + { + // The failed INSERT transaction is disposed before evidence uses a clean transaction. + if (!await HasGlobalIdentityEvidenceAsync(creation, draft, budget.Token).ConfigureAwait(false)) + throw new AuditWriteFailedException("The duplicate global audit key has no exact durable evidence.", duplicate); + LogGlobalDuplicate(_logger, null); + _durableDuplicates.Add(1, new KeyValuePair("operation", GlobalIdentityCreationReference.Operation)); + } + _health.ReportStandaloneWriteSucceeded(); + } + catch (Exception failure) + { + LogGlobalWriteFailed(_logger, null); + _standaloneWriteFailures.Add(1, new KeyValuePair("operation", GlobalIdentityCreationReference.Operation)); + _health.ReportStandaloneWriteFailed(GlobalIdentityCreationReference.Operation); + if (failure is System.Data.Common.DbException) + throw new AuditWriteFailedException("The global creation attempt could not be reconciled.", failure); + throw; + } + } + + private void RequireGlobalCatalog(GlobalIdentityCreationReference creation) + { + if (!_catalog.TryGetOffPath(GlobalIdentityCreationReference.Operation, out var entry) + || entry.ModuleName != "identity" || entry.OperationClass != OperationClass.Must + || entry.OperationType != OperationType.SecurityEvent || entry.EntityType != creation.Descriptor.EntityType) + throw new ArgumentException("Global creation requires its exact central MUST catalogue entry."); + } + + private async Task WriteGlobalIdentityTransactionAsync(GlobalIdentityCreationReference creation, + AuditEntryDraft draft, CancellationToken cancellationToken) + { + await using var connection = await _dataSource.Value.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); + await using var transaction = await connection.BeginTransactionAsync(IsolationLevel.ReadCommitted, cancellationToken).ConfigureAwait(false); + await AnnounceGlobalIdentityAsync(connection, transaction, creation, cancellationToken).ConfigureAwait(false); + await using var command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = InsertSql; + Bind(command.Parameters, draft); + await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + command.CommandText = "SET CONSTRAINTS ALL IMMEDIATE"; + command.Parameters.Clear(); + await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + } + + private async Task HasGlobalIdentityEvidenceAsync(GlobalIdentityCreationReference creation, + AuditEntryDraft draft, CancellationToken cancellationToken) + { + await using var connection = await _dataSource.Value.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); + await using var transaction = await connection.BeginTransactionAsync(IsolationLevel.ReadCommitted, cancellationToken).ConfigureAwait(false); + await using (var setup = new NpgsqlCommand("SET TRANSACTION READ ONLY", connection, transaction)) + await setup.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + await AnnounceGlobalIdentityAsync(connection, transaction, creation, cancellationToken).ConfigureAwait(false); + await using var command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = """ + SELECT public.fn_identity_audit_evidence(@id, @timestamp, @authority_id, @subject_key, @target_id, @source, @outcome) + """; + Add(command.Parameters, "id", creation.AuditId.Value); + Add(command.Parameters, "timestamp", draft.Timestamp); + Add(command.Parameters, "authority_id", creation.AuthorityId.Value); + Add(command.Parameters, "subject_key", creation.SubjectKey.ToByteArray()); + Add(command.Parameters, "target_id", creation.TargetUserId.Value); + Add(command.Parameters, "source", creation.Source); + Add(command.Parameters, "outcome", draft.Outcome.ToString().ToLowerInvariant()); + var matches = await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false) is true; + await transaction.CommitAsync(cancellationToken).ConfigureAwait(false); + return matches; + } + + private static async Task AnnounceGlobalIdentityAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, + GlobalIdentityCreationReference creation, CancellationToken cancellationToken) + { + await using var command = connection.CreateCommand(); + command.Transaction = transaction; + command.CommandText = """ + SELECT set_config('app.tenant_id', '', true), set_config('app.organization_id', '', true), + set_config('app.scope', '', true), set_config('app.resolving_host', '', true), + set_config('app.identity_authority_id', @authority, true), + set_config('app.identity_subject_key', @subject_key, true) + """; + Add(command.Parameters, "authority", creation.AuthorityId.Value.ToString("D")); + Add(command.Parameters, "subject_key", creation.SubjectKey.Hex); + await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + } + + private static readonly Action LogGlobalDuplicate = LoggerMessage.Define( + LogLevel.Warning, new EventId(4, nameof(LogGlobalDuplicate)), + "An exact non-success global audit row is already durable. This does not establish the business transaction outcome."); + + private static readonly Action LogGlobalWriteFailed = LoggerMessage.Define( + LogLevel.Critical, new EventId(5, nameof(LogGlobalWriteFailed)), + "The global identity attempt audit could not be reconciled. Audit health is unhealthy."); +} diff --git a/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs b/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs index 7d2ecfd3c..04286b1b3 100644 --- a/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs +++ b/backend/src/LearnStack.Infrastructure.Audit/PostgresAuditStore.cs @@ -4,6 +4,7 @@ using LearnStack.SharedKernel.Audit; using LearnStack.SharedKernel.Identifiers; using LearnStack.SharedKernel.Jobs; +using LearnStack.SharedKernel.Identity; using LearnStack.SharedKernel.Persistence; using LearnStack.SharedKernel.Tenancy; using System.Diagnostics.Metrics; @@ -38,7 +39,7 @@ namespace LearnStack.Infrastructure.Audit; /// 3 § 2). /// /// -public sealed class PostgresAuditStore : IAuditStore +public sealed partial class PostgresAuditStore : IAuditStore { /// The meter every audit-write counter hangs off. public const string MeterName = "LearnStack.Audit"; @@ -78,6 +79,7 @@ public sealed class PostgresAuditStore : IAuditStore private readonly IAuditHealth _health; private readonly IAuditCatalog _catalog; private readonly ITenantContextAccessor _tenantAccessor; + private readonly IGlobalIdentityEnrollment _globalEnrollment; private readonly Counter _durableDuplicates; private readonly Counter _standaloneWriteFailures; @@ -88,7 +90,8 @@ public PostgresAuditStore( IMeterFactory meterFactory, IAuditHealth health, IAuditCatalog catalog, - ITenantContextAccessor tenantAccessor) + ITenantContextAccessor tenantAccessor, + IGlobalIdentityEnrollment globalEnrollment) { ArgumentNullException.ThrowIfNull(meterFactory); @@ -100,6 +103,7 @@ public PostgresAuditStore( // Context controls diagnostics only. Row authority still comes exclusively // from the caller's classified draft/intent, including unresolved provisioning. _tenantAccessor = tenantAccessor ?? throw new ArgumentNullException(nameof(tenantAccessor)); + _globalEnrollment = globalEnrollment ?? throw new ArgumentNullException(nameof(globalEnrollment)); var meter = meterFactory.Create(MeterName); _durableDuplicates = meter.CreateCounter(DurableDuplicateCounterName); @@ -139,6 +143,11 @@ public async Task WritePendingAsync( JobApplicationSourceOwner.RefuseExternalEntry(); ArgumentNullException.ThrowIfNull(unitOfWork); + if (_globalEnrollment.IsActive || unitOfWork is IGlobalIdentityUnitOfWork { IsGlobalIdentityTransaction: true } + || _capture.Intents.Any(intent => intent.GlobalIdentity is not null + || intent.TenantId == TenantId.PlatformSentinel)) + throw new ArgumentException("Ordinary pending audit cannot carry global identity or sentinel attribution.", nameof(unitOfWork)); + var pending = _capture.Intents .Where(intent => intent.OperationClass == OperationClass.Must) .ToList(); @@ -209,6 +218,7 @@ public async Task WriteStandaloneAsync( { JobApplicationSourceOwner.RefuseExternalEntry(); ArgumentNullException.ThrowIfNull(entry); + RefuseGlobalCapture(); EnsureNotPlatformScope(entry); try @@ -326,6 +336,7 @@ public async Task WriteBestEffortAsync( { JobApplicationSourceOwner.RefuseExternalEntry(); ArgumentNullException.ThrowIfNull(entry); + RefuseGlobalCapture(); EnsureNotPlatformScope(entry); try @@ -367,9 +378,13 @@ public async Task WritePlatformScopeAsync( { JobApplicationSourceOwner.RefuseExternalEntry(); ArgumentNullException.ThrowIfNull(entry); + RefuseGlobalCapture(); ArgumentNullException.ThrowIfNull(connection); ArgumentNullException.ThrowIfNull(transaction); + if (entry.ModuleName == "identity" || entry.Operation == GlobalIdentityCreationReference.Operation) + throw new ArgumentException("Global identity creation cannot use the platform audit seam.", nameof(entry)); + // The caller's connection and the caller's transaction, because the row runs as // learnstack_platform under the sentinel tenant and the request's transaction is // the wrong lifetime for a record that must outlive it. No announcement is issued @@ -403,6 +418,7 @@ public async Task WriteEventTerminalAsync( CancellationToken cancellationToken = default) { JobApplicationSourceOwner.RefuseExternalEntry(); + RefuseGlobalCapture(); ArgumentNullException.ThrowIfNull(transition); transition.EnsureMatches(entry, connection, transaction); @@ -446,6 +462,7 @@ public async Task WriteJobTerminalAsync( CancellationToken cancellationToken = default) { JobApplicationSourceOwner.RefuseExternalEntry(); + RefuseGlobalCapture(); ArgumentNullException.ThrowIfNull(transition); transition.EnsureMatches(entry, connection, transaction); const string operation = "platform.job.dead_letter"; @@ -602,6 +619,12 @@ private static void Bind(DbParameterCollection parameters, AuditEntryDraft entry private static void Add(DbParameterCollection parameters, string name, object? value) => parameters.Add(new NpgsqlParameter(name, value ?? DBNull.Value)); + private void RefuseGlobalCapture() + { + if (_globalEnrollment.IsActive || _capture.Intents.Any(intent => intent.GlobalIdentity is not null)) + throw new ArgumentException("A global identity capture cannot use an ordinary or platform audit seam."); + } + /// /// Binds a jsonb parameter, typed explicitly. /// diff --git a/backend/src/LearnStack.Infrastructure/DataProtection/PersonalDataClassificationConvention.cs b/backend/src/LearnStack.Infrastructure/DataProtection/PersonalDataClassificationConvention.cs new file mode 100644 index 000000000..f807cecfc --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/DataProtection/PersonalDataClassificationConvention.cs @@ -0,0 +1,16 @@ +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Microsoft.EntityFrameworkCore.Metadata.Conventions; + +namespace LearnStack.Infrastructure.DataProtection; + +/// Rejects incomplete opted-in models after normal model construction and customization. +internal sealed class PersonalDataClassificationConvention : IModelFinalizingConvention +{ + public void ProcessModelFinalizing(IConventionModelBuilder modelBuilder, + IConventionContext context) + { + if (PersonalDataModelCensus.Inspect(modelBuilder.Metadata).Count != 0) + throw new InvalidOperationException(PersonalDataModelCensus.FailureMessage); + modelBuilder.HasAnnotation(PersonalDataClassificationExtensions.ValidatedModelAnnotation, true); + } +} diff --git a/backend/src/LearnStack.Infrastructure/DataProtection/PersonalDataClassificationExtensions.cs b/backend/src/LearnStack.Infrastructure/DataProtection/PersonalDataClassificationExtensions.cs new file mode 100644 index 000000000..04944e407 --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/DataProtection/PersonalDataClassificationExtensions.cs @@ -0,0 +1,83 @@ +using LearnStack.SharedKernel.DataProtection; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace LearnStack.Infrastructure.DataProtection; + +/// Reviewed property declarations, separate from snapshot redaction markers. +public static class PersonalDataClassificationExtensions +{ + public const string CategoryAnnotation = "LearnStack:PersonalData:Category"; + public const string PurposeAnnotation = "LearnStack:PersonalData:Purpose"; + public const string ValidatedModelAnnotation = "LearnStack:PersonalData:Validated"; + public const int MaximumPurposeLength = 256; + + public static PropertyBuilder HasPersonalData( + this PropertyBuilder builder, PersonalDataCategory category, string purpose) + { + ArgumentNullException.ThrowIfNull(builder); + Declare(builder.Metadata, category, purpose); + return builder; + } + + public static PropertyBuilder HasPersonalData( + this PropertyBuilder builder, PersonalDataCategory category, string purpose) + { + ArgumentNullException.ThrowIfNull(builder); + Declare(builder.Metadata, category, purpose); + return builder; + } + + /// Classifies existing scalar mappings; a misspelling never creates a shadow property. + public static EntityTypeBuilder DeclarePersonalData( + this EntityTypeBuilder builder, PersonalDataCategory category, + string purpose, params string[] propertyNames) where TEntity : class + { + ArgumentNullException.ThrowIfNull(builder); + ArgumentNullException.ThrowIfNull(propertyNames); + if (propertyNames.Length == 0) Refuse(); + var properties = propertyNames.Select(name => builder.Metadata.FindProperty(name) + ?? throw new InvalidOperationException(PersonalDataModelCensus.FailureMessage)).ToArray(); + // Validate the whole declaration before changing any property. + foreach (var property in properties) ValidateDeclaration(property, category, purpose); + foreach (var property in properties) SetDeclaration(property, category, purpose); + return builder; + } + + /// Opts this context into completeness validation before its model can be used. + public static ModelConfigurationBuilder UsePersonalDataClassification(this ModelConfigurationBuilder builder) + { + ArgumentNullException.ThrowIfNull(builder); + builder.Conventions.Add(_ => new PersonalDataClassificationConvention()); + return builder; + } + + internal static bool IsValidPurpose(object? purpose) => + purpose is string text && !string.IsNullOrWhiteSpace(text) && text.Length <= MaximumPurposeLength; + + private static void Declare(IMutableProperty property, PersonalDataCategory category, string purpose) + { + ValidateDeclaration(property, category, purpose); + SetDeclaration(property, category, purpose); + } + + private static void ValidateDeclaration(IMutableProperty property, PersonalDataCategory category, string purpose) + { + if (!Enum.IsDefined(category) || !IsValidPurpose(purpose)) Refuse(); + var previousCategory = property.FindAnnotation(CategoryAnnotation); + var previousPurpose = property.FindAnnotation(PurposeAnnotation); + if ((previousCategory is not null || previousPurpose is not null) + && (!Equals(previousCategory?.Value, category) + || !string.Equals(previousPurpose?.Value as string, purpose, StringComparison.Ordinal))) + Refuse(); + } + + private static void SetDeclaration(IMutableProperty property, PersonalDataCategory category, string purpose) + { + property.SetAnnotation(CategoryAnnotation, category); + property.SetAnnotation(PurposeAnnotation, purpose); + } + + private static void Refuse() => throw new InvalidOperationException(PersonalDataModelCensus.FailureMessage); +} diff --git a/backend/src/LearnStack.Infrastructure/DataProtection/PersonalDataModelCensus.cs b/backend/src/LearnStack.Infrastructure/DataProtection/PersonalDataModelCensus.cs new file mode 100644 index 000000000..b051c2d13 --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/DataProtection/PersonalDataModelCensus.cs @@ -0,0 +1,44 @@ +using LearnStack.SharedKernel.DataProtection; +using Microsoft.EntityFrameworkCore.Metadata; + +namespace LearnStack.Infrastructure.DataProtection; + +/// A diagnostic containing model names and a closed issue code, never property values. +public sealed record PersonalDataClassificationIssue(string EntityType, string Property, string Code); + +/// Pure completeness validation of actual EF scalar metadata, including inherited and shadow properties. +public static class PersonalDataModelCensus +{ + public const string FailureMessage = + "Personal-data classification is missing, invalid or conflicting. Fix: explicitly classify every mapped property with a valid category and purpose."; + + public static IReadOnlyList Inspect(IReadOnlyModel model) + { + ArgumentNullException.ThrowIfNull(model); + var issues = new List(); + foreach (var entity in model.GetEntityTypes().OrderBy(type => type.Name, StringComparer.Ordinal)) + InspectType(entity, entity.Name, string.Empty, issues); + return issues; + } + + private static void InspectType(IReadOnlyTypeBase type, string entityName, string prefix, + List issues) + { + foreach (var property in type.GetProperties().OrderBy(property => property.Name, StringComparer.Ordinal)) + { + var category = property.FindAnnotation(PersonalDataClassificationExtensions.CategoryAnnotation); + var purpose = property.FindAnnotation(PersonalDataClassificationExtensions.PurposeAnnotation); + if (category is null) + issues.Add(new(entityName, prefix + property.Name, "missing_category")); + else if (category.Value is not PersonalDataCategory value || !Enum.IsDefined(value)) + issues.Add(new(entityName, prefix + property.Name, "invalid_category")); + if (purpose is null) + issues.Add(new(entityName, prefix + property.Name, "missing_purpose")); + else if (!PersonalDataClassificationExtensions.IsValidPurpose(purpose.Value)) + issues.Add(new(entityName, prefix + property.Name, "invalid_purpose")); + } + + foreach (var complex in type.GetComplexProperties().OrderBy(property => property.Name, StringComparer.Ordinal)) + InspectType(complex.ComplexType, entityName, prefix + complex.Name + ".", issues); + } +} diff --git a/backend/src/LearnStack.Infrastructure/Persistence/AuditColumnMapping.cs b/backend/src/LearnStack.Infrastructure/Persistence/AuditColumnMapping.cs index 379c60918..a1cb5a097 100644 --- a/backend/src/LearnStack.Infrastructure/Persistence/AuditColumnMapping.cs +++ b/backend/src/LearnStack.Infrastructure/Persistence/AuditColumnMapping.cs @@ -1,3 +1,5 @@ +using LearnStack.Infrastructure.DataProtection; +using LearnStack.SharedKernel.DataProtection; using LearnStack.SharedKernel.Domain; using LearnStack.SharedKernel.Identifiers; using Microsoft.EntityFrameworkCore; @@ -54,22 +56,29 @@ public static void MapAuditColumns(this EntityTypeBuilder { ArgumentNullException.ThrowIfNull(builder); - builder.Property(x => x.CreatedAt).IsRequired(); + builder.Property(x => x.CreatedAt).IsRequired() + .HasPersonalData(PersonalDataCategory.Audit, "Record when the aggregate was created."); builder.Property(x => x.CreatedBy) .HasConversion() - .IsRequired(); - builder.Property(x => x.UpdatedAt); + .IsRequired() + .HasPersonalData(PersonalDataCategory.Identity, "Attribute aggregate creation to its actor."); + builder.Property(x => x.UpdatedAt) + .HasPersonalData(PersonalDataCategory.Audit, "Record when the aggregate was last updated."); builder.Property(x => x.UpdatedBy) - .HasConversion(); - builder.Property(x => x.DeletedAt); + .HasConversion() + .HasPersonalData(PersonalDataCategory.Identity, "Attribute the latest aggregate update to its actor."); + builder.Property(x => x.DeletedAt) + .HasPersonalData(PersonalDataCategory.Audit, "Record when the aggregate was soft-deleted."); builder.Property(x => x.DeletedBy) - .HasConversion(); + .HasConversion() + .HasPersonalData(PersonalDataCategory.Identity, "Attribute aggregate soft deletion to its actor."); builder.Property(x => x.Version) .HasColumnName("row_version") .HasDefaultValue(0L) .IsConcurrencyToken() - .ValueGeneratedNever(); + .ValueGeneratedNever() + .HasPersonalData(PersonalDataCategory.None, "Detect concurrent writes to this aggregate revision."); } /// diff --git a/backend/src/LearnStack.Infrastructure/Persistence/GlobalIdentityEnrollment.cs b/backend/src/LearnStack.Infrastructure/Persistence/GlobalIdentityEnrollment.cs new file mode 100644 index 000000000..56546e765 --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/Persistence/GlobalIdentityEnrollment.cs @@ -0,0 +1,18 @@ +using LearnStack.SharedKernel.Identity; + +namespace LearnStack.Infrastructure.Persistence; + +/// The scoped, non-allocating reader shared by the actual unit and the central audit store. +public sealed class GlobalIdentityEnrollment : IGlobalIdentityEnrollment +{ + private NpgsqlUnitOfWork? _unit; + + internal void Attach(NpgsqlUnitOfWork unit) + { + if (_unit is not null && !ReferenceEquals(_unit, unit)) + throw new InvalidOperationException("A scoped identity enrollment belongs to exactly one unit of work."); + _unit = unit; + } + + public bool IsActive => _unit?.IsGlobalIdentityTransaction is true; +} diff --git a/backend/src/LearnStack.Infrastructure/Persistence/GlobalIdentityScopeAccessor.cs b/backend/src/LearnStack.Infrastructure/Persistence/GlobalIdentityScopeAccessor.cs new file mode 100644 index 000000000..88ec639d1 --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/Persistence/GlobalIdentityScopeAccessor.cs @@ -0,0 +1,11 @@ +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Persistence; + +namespace LearnStack.Infrastructure.Persistence; + +/// Reads only the current physical global announcement; no mutable context-setting port. +public sealed class GlobalIdentityScopeAccessor(IUnitOfWork unitOfWork) : IGlobalIdentityScopeAccessor +{ + public GlobalIdentityContextAnnouncement? Current => unitOfWork is IGlobalIdentityUnitOfWork global + ? global.GetGlobalIdentityAnnouncement(unitOfWork.Transaction) : null; +} diff --git a/backend/src/LearnStack.Infrastructure/Persistence/IdentityLockObservation.cs b/backend/src/LearnStack.Infrastructure/Persistence/IdentityLockObservation.cs new file mode 100644 index 000000000..943c74e50 --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/Persistence/IdentityLockObservation.cs @@ -0,0 +1,46 @@ +using System.Diagnostics; +using System.Diagnostics.Metrics; +using Npgsql; + +namespace LearnStack.Infrastructure.Persistence; + +public enum IdentityLockKind { Subject = 1, User = 2, Tenant = 3 } + +/// Closed process signals; no scope, SQL, exception or person value is a dimension. +public static class IdentityLockObservation +{ + public const string MeterName = "learnstack.identity"; + private static readonly Meter Meter = new(MeterName); + private static readonly Histogram Wait = Meter.CreateHistogram( + "learnstack_identity_lock_wait_seconds", "s"); + private static readonly Counter Refusals = Meter.CreateCounter( + "learnstack_identity_lock_refusals_total", "1"); + + internal static void Complete(IdentityLockKind kind, long started, Exception? failure = null) + { + var outcome = failure switch + { + null => "acquired", + OperationCanceledException => "cancelled", + PostgresException { SqlState: PostgresErrorCodes.LockNotAvailable } => "timeout", + NpgsqlException { InnerException: TimeoutException } => "timeout", + _ => "fault", + }; + Wait.Record(Stopwatch.GetElapsedTime(started).TotalSeconds, + new("lock_kind", Name(kind)), new("outcome", outcome)); + if (failure is not null) + Refusals.Add(1, new("lock_kind", Name(kind)), new("reason", outcome)); + } + + /// Called once by the owning adapter when a real guard rejects its lock plan. + public static void PlanFault(IdentityLockKind kind) => + Refusals.Add(1, new("lock_kind", Name(kind)), new("reason", "fault")); + + private static string Name(IdentityLockKind kind) => kind switch + { + IdentityLockKind.Subject => "subject", + IdentityLockKind.User => "user", + IdentityLockKind.Tenant => "tenant", + _ => throw new ArgumentOutOfRangeException(nameof(kind)), + }; +} diff --git a/backend/src/LearnStack.Infrastructure/Persistence/IdentityMutationLocks.cs b/backend/src/LearnStack.Infrastructure/Persistence/IdentityMutationLocks.cs new file mode 100644 index 000000000..4d4fc7f39 --- /dev/null +++ b/backend/src/LearnStack.Infrastructure/Persistence/IdentityMutationLocks.cs @@ -0,0 +1,109 @@ +using System.Data; +using System.Data.Common; +using System.Diagnostics; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Persistence; +using Npgsql; + +namespace LearnStack.Infrastructure.Persistence; + +/// One immutable plan on one announced physical transaction; never a session lock owner. +public sealed class IdentityMutationLocks(IUnitOfWork unit) : IIdentityMutationLocks +{ + private IdentityMutationLockPlan? _plan; + private DbConnection? _connection; + private DbTransaction? _transaction; + private long _generation; + private bool _attempted, _faultRecorded; + + public async Task AcquireAsync(IdentityMutationLockPlan plan, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(plan); + if (_attempted || !IsAdmitted(plan)) Refuse(); + _attempted = true; + _connection = unit.Connection; + _transaction = unit.Transaction; + _generation = unit.GetTenantContextAnnouncement(_transaction)!.Generation; + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + deadline.CancelAfter(TimeSpan.FromSeconds(10)); + try + { + // The driver's cached isolation property cannot observe an explicit + // SET TRANSACTION made earlier on the same physical owner. + await using (var check = new NpgsqlCommand(""" + SELECT current_setting('transaction_isolation') = 'read committed' + AND current_setting('transaction_read_only') = 'off' + """, (NpgsqlConnection)_connection, (NpgsqlTransaction)_transaction!) { CommandTimeout = 10 }) + if (await check.ExecuteScalarAsync(deadline.Token) is not true) Refuse(); + await ExecuteAsync("SET LOCAL lock_timeout = '2s'", null, deadline.Token); + foreach (var user in plan.UserIds) + await AcquireOneAsync(IdentityLockKind.User, IdentityAdvisoryLockKey.ForUser(user), false, deadline.Token); + await AcquireOneAsync(IdentityLockKind.Tenant, IdentityAdvisoryLockKey.ForTenant(plan.TenantId), + plan.TenantMode == IdentityTenantLockMode.Shared, deadline.Token); + deadline.Token.ThrowIfCancellationRequested(); + _plan = plan; + RequireCurrent(plan); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + unit.MarkRollbackOnly(); + throw new OperationCanceledException(cancellationToken); + } + catch (Exception failure) when (failure is not OutOfMemoryException and not StackOverflowException) + { + unit.MarkRollbackOnly(); + throw new IdentityMutationLockException(); + } + } + + public void RequireCurrent(IdentityMutationLockPlan plan) + { + ArgumentNullException.ThrowIfNull(plan); + if (!ReferenceEquals(_plan, plan) || !IsAdmitted(plan) + || !ReferenceEquals(_connection, unit.Connection) || !ReferenceEquals(_transaction, unit.Transaction) + || unit.GetTenantContextAnnouncement(unit.Transaction)?.Generation != _generation) + Refuse(); + } + + private bool IsAdmitted(IdentityMutationLockPlan plan) => unit.HasActiveTransaction + && !unit.IsRollbackOnly && unit.Mode == TransactionMode.ReadWrite + && unit is not IGlobalIdentityUnitOfWork { IsGlobalIdentityTransaction: true } + && unit.Transaction is { IsolationLevel: IsolationLevel.ReadCommitted } + && unit.GetTenantContextAnnouncement(unit.Transaction) is { Generation: > 0 } announcement + && announcement.TenantId == plan.TenantId; + + private void Refuse() + { + if (!_faultRecorded) + { + _faultRecorded = true; + IdentityLockObservation.PlanFault(IdentityLockKind.Tenant); + } + if (unit.HasActiveTransaction) unit.MarkRollbackOnly(); + throw new IdentityMutationLockException(); + } + + private async Task AcquireOneAsync(IdentityLockKind kind, long key, bool shared, CancellationToken cancellationToken) + { + var started = Stopwatch.GetTimestamp(); + try + { + await ExecuteAsync(shared ? "SELECT pg_catalog.pg_advisory_xact_lock_shared(@key)" + : "SELECT pg_catalog.pg_advisory_xact_lock(@key)", key, cancellationToken); + IdentityLockObservation.Complete(kind, started); + } + catch (Exception failure) when (failure is not OutOfMemoryException and not StackOverflowException) + { + IdentityLockObservation.Complete(kind, started, failure); + throw; + } + } + + private async Task ExecuteAsync(string sql, long? key, CancellationToken cancellationToken) + { + await using var command = new NpgsqlCommand(sql, (NpgsqlConnection)_connection!, (NpgsqlTransaction)_transaction!) + { CommandTimeout = 10 }; + if (key is { } value) command.Parameters.AddWithValue("key", value); + await command.ExecuteNonQueryAsync(cancellationToken); + } +} diff --git a/backend/src/LearnStack.Infrastructure/Persistence/ModuleDbContextRegistration.cs b/backend/src/LearnStack.Infrastructure/Persistence/ModuleDbContextRegistration.cs index 6558db3f0..7008298de 100644 --- a/backend/src/LearnStack.Infrastructure/Persistence/ModuleDbContextRegistration.cs +++ b/backend/src/LearnStack.Infrastructure/Persistence/ModuleDbContextRegistration.cs @@ -28,12 +28,16 @@ namespace LearnStack.Infrastructure.Persistence; /// which is what the rule asserts against. /// /// -/// EF issues its own savepoints, and that is left on. A context enlisted in +/// EF automatic savepoints remain the default. A context enlisted in /// an externally supplied transaction wraps every SaveChangesAsync in a /// real SAVEPOINT / RELEASE SAVEPOINT, so a failed save rolls back /// to its own savepoint and leaves the ambient transaction usable. ADR-0040's /// "frames, not savepoints" describes the unit of work's in-process depth counter, /// not the connection — the two mechanisms are independent and both are wanted. +/// The closed Identity contextual graph adapter suspends this flag only during +/// its atomic save, restores it in finally and poisons the whole unit on any +/// save failure; it admits no partial repair. The canonical Identity contract +/// in Database Standards owns that bounded adapter behavior. /// /// public static class ModuleDbContextRegistration @@ -109,6 +113,11 @@ public static IServiceCollection AddModuleDbContext(this IServiceColle services.TryAddScoped(provider => { var unitOfWork = provider.GetRequiredService(); + var global = unitOfWork as IGlobalIdentityUnitOfWork; + var globalAnnouncement = global?.GetGlobalIdentityAnnouncement(unitOfWork.Transaction); + if (global is { IsGlobalIdentityTransaction: true } + && (globalAnnouncement is null || globalAnnouncement.Descriptor.ContextType != typeof(TContext))) + throw new InvalidOperationException("Only the declared context can enroll in a global identity owner."); if (unitOfWork.Transaction is null) { @@ -132,7 +141,10 @@ public static IServiceCollection AddModuleDbContext(this IServiceColle // is false by this overload's contract, so disposing the context // does not return the connection to the pool underneath its // siblings — IUnitOfWork is the sole owner. - .UseNpgsql(unitOfWork.Connection) + .UseNpgsql(unitOfWork.Connection, options => + { + if (globalAnnouncement is not null) options.CommandTimeout(10); + }) // Without this EF has no ILoggerFactory to resolve, and every // Microsoft.EntityFrameworkCore log category is silent for every // context this helper registers — on a seam whose whole premise is @@ -177,6 +189,8 @@ public static IServiceCollection AddModuleDbContext(this IServiceColle // options, so it would fail to construct any context with a second // parameter, which is now every tenant-scoped one. var context = ActivatorUtilities.CreateInstance(provider, options); + if (globalAnnouncement is not null) + global!.EnrollGlobalIdentityContext(context, globalAnnouncement.Descriptor); foreach (var interceptor in saveInterceptors.OfType()) { interceptor.Attach(context); diff --git a/backend/src/LearnStack.Infrastructure/Persistence/NpgsqlUnitOfWork.cs b/backend/src/LearnStack.Infrastructure/Persistence/NpgsqlUnitOfWork.cs index 34d6537cf..9fa1d86e3 100644 --- a/backend/src/LearnStack.Infrastructure/Persistence/NpgsqlUnitOfWork.cs +++ b/backend/src/LearnStack.Infrastructure/Persistence/NpgsqlUnitOfWork.cs @@ -1,7 +1,9 @@ using System.Data.Common; +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.ExceptionServices; using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; using LearnStack.SharedKernel.Jobs; using LearnStack.SharedKernel.Persistence; using Microsoft.Extensions.Logging; @@ -44,14 +46,23 @@ namespace LearnStack.Infrastructure.Persistence; /// that a later BEGIN clears is not. /// /// -public sealed class NpgsqlUnitOfWork( - NpgsqlDataSource dataSource, ILogger logger) : IUnitOfWork +public sealed class NpgsqlUnitOfWork : IGlobalIdentityUnitOfWork { - private readonly NpgsqlDataSource _dataSource = - dataSource ?? throw new ArgumentNullException(nameof(dataSource)); + private readonly NpgsqlDataSource _dataSource; - private readonly ILogger _logger = - logger ?? throw new ArgumentNullException(nameof(logger)); + private readonly ILogger _logger; + private readonly GlobalIdentityEnrollment _enrollment; + + public NpgsqlUnitOfWork(NpgsqlDataSource dataSource, ILogger logger, + GlobalIdentityEnrollment? enrollment = null) + { + _dataSource = dataSource ?? throw new ArgumentNullException(nameof(dataSource)); + _logger = logger ?? throw new ArgumentNullException(nameof(logger)); + _enrollment = enrollment ?? new GlobalIdentityEnrollment(); + _enrollment.Attach(this); + } + + public IGlobalIdentityEnrollment GlobalIdentityEnrollment => _enrollment; private readonly JobApplicationSourceOwner? _jobSourceOwner = JobApplicationSourceOwner.Current; private bool _jobMainBound; @@ -85,6 +96,13 @@ public sealed class NpgsqlUnitOfWork( private bool _tenantContextIssued; private TenantContextAnnouncement? _tenantContextAnnouncement; + private GlobalIdentityOwnerDescriptor? _globalIdentityDescriptor; + private GlobalIdentityContextAnnouncement? _globalIdentityAnnouncement; + private object? _globalIdentityContext; + private bool _openingGlobalIdentity; + private bool _resolvingGlobalIdentity; + private bool _globalIdentityLocked; + private bool _globalIdentitySealed; private bool _disposed; public DbConnection Connection @@ -125,12 +143,22 @@ public DbTransaction? Transaction public Task BeginTransactionAsync(CancellationToken cancellationToken = default) => BeginTransactionAsync(TransactionMode.ReadWrite, cancellationToken); - public async Task BeginTransactionAsync( - TransactionMode mode, CancellationToken cancellationToken = default) + public Task BeginTransactionAsync( + TransactionMode mode, CancellationToken cancellationToken = default) => + BeginTransactionCoreAsync(mode, globalIdentity: false, cancellationToken); + + private async Task BeginTransactionCoreAsync( + TransactionMode mode, bool globalIdentity, CancellationToken cancellationToken) { JobApplicationSourceOwner.RefuseExternalEntry(); ObjectDisposedException.ThrowIf(_disposed, this); + if (!globalIdentity && IsGlobalIdentityTransaction) + { + MarkRollbackOnly(); + throw new InvalidOperationException("An ordinary transaction cannot join a global identity owner."); + } + if (_rollbackOnly) { throw new InvalidOperationException( @@ -171,7 +199,7 @@ public async Task BeginTransactionAsync( await _connection.OpenAsync(cancellationToken); } - _transaction = mode == TransactionMode.ReadOnly + _transaction = mode == TransactionMode.ReadOnly || globalIdentity ? await _connection.BeginTransactionAsync(System.Data.IsolationLevel.ReadCommitted, cancellationToken) : await _connection.BeginTransactionAsync(cancellationToken); _jobSourceOwner?.HoldMainTransaction(this, _transaction); @@ -215,7 +243,122 @@ public async Task BeginTransactionAsync( _commitRequested = false; } - return new Frame(this, ++_depth, _generation); + return new Frame(this, ++_depth, _generation, + releaseConnection: globalIdentity && mode == TransactionMode.ReadOnly); + } + + public bool IsGlobalIdentityTransaction => _openingGlobalIdentity || _resolvingGlobalIdentity + || _globalIdentityDescriptor is not null; + + public async Task BeginGlobalIdentityTransactionAsync( + GlobalIdentityOwnerDescriptor descriptor, TransactionMode mode, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(descriptor); + JobApplicationSourceOwner.RefuseExternalEntry(); + ObjectDisposedException.ThrowIf(_disposed, this); + if (HasActiveTransaction || IsGlobalIdentityTransaction || _jobSourceOwner is not null + || JobApplicationSourceOwner.Current is not null + || (descriptor.Kind == GlobalIdentityOwnerKind.Lookup + ? mode != TransactionMode.ReadOnly : mode != TransactionMode.ReadWrite)) + { + if (HasActiveTransaction) MarkRollbackOnly(); + throw new InvalidOperationException("Global identity admission requires a fresh, correctly typed owner."); + } + + _openingGlobalIdentity = true; + IUnitOfWorkScope? scope = null; + try + { + scope = await BeginTransactionCoreAsync(mode, globalIdentity: true, cancellationToken); + _globalIdentityDescriptor = descriptor; + await ExecuteAsync("SELECT set_config('app.tenant_id', '', true), " + + "set_config('app.organization_id', '', true), set_config('app.scope', '', true), " + + "set_config('app.resolving_host', '', true), " + + "set_config('app.identity_authority_id', @authority, true), " + + "set_config('app.identity_subject_key', @subject, true)", cancellationToken, + ("authority", descriptor.Subject.AuthorityId.Value.ToString("D")), + ("subject", descriptor.Subject.SubjectKey.Hex)); + _globalIdentityAnnouncement = new GlobalIdentityContextAnnouncement(_generation, descriptor); + return scope; + } + catch + { + MarkRollbackOnly(); + try { await RollbackCoreAsync(); } + catch { LogSetupCleanupFailure(_logger, null); } + if (scope is not null) + { + try { await scope.DisposeAsync(); } + catch { LogSetupCleanupFailure(_logger, null); } + } + throw; + } + finally + { + _openingGlobalIdentity = false; + } + } + + public GlobalIdentityContextAnnouncement? GetGlobalIdentityAnnouncement(DbTransaction? transaction) => + transaction is not null && ReferenceEquals(transaction, _transaction) + ? _globalIdentityAnnouncement : null; + + public async Task AcquireGlobalIdentitySubjectLockAsync(GlobalIdentityOwnerDescriptor descriptor, + CancellationToken cancellationToken = default) + { + RequireGlobalIdentityOwner(descriptor); + if (_mode != TransactionMode.ReadWrite || _globalIdentityLocked || _globalIdentitySealed) + throw new InvalidOperationException("The global identity subject lock belongs only to its fresh creation owner."); + await ExecuteAsync("SET LOCAL lock_timeout = '2s'", cancellationToken); + var started = Stopwatch.GetTimestamp(); + try + { + await ExecuteAsync("SELECT pg_catalog.pg_advisory_xact_lock(@key)", cancellationToken, + ("key", IdentityAdvisoryLockKey.ForSubject(descriptor.Subject))); + IdentityLockObservation.Complete(IdentityLockKind.Subject, started); + } + catch (Exception failure) when (failure is not OutOfMemoryException and not StackOverflowException) + { + IdentityLockObservation.Complete(IdentityLockKind.Subject, started, failure); + throw; + } + _globalIdentityLocked = true; + } + + public void EnrollGlobalIdentityContext(object context, GlobalIdentityOwnerDescriptor descriptor) + { + ArgumentNullException.ThrowIfNull(context); + RequireGlobalIdentityOwner(descriptor); + if (context.GetType() != descriptor.ContextType || _globalIdentitySealed + || (_mode == TransactionMode.ReadWrite && !_globalIdentityLocked) + || (_globalIdentityContext is not null && !ReferenceEquals(_globalIdentityContext, context))) + throw new InvalidOperationException("The context does not belong to this global identity owner."); + _globalIdentityContext = context; + } + + public bool IsGlobalIdentityContextEnrolled(object context, DbTransaction? transaction) => + !_globalIdentitySealed && !_rollbackOnly && _globalIdentityContext is not null + && ReferenceEquals(_globalIdentityContext, context) + && GetGlobalIdentityAnnouncement(transaction) is not null; + + public async Task ValidateGlobalIdentityConstraintsAsync(GlobalIdentityOwnerDescriptor descriptor, + CancellationToken cancellationToken = default) + { + RequireGlobalIdentityOwner(descriptor); + if (_mode != TransactionMode.ReadWrite || !_globalIdentityLocked || _globalIdentitySealed) + throw new InvalidOperationException("Global constraint validation requires the live unsealed creation owner."); + await ExecuteAsync("SET CONSTRAINTS ALL IMMEDIATE", cancellationToken); + _globalIdentitySealed = true; + } + + private void RequireGlobalIdentityOwner(GlobalIdentityOwnerDescriptor descriptor) + { + ObjectDisposedException.ThrowIf(_disposed, this); + if (_transaction is null || _depth != 1 || _rollbackOnly + || !ReferenceEquals(_globalIdentityDescriptor, descriptor) + || _globalIdentityAnnouncement is not { Generation: > 0 } announcement + || announcement.Generation != _generation) + throw new InvalidOperationException("The global identity owner no longer matches its live transaction."); } public async Task SetTenantContextAsync( @@ -225,6 +368,12 @@ public async Task SetTenantContextAsync( ArgumentNullException.ThrowIfNull(context); ObjectDisposedException.ThrowIf(_disposed, this); + if (IsGlobalIdentityTransaction) + { + MarkRollbackOnly(); + throw new InvalidOperationException("A tenant setter cannot announce a global identity transaction."); + } + if (_transaction is null) { throw new InvalidOperationException( @@ -306,7 +455,8 @@ public async Task SetTenantContextAsync( await ExecuteAsync( "SELECT set_config('app.tenant_id', @tenant, true), " - + "set_config('app.organization_id', @organization, true)", + + "set_config('app.organization_id', @organization, true), " + + "set_config('app.identity_authority_id', '', true), set_config('app.identity_subject_key', '', true)", cancellationToken, ("tenant", tenant), ("organization", organization)); @@ -327,6 +477,12 @@ public async Task SetProvisioningTenantContextAsync( JobApplicationSourceOwner.RefuseExternalEntry(); ObjectDisposedException.ThrowIf(_disposed, this); + if (IsGlobalIdentityTransaction) + { + MarkRollbackOnly(); + throw new InvalidOperationException("Provisioning cannot announce a global identity transaction."); + } + if (_transaction is null) { throw new InvalidOperationException( @@ -384,7 +540,8 @@ public async Task SetProvisioningTenantContextAsync( // into a provisioning write. await ExecuteAsync( "SELECT set_config('app.tenant_id', @tenant, true), " - + "set_config('app.organization_id', '', true)", + + "set_config('app.organization_id', '', true), " + + "set_config('app.identity_authority_id', '', true), set_config('app.identity_subject_key', '', true)", cancellationToken, ("tenant", tenantId.Value.ToString())); @@ -406,6 +563,11 @@ private void ClearTenantContextAnnouncement() { _tenantContextIssued = false; _tenantContextAnnouncement = null; + _globalIdentityDescriptor = null; + _globalIdentityAnnouncement = null; + _globalIdentityContext = null; + _globalIdentityLocked = false; + _globalIdentitySealed = false; } private static readonly Action LogResolvedWithoutTenant = @@ -463,6 +625,7 @@ public async ValueTask DisposeAsync() return; } + _resolvingGlobalIdentity = IsGlobalIdentityTransaction; _disposed = true; ClearTenantContextAnnouncement(); @@ -503,6 +666,7 @@ public async ValueTask DisposeAsync() } if (_jobMainBound && connectionCleanupSucceeded) _jobSourceOwner!.ReportMainCleanup(this, succeeded: true); + _resolvingGlobalIdentity = false; } cleanupFailure?.Throw(); @@ -526,6 +690,12 @@ public async ValueTask DisposeAsync() private async Task CommitFrameAsync(CancellationToken cancellationToken) { + if (_globalIdentityDescriptor is not null && _mode == TransactionMode.ReadWrite && !_globalIdentitySealed) + { + MarkRollbackOnly(); + await RollbackCoreAsync(); + throw new InvalidOperationException("A global identity creation cannot commit before final constraint validation."); + } _commitRequested = true; if (--_depth > 0) @@ -544,6 +714,7 @@ private async Task CommitFrameAsync(CancellationToken cancellationToken) } var transaction = _transaction!; + _resolvingGlobalIdentity = _resolvingGlobalIdentity || _globalIdentityDescriptor is not null; _transaction = null; _mode = null; ClearTenantContextAnnouncement(); @@ -568,6 +739,10 @@ private async Task CommitFrameAsync(CancellationToken cancellationToken) } throw; } + finally + { + _resolvingGlobalIdentity = false; + } // The caller can now record definitive durability before awaiting cleanup. // Only one completed transaction can remain: Begin cleans it before reuse. @@ -623,6 +798,7 @@ private async Task RollbackFrameAsync() private async Task RollbackCoreAsync() { var transaction = _transaction; + _resolvingGlobalIdentity = _resolvingGlobalIdentity || _globalIdentityDescriptor is not null; _transaction = null; _mode = null; _depth = 0; @@ -630,6 +806,7 @@ private async Task RollbackCoreAsync() if (transaction is null) { + _resolvingGlobalIdentity = false; return; } @@ -657,6 +834,7 @@ private async Task RollbackCoreAsync() _jobSourceOwner?.ReportMainTransactionCleanup(this, transaction, succeeded: false); cleanupFailure ??= ExceptionDispatchInfo.Capture(failure); } + _resolvingGlobalIdentity = false; } cleanupFailure?.Throw(); } @@ -675,6 +853,7 @@ private async Task ExecuteAsync( string sql, CancellationToken cancellationToken, params (string Name, object Value)[] parameters) { await using var command = _connection!.CreateCommand(); + if (IsGlobalIdentityTransaction) command.CommandTimeout = 10; command.CommandText = sql; command.Transaction = (NpgsqlTransaction?)_transaction; @@ -693,7 +872,7 @@ private async Task ExecuteAsync( /// opened after this one is still open would commit nothing and report /// success. /// - private sealed class Frame(NpgsqlUnitOfWork unitOfWork, int depth, long generation) + private sealed class Frame(NpgsqlUnitOfWork unitOfWork, int depth, long generation, bool releaseConnection) : IUnitOfWorkScope { private bool _resolved; @@ -767,7 +946,22 @@ public async ValueTask DisposeAsync() // Disposal owns rollback cleanup even under external denial. It // cannot create operational authority or resolve a later generation. await FailOwnedAsync(); - if (IsOwner && !IsStale()) await unitOfWork.DisposeCompletedTransactionAsync(); + if (IsOwner && !IsStale()) + { + await unitOfWork.DisposeCompletedTransactionAsync(); + // A binding read precedes the ordinary request owner. Return its + // connector before dispatch, retaining the connection object so + // the same scoped unit/EF contexts can open their next owner. + if (releaseConnection && unitOfWork._connection is { } connection) + { + try { await connection.CloseAsync(); } + catch + { + unitOfWork._rollbackOnly = true; + throw; + } + } + } } private bool AlreadyResolved() => diff --git a/backend/src/LearnStack.Infrastructure/Persistence/TenantContextGuardInterceptor.cs b/backend/src/LearnStack.Infrastructure/Persistence/TenantContextGuardInterceptor.cs index b69900d64..f1f5191ea 100644 --- a/backend/src/LearnStack.Infrastructure/Persistence/TenantContextGuardInterceptor.cs +++ b/backend/src/LearnStack.Infrastructure/Persistence/TenantContextGuardInterceptor.cs @@ -1,6 +1,7 @@ using System.Data.Common; using LearnStack.SharedKernel.Errors; using LearnStack.SharedKernel.Persistence; +using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; namespace LearnStack.Infrastructure.Persistence; @@ -58,7 +59,7 @@ public TenantContextGuardInterceptor(IUnitOfWork unitOfWork) public override InterceptionResult ReaderExecuting( DbCommand command, CommandEventData eventData, InterceptionResult result) { - Guard(command); + Guard(command, eventData.Context); return base.ReaderExecuting(command, eventData, result); } @@ -68,14 +69,14 @@ public override ValueTask> ReaderExecutingAsync InterceptionResult result, CancellationToken cancellationToken = default) { - Guard(command); + Guard(command, eventData.Context); return base.ReaderExecutingAsync(command, eventData, result, cancellationToken); } public override InterceptionResult NonQueryExecuting( DbCommand command, CommandEventData eventData, InterceptionResult result) { - Guard(command); + Guard(command, eventData.Context); return base.NonQueryExecuting(command, eventData, result); } @@ -85,14 +86,14 @@ public override ValueTask> NonQueryExecutingAsync( InterceptionResult result, CancellationToken cancellationToken = default) { - Guard(command); + Guard(command, eventData.Context); return base.NonQueryExecutingAsync(command, eventData, result, cancellationToken); } public override InterceptionResult ScalarExecuting( DbCommand command, CommandEventData eventData, InterceptionResult result) { - Guard(command); + Guard(command, eventData.Context); return base.ScalarExecuting(command, eventData, result); } @@ -102,13 +103,19 @@ public override ValueTask> ScalarExecutingAsync( InterceptionResult result, CancellationToken cancellationToken = default) { - Guard(command); + Guard(command, eventData.Context); return base.ScalarExecutingAsync(command, eventData, result, cancellationToken); } /// Throws unless a sanctioned setter announced this command's transaction. - private void Guard(DbCommand command) + private void Guard(DbCommand command, DbContext? context) { + if (_unitOfWork is IGlobalIdentityUnitOfWork { IsGlobalIdentityTransaction: true } global) + { + if (context is not null && global.IsGlobalIdentityContextEnrolled(context, command.Transaction)) return; + throw new TenantContextMissingException("The command does not belong to the enrolled global identity context."); + } + if (_unitOfWork.IsTenantContextIssuedOn(command.Transaction)) { return; diff --git a/backend/src/LearnStack.SharedKernel/Audit/AuditDraftComposer.cs b/backend/src/LearnStack.SharedKernel/Audit/AuditDraftComposer.cs index 083ed7a72..f99f72758 100644 --- a/backend/src/LearnStack.SharedKernel/Audit/AuditDraftComposer.cs +++ b/backend/src/LearnStack.SharedKernel/Audit/AuditDraftComposer.cs @@ -124,6 +124,8 @@ private static AuditEntryDraft Compose( { ArgumentNullException.ThrowIfNull(changes); + intent.GlobalIdentity?.RequireIntent(intent); + var subject = Subject.Of(intent, changes); return new AuditEntryDraft @@ -162,6 +164,13 @@ private static AuditEntryDraft Compose( private static string? ComposeMetadata(AuditIntent intent) { + if (intent.GlobalIdentity is { } identity) + { + return "{\"identity_authority_id\":" + AuditJson.Quote(identity.AuthorityId.Value.ToString("D")) + + ",\"identity_subject_key\":" + AuditJson.Quote(identity.SubjectKey.Hex) + + ",\"identity_source\":" + AuditJson.Quote(identity.Source) + "}"; + } + if (intent.CausationId is null && intent.CausalActorUserId is null && intent.JobId is null && intent.ParentJobId is null) return null; if (intent.CausationId == Guid.Empty diff --git a/backend/src/LearnStack.SharedKernel/Audit/AuditIntent.cs b/backend/src/LearnStack.SharedKernel/Audit/AuditIntent.cs index ae482c606..fe769f6ad 100644 --- a/backend/src/LearnStack.SharedKernel/Audit/AuditIntent.cs +++ b/backend/src/LearnStack.SharedKernel/Audit/AuditIntent.cs @@ -100,6 +100,9 @@ public sealed record AuditIntent( Type? EntityType, DateTimeOffset DeclaredAt) { + /// Closed creation attribution minted by the common global audit entry. + public GlobalIdentityCreationReference? GlobalIdentity { get; init; } + /// The trusted incoming event identity for delivery-originated work. public Guid? CausationId { get; init; } diff --git a/backend/src/LearnStack.SharedKernel/Audit/GlobalIdentityCreationReference.cs b/backend/src/LearnStack.SharedKernel/Audit/GlobalIdentityCreationReference.cs new file mode 100644 index 000000000..e1bd70e80 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Audit/GlobalIdentityCreationReference.cs @@ -0,0 +1,101 @@ +using System.Data.Common; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Persistence; + +namespace LearnStack.SharedKernel.Audit; + +/// The central creation intent's immutable target and PostgreSQL audit key. +public sealed class GlobalIdentityCreationReference +{ + public const string Operation = "identity.user.create"; + private readonly IGlobalIdentityUnitOfWork _unit; + private readonly DbConnection _connection; + private readonly DbTransaction _transaction; + private readonly GlobalIdentityContextAnnouncement _announcement; + + private GlobalIdentityCreationReference(IGlobalIdentityUnitOfWork unit, + GlobalIdentityContextAnnouncement announcement, UserId targetUserId, AuditEntryId auditId, + DateTimeOffset timestamp) + { + if (!targetUserId.IsInitialized() || targetUserId.Value.Version != 7 || targetUserId == UserId.SystemActor + || !auditId.IsInitialized() || auditId.Value.Version != 7 + || announcement.Descriptor.Kind == GlobalIdentityOwnerKind.Lookup + || (announcement.Descriptor.SeedActor is { } seed && seed != targetUserId) + || timestamp <= DateTimeOffset.MinValue || timestamp >= DateTimeOffset.MaxValue) + throw new ArgumentException("Global identity creation attribution is invalid."); + _unit = unit; + _connection = unit.Connection; + _transaction = unit.Transaction ?? throw new InvalidOperationException("Global creation requires its live owner."); + _announcement = announcement; + TargetUserId = targetUserId; + AuditId = auditId; + Timestamp = NormalizeTimestamp(timestamp); + RequireLive(unit); + } + + public UserId TargetUserId { get; } + public AuditEntryId AuditId { get; } + public DateTimeOffset Timestamp { get; } + public GlobalIdentityOwnerDescriptor Descriptor => _announcement.Descriptor; + public IdentityAuthorityId AuthorityId => Descriptor.Subject.AuthorityId; + public IdentitySubjectKey SubjectKey => Descriptor.Subject.SubjectKey; + public string Source => Descriptor.Source; + public UserId? ActorUserId => Descriptor.Kind == GlobalIdentityOwnerKind.SeedAdoption ? UserId.SystemActor : null; + + public void RequireSubject(IdentityAuthorityId authorityId, IdentitySubjectKey subjectKey) + { + if (authorityId != AuthorityId || !SubjectKey.Equals(subjectKey)) + throw new InvalidOperationException("The creation reference belongs to another identity subject."); + } + + public void RequireSubject(GlobalIdentitySubject subject) + { + ArgumentNullException.ThrowIfNull(subject); + RequireSubject(subject.AuthorityId, subject.SubjectKey); + if (!string.Equals(subject.Issuer, Descriptor.Subject.Issuer, StringComparison.Ordinal) + || !string.Equals(subject.Subject, Descriptor.Subject.Subject, StringComparison.Ordinal)) + throw new InvalidOperationException("The creation reference belongs to another identity subject."); + } + + public void RequireLive(IUnitOfWork unit) + { + if (!ReferenceEquals(unit, _unit) || !unit.HasActiveTransaction || unit.IsRollbackOnly + || unit.Mode != TransactionMode.ReadWrite || !ReferenceEquals(unit.Connection, _connection) + || !ReferenceEquals(unit.Transaction, _transaction) || _announcement.Generation <= 0 + || _unit.GetGlobalIdentityAnnouncement(_transaction) != _announcement) + throw new InvalidOperationException("The creation reference no longer belongs to its live owner."); + } + + public void RequireIntent(AuditIntent intent) + { + if (!ReferenceEquals(intent.GlobalIdentity, this) || intent.Id != AuditId || intent.DeclaredAt != Timestamp + || intent.TenantId != TenantId.PlatformSentinel || intent.OrganizationId is not null + || intent.ActorUserId != ActorUserId || intent.ModuleName != "identity" || intent.Operation != Operation + || intent.OperationClass != OperationClass.Must || intent.OperationType != OperationType.SecurityEvent + || intent.EntityType != Descriptor.EntityType || intent.SubjectId != TargetUserId.Value.ToString("D") + || intent.CausationId is not null || intent.CausalActorUserId is not null + || intent.JobId is not null || intent.ParentJobId is not null) + throw new ArgumentException("The global identity intent differs from its captured creation reference."); + } + + public static DateTimeOffset NormalizeTimestamp(DateTimeOffset value) => + new(value.UtcTicks - value.UtcTicks % 10, TimeSpan.Zero); + + public DateTimeOffset ReconciliationTimestamp(DateTimeOffset now) + { + var normalized = NormalizeTimestamp(now); + return normalized == Timestamp ? normalized.AddTicks(10) : normalized; + } + + public override string ToString() => nameof(GlobalIdentityCreationReference); + +#pragma warning disable CA1034 // Only the censused common audit source may mint the privately constructed reference. + public abstract class MintingSource +#pragma warning restore CA1034 + { + protected static GlobalIdentityCreationReference Mint(IGlobalIdentityUnitOfWork unit, + GlobalIdentityContextAnnouncement announcement, UserId targetUserId, AuditEntryId auditId, + DateTimeOffset timestamp) => new(unit, announcement, targetUserId, auditId, timestamp); + } +} diff --git a/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs b/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs index 85f8c026f..e5c48a10a 100644 --- a/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs +++ b/backend/src/LearnStack.SharedKernel/Audit/IAuditStore.cs @@ -4,7 +4,7 @@ namespace LearnStack.SharedKernel.Audit; /// -/// The only sanctioned way to put a row in audit_log. Six writes, and +/// The only sanctioned way to put a row in audit_log. Eight writes, and /// no update. /// /// @@ -34,6 +34,14 @@ namespace LearnStack.SharedKernel.Audit; /// public interface IAuditStore { + /// Writes the enrolled global creation intent on its original live owner. + Task WriteGlobalIdentityPendingAsync(IUnitOfWork unitOfWork, GlobalIdentityCreationReference creation, + CancellationToken cancellationToken = default); + + /// Reconciles only captured failed/indeterminate global creation in a fresh bounded transaction. + Task ReconcileGlobalIdentityAsync(AuditIntent intent, IReadOnlyList changes, + AuditIntentState state, DateTimeOffset timestamp, CancellationToken cancellationToken = default); + /// /// Writes every pending MUST-class intent on the ambient transaction, /// immediately before COMMIT. A no-op when nothing is pending. diff --git a/backend/src/LearnStack.SharedKernel/DataProtection/PersonalDataCategory.cs b/backend/src/LearnStack.SharedKernel/DataProtection/PersonalDataCategory.cs new file mode 100644 index 000000000..e5c548681 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/DataProtection/PersonalDataCategory.cs @@ -0,0 +1,13 @@ +namespace LearnStack.SharedKernel.DataProtection; + +/// Explicit semantic classification of a mapped property (ADR-0073). +/// Zero is deliberately invalid: nonpersonal data requires an explicit None declaration. +public enum PersonalDataCategory +{ + None = 1, + Identity = 2, + Behaviour = 3, + Sensitive = 4, + Payment = 5, + Audit = 6, +} diff --git a/backend/src/LearnStack.SharedKernel/Identifiers/IdentityAuthorityId.cs b/backend/src/LearnStack.SharedKernel/Identifiers/IdentityAuthorityId.cs new file mode 100644 index 000000000..a2181c501 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Identifiers/IdentityAuthorityId.cs @@ -0,0 +1,7 @@ +using Vogen; + +namespace LearnStack.SharedKernel.Identifiers; + +/// The deployment-installed identity authority, independent of its current issuer address. +[ValueObject(LearnStackVogenDefaults.IdMask)] +public readonly partial record struct IdentityAuthorityId : IStronglyTypedId; diff --git a/backend/src/LearnStack.SharedKernel/Identifiers/UserId.cs b/backend/src/LearnStack.SharedKernel/Identifiers/UserId.cs index cd4abc65b..bb7c2524f 100644 --- a/backend/src/LearnStack.SharedKernel/Identifiers/UserId.cs +++ b/backend/src/LearnStack.SharedKernel/Identifiers/UserId.cs @@ -7,12 +7,12 @@ namespace LearnStack.SharedKernel.Identifiers; /// Lives in (per ADR-0023's /// cross-cutting value-object placement) so audit metadata and other /// kernel surfaces can reference users without depending on the Identity -/// module whose domain lands in Phase 03. The Identity module consumes the same -/// type once it ships; there is exactly one UserId shape. +/// module. The Identity module consumes the same type; there is exactly one +/// UserId shape. /// /// /// There is no UserId.New() convenience: new -/// values are minted by aggregate methods through the injected +/// values are minted by admitted owners through the injected /// IGuidFactory (UserId.From(guidFactory.NewUuidV7())) so /// tests can pin the value deterministically — see Standards 02 § Time. /// @@ -43,13 +43,14 @@ namespace LearnStack.SharedKernel.Identifiers; /// It is not a foreign key, and needs no users row. /// created_by, updated_by, deleted_by and /// audit_log.actor_user_id carry no referential constraint anywhere in - /// the schema, so an actor identifier can remain after the user row is erased. + /// the schema, so an actor identifier can remain independently of account closure. + /// ADR-0072 retains the global binding/tombstone rather than deleting that row. /// It preserves audit continuity but remains pseudonymous and may be linked to /// a person through other retained records; erasing the user row alone does not /// establish anonymization. An enforced foreign key would require an explicit /// deletion policy for these retained references. See /// ADR-0038 - /// Amendment 1; the users table itself is owned by Phase 03. + /// Amendment 1; the users table itself is owned by Identity. /// /// public static UserId SystemActor { get; } = diff --git a/backend/src/LearnStack.SharedKernel/Identity/GlobalIdentityContextAnnouncement.cs b/backend/src/LearnStack.SharedKernel/Identity/GlobalIdentityContextAnnouncement.cs new file mode 100644 index 000000000..81fa67880 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Identity/GlobalIdentityContextAnnouncement.cs @@ -0,0 +1,10 @@ +namespace LearnStack.SharedKernel.Identity; + +/// Read-only evidence for the exact descriptor announced on one physical transaction generation. +public sealed record GlobalIdentityContextAnnouncement(long Generation, GlobalIdentityOwnerDescriptor Descriptor); + +/// Scoped read-only view used by context-instance EF self filters. +public interface IGlobalIdentityScopeAccessor +{ + GlobalIdentityContextAnnouncement? Current { get; } +} diff --git a/backend/src/LearnStack.SharedKernel/Identity/GlobalIdentityOwnerDescriptor.cs b/backend/src/LearnStack.SharedKernel/Identity/GlobalIdentityOwnerDescriptor.cs new file mode 100644 index 000000000..d8366030c --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Identity/GlobalIdentityOwnerDescriptor.cs @@ -0,0 +1,57 @@ +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.SharedKernel.Identity; + +public enum GlobalIdentityOwnerKind { Lookup = 1, Bootstrap = 2, SeedAdoption = 3 } + +/// Closed provenance for one internal owner. Only enumerated production minters may derive its source. +public sealed class GlobalIdentityOwnerDescriptor +{ + private GlobalIdentityOwnerDescriptor(GlobalIdentitySubject subject, GlobalIdentityOwnerKind kind, + Type contextType, Type entityType, UserId? seedActor) + { + ArgumentNullException.ThrowIfNull(subject); + ArgumentNullException.ThrowIfNull(contextType); + ArgumentNullException.ThrowIfNull(entityType); + if (!Enum.IsDefined(kind) || contextType.IsAbstract || entityType.IsAbstract + || (kind == GlobalIdentityOwnerKind.SeedAdoption + && (seedActor is not { } actor || !actor.IsInitialized() || actor.Value.Version != 7 + || actor == UserId.SystemActor)) + || (kind != GlobalIdentityOwnerKind.SeedAdoption && seedActor is not null)) + throw new ArgumentException("Global identity owner provenance is invalid."); + Subject = subject; + Kind = kind; + ContextType = contextType; + EntityType = entityType; + SeedActor = seedActor; + } + + public GlobalIdentitySubject Subject { get; } + public GlobalIdentityOwnerKind Kind { get; } + public Type ContextType { get; } + public Type EntityType { get; } + public UserId? SeedActor { get; } + public string Source => Kind switch + { + GlobalIdentityOwnerKind.Bootstrap => "identity-bootstrap", + GlobalIdentityOwnerKind.SeedAdoption => "identity-seed-adoption", + _ => throw new InvalidOperationException("A lookup has no creation audit source."), + }; + + public override string ToString() => nameof(GlobalIdentityOwnerDescriptor); + +#pragma warning disable CA1034 // Private construction and a closed minting-source census preserve provenance. + public abstract class MintingSource +#pragma warning restore CA1034 + { + protected static GlobalIdentityOwnerDescriptor ForLookup(GlobalIdentitySubject subject, + Type contextType, Type entityType) => new(subject, GlobalIdentityOwnerKind.Lookup, contextType, entityType, null); + + protected static GlobalIdentityOwnerDescriptor ForBootstrap(GlobalIdentitySubject subject, + Type contextType, Type entityType) => new(subject, GlobalIdentityOwnerKind.Bootstrap, contextType, entityType, null); + + protected static GlobalIdentityOwnerDescriptor ForSeedAdoption(GlobalIdentitySubject subject, + UserId actor, Type contextType, Type entityType) => + new(subject, GlobalIdentityOwnerKind.SeedAdoption, contextType, entityType, actor); + } +} diff --git a/backend/src/LearnStack.SharedKernel/Identity/GlobalIdentitySubject.cs b/backend/src/LearnStack.SharedKernel/Identity/GlobalIdentitySubject.cs new file mode 100644 index 000000000..10ece65a9 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Identity/GlobalIdentitySubject.cs @@ -0,0 +1,31 @@ +using LearnStack.SharedKernel.Domain; +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.SharedKernel.Identity; + +/// Exact qualified provider facts. Possession of this value does not authorize creation or adoption. +public sealed class GlobalIdentitySubject +{ + public GlobalIdentitySubject(IdentityAuthorityId authorityId, string issuer, string subject) + { + if (!authorityId.IsInitialized() || authorityId.Value == Guid.Empty + || string.IsNullOrWhiteSpace(issuer) || issuer.Length > 2048 + || !Uri.TryCreate(issuer, UriKind.Absolute, out var address) + || address.Scheme is not ("http" or "https") + || !string.IsNullOrEmpty(address.UserInfo) || !string.IsNullOrEmpty(address.Fragment) + || string.IsNullOrWhiteSpace(subject) || subject.Length > 255 || !JsonValue.IsStorableText(subject)) + throw new ArgumentException("Qualified identity subject facts are invalid."); + + AuthorityId = authorityId; + Issuer = issuer; + Subject = subject; + SubjectKey = IdentitySubjectKey.Compute(authorityId, subject); + } + + public IdentityAuthorityId AuthorityId { get; } + public string Issuer { get; } + public string Subject { get; } + public IdentitySubjectKey SubjectKey { get; } + + public override string ToString() => nameof(GlobalIdentitySubject); +} diff --git a/backend/src/LearnStack.SharedKernel/Identity/IGlobalIdentityEnrollment.cs b/backend/src/LearnStack.SharedKernel/Identity/IGlobalIdentityEnrollment.cs new file mode 100644 index 000000000..e6c64c295 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Identity/IGlobalIdentityEnrollment.cs @@ -0,0 +1,7 @@ +namespace LearnStack.SharedKernel.Identity; + +/// Scoped read-only enrollment state. Reading it never creates a unit, connection or data source. +public interface IGlobalIdentityEnrollment +{ + bool IsActive { get; } +} diff --git a/backend/src/LearnStack.SharedKernel/Identity/IIdentityMutationLocks.cs b/backend/src/LearnStack.SharedKernel/Identity/IIdentityMutationLocks.cs new file mode 100644 index 000000000..e816a22a4 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Identity/IIdentityMutationLocks.cs @@ -0,0 +1,35 @@ +using System.Collections.Immutable; +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.SharedKernel.Identity; + +public enum IdentityTenantLockMode { Shared = 1, Exclusive = 2 } + +/// Complete ordered contextual mutation plan; never a caller's authorization assertion. +public sealed record IdentityMutationLockPlan +{ + public IdentityMutationLockPlan(IEnumerable userIds, TenantId tenantId, IdentityTenantLockMode tenantMode) + { + ArgumentNullException.ThrowIfNull(userIds); + if (!tenantId.IsInitialized() || tenantId.Value == Guid.Empty || tenantId == TenantId.PlatformSentinel) + throw new ArgumentException("Identity mutation tenant is invalid.", nameof(tenantId)); + if (!Enum.IsDefined(tenantMode)) throw new ArgumentOutOfRangeException(nameof(tenantMode)); + var users = userIds.ToImmutableArray(); + if (users.Any(user => !user.IsInitialized() || user.Value == Guid.Empty || user == UserId.SystemActor)) + throw new ArgumentException("Identity mutation target is invalid.", nameof(userIds)); + UserIds = users.Distinct().OrderBy(IdentityAdvisoryLockKey.ForUser).ToImmutableArray(); + TenantId = tenantId; + TenantMode = tenantMode; + } + + public ImmutableArray UserIds { get; } + public TenantId TenantId { get; } + public IdentityTenantLockMode TenantMode { get; } +} + +/// Transaction-bound User-before-tenant locking on the current trusted tenant owner. +public interface IIdentityMutationLocks +{ + Task AcquireAsync(IdentityMutationLockPlan plan, CancellationToken cancellationToken = default); + void RequireCurrent(IdentityMutationLockPlan plan); +} diff --git a/backend/src/LearnStack.SharedKernel/Identity/IdentityAdvisoryLockKey.cs b/backend/src/LearnStack.SharedKernel/Identity/IdentityAdvisoryLockKey.cs new file mode 100644 index 000000000..378728def --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Identity/IdentityAdvisoryLockKey.cs @@ -0,0 +1,48 @@ +using System.Buffers.Binary; +using System.Security.Cryptography; +using System.Text; +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.SharedKernel.Identity; + +/// Stable database lock keys; collisions serialize unrelated work and never grant authority. +public static class IdentityAdvisoryLockKey +{ + public static long ForUser(UserId userId) + { + if (!userId.IsInitialized() || userId.Value == Guid.Empty || userId == UserId.SystemActor) + throw new ArgumentException("Identity lock target is invalid.", nameof(userId)); + return ForIdentifier("user", userId.Value); + } + + public static long ForTenant(TenantId tenantId) + { + if (!tenantId.IsInitialized() || tenantId.Value == Guid.Empty || tenantId == TenantId.PlatformSentinel) + throw new ArgumentException("Identity lock tenant is invalid.", nameof(tenantId)); + return ForIdentifier("tenant", tenantId.Value); + } + + public static long ForSubject(GlobalIdentitySubject subject) + { + ArgumentNullException.ThrowIfNull(subject); + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + IdentitySubjectKey.Append(hash, Encoding.UTF8.GetBytes("learnstack.identity.lock.v1")); + IdentitySubjectKey.Append(hash, Encoding.UTF8.GetBytes("subject")); + Span authority = stackalloc byte[16]; + subject.AuthorityId.Value.TryWriteBytes(authority, bigEndian: true, out _); + IdentitySubjectKey.Append(hash, authority); + IdentitySubjectKey.Append(hash, subject.SubjectKey.ToByteArray()); + return BinaryPrimitives.ReadInt64BigEndian(hash.GetHashAndReset()); + } + + private static long ForIdentifier(string kind, Guid identifier) + { + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + IdentitySubjectKey.Append(hash, Encoding.UTF8.GetBytes("learnstack.identity.lock.v1")); + IdentitySubjectKey.Append(hash, Encoding.UTF8.GetBytes(kind)); + Span bytes = stackalloc byte[16]; + identifier.TryWriteBytes(bytes, bigEndian: true, out _); + IdentitySubjectKey.Append(hash, bytes); + return BinaryPrimitives.ReadInt64BigEndian(hash.GetHashAndReset()); + } +} diff --git a/backend/src/LearnStack.SharedKernel/Identity/IdentityMutationLockException.cs b/backend/src/LearnStack.SharedKernel/Identity/IdentityMutationLockException.cs new file mode 100644 index 000000000..d8992df13 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Identity/IdentityMutationLockException.cs @@ -0,0 +1,9 @@ +using LearnStack.SharedKernel.Errors; + +namespace LearnStack.SharedKernel.Identity; + +/// Fixed lock-plan failure, without provider payload or target information. +public sealed class IdentityMutationLockException : InfrastructureException +{ + public IdentityMutationLockException() : base("Identity mutation admission was refused.") { } +} diff --git a/backend/src/LearnStack.SharedKernel/Identity/IdentitySubjectKey.cs b/backend/src/LearnStack.SharedKernel/Identity/IdentitySubjectKey.cs new file mode 100644 index 000000000..12644fc87 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Identity/IdentitySubjectKey.cs @@ -0,0 +1,61 @@ +using System.Buffers.Binary; +using System.Security.Cryptography; +using System.Text; +using LearnStack.SharedKernel.Domain; +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.SharedKernel.Identity; + +/// Immutable, linkable subject digest. This value supplies neither secrecy nor admission authority. +public sealed class IdentitySubjectKey : IEquatable +{ + private readonly byte[] _bytes; + + private IdentitySubjectKey(byte[] bytes) + { + _bytes = bytes.ToArray(); + Hex = Convert.ToHexStringLower(_bytes); + } + + public string Hex { get; } + + public byte[] ToByteArray() => _bytes.ToArray(); + + public static IdentitySubjectKey FromBytes(ReadOnlySpan bytes) + { + if (bytes.Length != 32) throw new ArgumentException("An identity subject key requires exactly 32 bytes."); + return new IdentitySubjectKey(bytes.ToArray()); + } + + public static IdentitySubjectKey Compute(IdentityAuthorityId authorityId, string subject) + { + if (!authorityId.IsInitialized() || authorityId.Value == Guid.Empty + || string.IsNullOrWhiteSpace(subject) || subject.Length > 255 || !JsonValue.IsStorableText(subject)) + throw new ArgumentException("Identity subject-key inputs are invalid."); + + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + Append(hash, Encoding.UTF8.GetBytes("learnstack.identity.subject.v1")); + Span authority = stackalloc byte[16]; + authorityId.Value.TryWriteBytes(authority, bigEndian: true, out _); + Append(hash, authority); + Append(hash, Encoding.UTF8.GetBytes(subject)); + return new IdentitySubjectKey(hash.GetHashAndReset()); + } + + internal static void Append(IncrementalHash hash, ReadOnlySpan value) + { + Span length = stackalloc byte[4]; + BinaryPrimitives.WriteUInt32BigEndian(length, checked((uint)value.Length)); + hash.AppendData(length); + hash.AppendData(value); + } + + public bool Equals(IdentitySubjectKey? other) => other is not null + && string.Equals(Hex, other.Hex, StringComparison.Ordinal); + + public override bool Equals(object? obj) => obj is IdentitySubjectKey other && Equals(other); + + public override int GetHashCode() => StringComparer.Ordinal.GetHashCode(Hex); + + public override string ToString() => nameof(IdentitySubjectKey); +} diff --git a/backend/src/LearnStack.SharedKernel/Localization/LocaleTag.cs b/backend/src/LearnStack.SharedKernel/Localization/LocaleTag.cs index bc4bccad0..e868ff159 100644 --- a/backend/src/LearnStack.SharedKernel/Localization/LocaleTag.cs +++ b/backend/src/LearnStack.SharedKernel/Localization/LocaleTag.cs @@ -23,12 +23,15 @@ public static partial class LocaleTag /// public const int MaxLength = 35; + /// Checks shape without allocating an exception containing the supplied locale. + public static bool IsWellFormed(string? value) => value is not null && Pattern().IsMatch(value); + public static void EnsureWellFormed(string value, string parameterName) { // Shape first, then the framework. CultureInfo alone is not a check: // .NET treats an unknown but well-formed tag as a valid custom culture, // and on some platforms accepts tags this pattern rejects. - if (!Pattern().IsMatch(value)) + if (!IsWellFormed(value)) { throw new ArgumentException( $"'{value}' is not a well-formed BCP-47 language tag — expected forms are " diff --git a/backend/src/LearnStack.SharedKernel/Permissions/PermissionDefinition.cs b/backend/src/LearnStack.SharedKernel/Permissions/PermissionDefinition.cs new file mode 100644 index 000000000..0fdf79253 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Permissions/PermissionDefinition.cs @@ -0,0 +1,39 @@ +namespace LearnStack.SharedKernel.Permissions; + +public enum PermissionScope { Platform = 1, Tenant = 2, Organization = 3 } + +public enum BuiltInRoleKey +{ + TenantAdmin = 1, Instructor = 2, Learner = 3, Guardian = 4, Editor = 5, + OrgAdmin = 6, OrgInstructor = 7, +} + +/// A scoped capability definition; registration alone grants no authority. +public sealed record PermissionDefinition +{ + public PermissionDefinition(PermissionScope scope, string key, bool isActive = true) + { + if (!Enum.IsDefined(scope)) throw new ArgumentOutOfRangeException(nameof(scope)); + ArgumentNullException.ThrowIfNull(key); + var segments = key.Split('.'); + if (segments.Length != 3 || !IsSegment(segments[0]) || !IsSegment(segments[1]) + || segments[2] is not ("read" or "write" or "delete" or "admin")) + throw new ArgumentException("Permission definition is invalid.", nameof(key)); + Scope = scope; + Key = key; + IsActive = isActive; + } + + public PermissionScope Scope { get; } + public string Key { get; } + public bool IsActive { get; } + + private static bool IsSegment(string value) => value.Length > 0 && value[0] is >= 'a' and <= 'z' + && value.All(character => character is >= 'a' and <= 'z' or >= '0' and <= '9' or '_'); +} + +/// Finite operation metadata, independent of seed or live admission. +public interface IIdentityPermissionRequest +{ + PermissionDefinition RequiredPermission { get; } +} diff --git a/backend/src/LearnStack.SharedKernel/Persistence/IGlobalIdentityUnitOfWork.cs b/backend/src/LearnStack.SharedKernel/Persistence/IGlobalIdentityUnitOfWork.cs new file mode 100644 index 000000000..0867a9eb7 --- /dev/null +++ b/backend/src/LearnStack.SharedKernel/Persistence/IGlobalIdentityUnitOfWork.cs @@ -0,0 +1,26 @@ +using System.Data.Common; +using LearnStack.SharedKernel.Identity; + +namespace LearnStack.SharedKernel.Persistence; + +/// Exact global-self authority on the common ambient connection; not tenant authority or a general SQL executor. +public interface IGlobalIdentityUnitOfWork : IUnitOfWork +{ + bool IsGlobalIdentityTransaction { get; } + + Task BeginGlobalIdentityTransactionAsync(GlobalIdentityOwnerDescriptor descriptor, + TransactionMode mode, CancellationToken cancellationToken = default); + + GlobalIdentityContextAnnouncement? GetGlobalIdentityAnnouncement(DbTransaction? transaction); + + Task AcquireGlobalIdentitySubjectLockAsync(GlobalIdentityOwnerDescriptor descriptor, + CancellationToken cancellationToken = default); + + void EnrollGlobalIdentityContext(object context, GlobalIdentityOwnerDescriptor descriptor); + + bool IsGlobalIdentityContextEnrolled(object context, DbTransaction? transaction); + + /// Validates deferred guards and seals further EF/capture mutation before physical COMMIT admission. + Task ValidateGlobalIdentityConstraintsAsync(GlobalIdentityOwnerDescriptor descriptor, + CancellationToken cancellationToken = default); +} diff --git a/backend/src/LearnStack.Tools.IdentityAuthorityInstaller/LearnStack.Tools.IdentityAuthorityInstaller.csproj b/backend/src/LearnStack.Tools.IdentityAuthorityInstaller/LearnStack.Tools.IdentityAuthorityInstaller.csproj new file mode 100644 index 000000000..7add504a2 --- /dev/null +++ b/backend/src/LearnStack.Tools.IdentityAuthorityInstaller/LearnStack.Tools.IdentityAuthorityInstaller.csproj @@ -0,0 +1,9 @@ + + + Exe + LearnStack.Tools.IdentityAuthorityInstaller + + + + + diff --git a/backend/src/LearnStack.Tools.IdentityAuthorityInstaller/Program.cs b/backend/src/LearnStack.Tools.IdentityAuthorityInstaller/Program.cs new file mode 100644 index 000000000..cd1e035ec --- /dev/null +++ b/backend/src/LearnStack.Tools.IdentityAuthorityInstaller/Program.cs @@ -0,0 +1,43 @@ +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Identifiers; +using Npgsql; + +namespace LearnStack.Tools.IdentityAuthorityInstaller; + +/// Deployment-only installation; receives migration credentials through the process environment, never argv. +internal static class Program +{ + public static async Task Main(string[] args) + { + if (args.Length != 0) return Refuse(); + try + { + var connectionString = Environment.GetEnvironmentVariable("ConnectionStrings__Migration"); + var authorityText = Environment.GetEnvironmentVariable("Identity__AuthorityId"); + var issuer = Environment.GetEnvironmentVariable("Authentication__Tenant__Issuer"); + if (string.IsNullOrWhiteSpace(connectionString) + || !Guid.TryParseExact(authorityText, "D", out var authorityId) || authorityId == Guid.Empty + || issuer is null + || new NpgsqlConnectionStringBuilder(connectionString).Username != "learnstack_migration") return Refuse(); + var registration = new IdentityAuthorityRegistration(IdentityAuthorityId.From(authorityId), issuer); + using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + await using var connection = new NpgsqlConnection(connectionString); + await connection.OpenAsync(deadline.Token); + await IdentityAuthorityDeploymentInstaller.InstallAsync(connection, registration, deadline.Token); + Console.WriteLine("identity-authority: installed or verified without changing an existing registration."); + return 0; + } +#pragma warning disable CA1031 // The deployment CLI emits fixed diagnostics, never provider/credential exception payloads. + catch (Exception) +#pragma warning restore CA1031 + { + return Refuse(); + } + } + + private static int Refuse() + { + Console.Error.WriteLine("identity-authority: installation refused; verify the migration role, stable Identity__AuthorityId and exact Authentication__Tenant__Issuer. Existing registrations are never repaired or rebound."); + return 2; + } +} diff --git a/backend/src/LearnStack.Tools.Seeder/FixedSeedIdentityFoundationAdmission.cs b/backend/src/LearnStack.Tools.Seeder/FixedSeedIdentityFoundationAdmission.cs new file mode 100644 index 000000000..6a01b64b4 --- /dev/null +++ b/backend/src/LearnStack.Tools.Seeder/FixedSeedIdentityFoundationAdmission.cs @@ -0,0 +1,79 @@ +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; + +namespace LearnStack.Tools.Seeder; + +/// Confined console capability: exactly four witnessed persons and exact retained v1 acts. +public sealed class FixedSeedIdentityFoundationAdmission : ISeedIdentityFoundationAdmission +{ + private readonly HashSet _adopted = []; + private readonly HashSet _acts = []; + + public FixedSeedIdentityFoundationAdmission(SeedProviderWitness witness) + { + ArgumentNullException.ThrowIfNull(witness); + Witness = witness; + var manifest = IdentityFoundationManifest.Version1; + if (SeedData.IdentityUsers.Length != 4 || witness.Subjects.Count != 4 + || SeedData.IdentityRoles.Length != 16 || SeedData.IdentityMemberships.Length != 4 + || SeedData.IdentityRoles.Select(role => role.RoleId).Distinct().Count() != 16 + || SeedData.IdentityMemberships.Select(member => member.MembershipId).Distinct().Count() != 4 + || SeedData.IdentityMemberships.Select(member => member.Identity.UserId).Distinct().Count() != 4 + || SeedData.IdentityUsers.Any(person => !witness.Subjects.ContainsKey(person.UserId))) throw Refused(); + foreach (var tenant in SeedData.All) + { + var roles = SeedData.IdentityRoles.Where(role => role.Tenant == tenant).ToArray(); + if (roles.Length != 8 || !roles.Select(role => (role.BuiltInKey, role.Scope)).ToHashSet() + .SetEquals(manifest.Templates.Select(template => (template.BuiltInKey, template.Scope)))) throw Refused(); + } + foreach (var role in SeedData.IdentityRoles) + foreach (var operation in new[] { SeedIdentityFoundationOperation.InitializeRole, SeedIdentityFoundationOperation.VerifyRole }) + _acts.Add(new(operation, role.Tenant.TenantId, null, UserId.SystemActor, role.RoleId, + null, null, role.BuiltInKey, role.Scope, manifest.Version, + manifest.RoleFingerprint(role.Tenant.TenantId, role.RoleId, role.BuiltInKey, role.Scope))); + foreach (var member in SeedData.IdentityMemberships) + { + if (!witness.Subjects.ContainsKey(member.Identity.UserId) || member.Identity.Tenant != member.Role.Tenant + || member.Scope != member.Role.Scope) throw Refused(); + foreach (var operation in new[] { member.IsFirstAdmin ? SeedIdentityFoundationOperation.CreateFirstAdmin + : SeedIdentityFoundationOperation.CreateMembership, SeedIdentityFoundationOperation.VerifyMembership }) + _acts.Add(new(operation, member.Identity.Tenant.TenantId, member.OrganizationId, UserId.SystemActor, + member.MembershipId, member.Identity.UserId, member.Role.RoleId, null, member.Scope, manifest.Version, + manifest.MembershipFingerprint(member.Identity.Tenant.TenantId, member.OrganizationId, + member.MembershipId, member.Identity.UserId, member.Role.RoleId))); + _acts.Add(new(SeedIdentityFoundationOperation.SetProfile, member.Identity.Tenant.TenantId, member.OrganizationId, + UserId.SystemActor, member.MembershipId, member.Identity.UserId, member.Role.RoleId, null, member.Scope, manifest.Version, + manifest.ProfileFingerprint(member.Identity.Tenant.TenantId, member.OrganizationId, member.MembershipId, + member.DisplayName, member.PreferredLocale))); + } + } + + public SeedProviderWitness Witness { get; } + + public ValueTask AllowsAsync(GlobalIdentitySubject subject, UserId declaredActor, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + return ValueTask.FromResult(subject is not null && Witness.Subjects.TryGetValue(declaredActor, out var expected) + && subject.AuthorityId == expected.AuthorityId && string.Equals(subject.Issuer, expected.Issuer, StringComparison.Ordinal) + && string.Equals(subject.Subject, expected.Subject, StringComparison.Ordinal)); + } + + public ValueTask AllowsFoundationAsync(SeedIdentityFoundationAct act, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + return ValueTask.FromResult(_adopted.Count == 4 && _acts.Contains(act)); + } + + internal void RecordAdopted(UserId actor) + { + if (!Witness.Subjects.ContainsKey(actor)) throw Refused(); + _adopted.Add(actor); + } + + public override string ToString() => nameof(FixedSeedIdentityFoundationAdmission); + private static InvalidOperationException Refused() => new("Development identity declaration was refused."); +} diff --git a/backend/src/LearnStack.Tools.Seeder/LearnStack.Tools.Seeder.csproj b/backend/src/LearnStack.Tools.Seeder/LearnStack.Tools.Seeder.csproj index 7bbe99a7b..1d583284d 100644 --- a/backend/src/LearnStack.Tools.Seeder/LearnStack.Tools.Seeder.csproj +++ b/backend/src/LearnStack.Tools.Seeder/LearnStack.Tools.Seeder.csproj @@ -21,6 +21,8 @@ + + diff --git a/backend/src/LearnStack.Tools.Seeder/Program.cs b/backend/src/LearnStack.Tools.Seeder/Program.cs index c82846a65..2bf54237b 100644 --- a/backend/src/LearnStack.Tools.Seeder/Program.cs +++ b/backend/src/LearnStack.Tools.Seeder/Program.cs @@ -3,6 +3,9 @@ using Microsoft.Extensions.Logging; using LearnStack.Infrastructure.Persistence; using System.Text.Json; +using System.Runtime.InteropServices; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Identifiers; // Read-only tooling projection: no data source, seeding side effect or credentials. if (args is ["--demo-identities"]) @@ -28,7 +31,8 @@ return 2; } } -if (args.Length != 0) +var identityFoundation = args is ["--identity-foundation-stdin"]; +if (args.Length != 0 && !identityFoundation) { Console.Error.WriteLine("seed: unsupported arguments."); return 2; @@ -59,17 +63,42 @@ // One data source for the whole run, shared by every per-act provider: a seeder that // opened a pool per command would leave an idle connection behind for each one. using var loggerFactory = LoggerFactory.Create(logging => logging.AddSimpleConsole()); +using var cancellation = new CancellationTokenSource(); +Console.CancelKeyPress += (_, eventArgs) => { eventArgs.Cancel = true; cancellation.Cancel(); }; +using var terminate = OperatingSystem.IsWindows() ? null : PosixSignalRegistration.Create(PosixSignal.SIGTERM, + signal => { signal.Cancel = true; cancellation.Cancel(); }); +using var hangup = OperatingSystem.IsWindows() ? null : PosixSignalRegistration.Create(PosixSignal.SIGHUP, + signal => { signal.Cancel = true; cancellation.Cancel(); }); try { await using var dataSource = ApplicationDataSource.Build(connectionString); + if (identityFoundation) + { + if (!Guid.TryParseExact(Environment.GetEnvironmentVariable("Identity__AuthorityId"), "D", out var authorityId)) + throw new InvalidOperationException("Identity authority configuration is invalid."); + var registration = new IdentityAuthorityRegistration(IdentityAuthorityId.From(authorityId), + Environment.GetEnvironmentVariable("Authentication__Tenant__Issuer") ?? ""); + var witness = await SeedProviderWitness.ReadAsync(Console.OpenStandardInput(), registration, cancellation.Token); + var admission = new FixedSeedIdentityFoundationAdmission(witness); + var identityRunner = new SeedIdentityFoundationRunner( + context => SeedComposition.Build(dataSource, context, loggerFactory, + identityAuthority: registration, seedAdmission: admission), admission); + await identityRunner.RunAsync(cancellation.Token); + return 0; + } var runner = new SeedRunner( context => SeedComposition.Build(dataSource, context, loggerFactory), loggerFactory.CreateLogger()); - return await runner.RunAsync(CancellationToken.None); + return await runner.RunAsync(cancellation.Token); } catch (Exception failure) { + if (identityFoundation) + { + Console.Error.WriteLine("seed: development identity foundation was refused."); + return 1; + } // Non-zero, and nothing else: `make seed` is a gate, and a seeder that reported // success after failing would hand the next step a database it cannot use. The // message reaches the operator through the logger, which is already on the console. diff --git a/backend/src/LearnStack.Tools.Seeder/SeedComposition.cs b/backend/src/LearnStack.Tools.Seeder/SeedComposition.cs index 29bed24eb..6387ea307 100644 --- a/backend/src/LearnStack.Tools.Seeder/SeedComposition.cs +++ b/backend/src/LearnStack.Tools.Seeder/SeedComposition.cs @@ -1,4 +1,6 @@ using LearnStack.Infrastructure.Jobs; +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Infrastructure.Bindings; using LearnStack.Modules.Customization.Infrastructure; using LearnStack.Modules.Customization.Application.Contracts.Definitions; using LearnStack.Modules.Tenancy.Application.Contracts.Locales; @@ -74,7 +76,9 @@ public static ServiceProvider Build( NpgsqlDataSource dataSource, ITenantContext? context, ILoggerFactory loggerFactory, - IReservedHostRegistry? reservedHosts = null) + IReservedHostRegistry? reservedHosts = null, + IdentityAuthorityRegistration? identityAuthority = null, + ISeedIdentityFoundationAdmission? seedAdmission = null) { ArgumentNullException.ThrowIfNull(dataSource); ArgumentNullException.ThrowIfNull(loggerFactory); @@ -95,6 +99,9 @@ public static ServiceProvider Build( provider.GetRequiredService().Current ?? UnresolvedTenantContext.Instance); + services.TryAddScoped(); + services.TryAddScoped(provider => + provider.GetRequiredService()); services.AddScoped(); services.AddModuleDbContext(); services.AddTenantSettingsReads(); @@ -103,6 +110,8 @@ public static ServiceProvider Build( services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); // The Customization module, for act three. Its context goes through the same @@ -236,6 +245,9 @@ public static ServiceProvider Build( // answer, and it must not be able to see uncommitted state from that write. services.AddSingleton(new Lazy(() => dataSource)); services.AddSingleton(); + if (seedAdmission is not null) services.AddSingleton(seedAdmission); + services.AddIdentityGlobalFoundation(identityAuthority); + services.AddIdentityContextualFoundation(); // Fronts no cache: a one-shot process has nothing in memory to go stale, and the // default answers truthfully for that host rather than approximating the API's. @@ -245,7 +257,8 @@ public static ServiceProvider Build( services.AddLearnStackMediatRPipeline( typeof(ITenantWriteStore).Assembly, typeof(ITenantContentTypeStore).Assembly, - typeof(LearnStack.Modules.Education.Application.AssemblyMarker).Assembly); + typeof(LearnStack.Modules.Education.Application.AssemblyMarker).Assembly, + typeof(LearnStack.Modules.Identity.Application.AssemblyMarker).Assembly); return services.BuildServiceProvider(); } diff --git a/backend/src/LearnStack.Tools.Seeder/SeedData.cs b/backend/src/LearnStack.Tools.Seeder/SeedData.cs index e684d243a..5d6180789 100644 --- a/backend/src/LearnStack.Tools.Seeder/SeedData.cs +++ b/backend/src/LearnStack.Tools.Seeder/SeedData.cs @@ -1,6 +1,7 @@ using System.Collections.Immutable; using LearnStack.Modules.Customization.Application.Contracts.Customization; using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; namespace LearnStack.Tools.Seeder; @@ -27,7 +28,7 @@ public static class SeedData YogaCurriculum()); public static readonly IReadOnlyList All = [English, Yoga]; - // Authentication personas are development data, not application memberships. + // Authentication personas retain provider claims independently of Membership scope. // The legacy usernames retain their Keycloak subjects/passwords on warm upgrades. public static readonly ImmutableArray IdentityUsers = [ @@ -41,6 +42,39 @@ public static class SeedData "demo-learner@tenant-b.test", "Demo", "Learner", "tenant-learner", new("account", "manage-account")), ]; + public static readonly ImmutableArray IdentityRoles = + [ + new(English, Id("01916d82-4b10-7000-8000-00000000a101"), BuiltInRoleKey.TenantAdmin, PermissionScope.Tenant), + new(English, Id("01916d82-4b10-7000-8000-00000000a102"), BuiltInRoleKey.Instructor, PermissionScope.Tenant), + new(English, Id("01916d82-4b10-7000-8000-00000000a103"), BuiltInRoleKey.Learner, PermissionScope.Tenant), + new(English, Id("01916d82-4b10-7000-8000-00000000a104"), BuiltInRoleKey.Guardian, PermissionScope.Tenant), + new(English, Id("01916d82-4b10-7000-8000-00000000a105"), BuiltInRoleKey.Editor, PermissionScope.Tenant), + new(English, Id("01916d82-4b10-7000-8000-00000000a106"), BuiltInRoleKey.OrgAdmin, PermissionScope.Organization), + new(English, Id("01916d82-4b10-7000-8000-00000000a107"), BuiltInRoleKey.OrgInstructor, PermissionScope.Organization), + new(English, Id("01916d82-4b10-7000-8000-00000000a108"), BuiltInRoleKey.Learner, PermissionScope.Organization), + new(Yoga, Id("01916d82-4b10-7000-8000-00000000b101"), BuiltInRoleKey.TenantAdmin, PermissionScope.Tenant), + new(Yoga, Id("01916d82-4b10-7000-8000-00000000b102"), BuiltInRoleKey.Instructor, PermissionScope.Tenant), + new(Yoga, Id("01916d82-4b10-7000-8000-00000000b103"), BuiltInRoleKey.Learner, PermissionScope.Tenant), + new(Yoga, Id("01916d82-4b10-7000-8000-00000000b104"), BuiltInRoleKey.Guardian, PermissionScope.Tenant), + new(Yoga, Id("01916d82-4b10-7000-8000-00000000b105"), BuiltInRoleKey.Editor, PermissionScope.Tenant), + new(Yoga, Id("01916d82-4b10-7000-8000-00000000b106"), BuiltInRoleKey.OrgAdmin, PermissionScope.Organization), + new(Yoga, Id("01916d82-4b10-7000-8000-00000000b107"), BuiltInRoleKey.OrgInstructor, PermissionScope.Organization), + new(Yoga, Id("01916d82-4b10-7000-8000-00000000b108"), BuiltInRoleKey.Learner, PermissionScope.Organization), + ]; + + public static readonly ImmutableArray IdentityMemberships = + [ + new(IdentityUsers[0], Id("01916d82-4b10-7000-8000-00000000a201"), null, IdentityRoles[0], "Demo Admin", "en", true), + new(IdentityUsers[1], Id("01916d82-4b10-7000-8000-00000000a202"), null, IdentityRoles[2], "Demo Learner", "en", false), + new(IdentityUsers[2], Id("01916d82-4b10-7000-8000-00000000b201"), null, IdentityRoles[8], "Demo Admin", "tr-TR", true), + new(IdentityUsers[3], Id("01916d82-4b10-7000-8000-00000000b202"), Yoga.DefaultOrganization.OrganizationId, + IdentityRoles[15], "Demo Learner", "tr-TR", false), + ]; + + // Four global creations, sixteen Role roots, four Membership roots and four profile acts. + public static long ExpectedIdentityAuditWrites => IdentityUsers.Length + IdentityRoles.Length + IdentityMemberships.Length * 2L; + public static long ExpectedCombinedAuditWrites => ExpectedAuditWrites + ExpectedIdentityAuditWrites; + // Provisioning audits both sanctioned roots; follow-on organization and host each add one. // Each tenant initializes two built-ins once; authored definitions audit registration and publication. public static long ExpectedAuditWrites => Inventory.Tenants * 4L + Inventory.Locales @@ -186,6 +220,12 @@ public sealed record SeedIdentity(UserId UserId, SeedTenant Tenant, string Usern string FirstName, string LastName, string RealmRole, SeedAccountCapability AccountCapability, string? LegacyTenantAttribute = null); public sealed record SeedAccountCapability(string ClientId, string Role); +public sealed record SeedFoundationRole(SeedTenant Tenant, Guid RoleId, BuiltInRoleKey BuiltInKey, PermissionScope Scope); +public sealed record SeedFoundationMembership(SeedIdentity Identity, Guid MembershipId, OrganizationId? OrganizationId, + SeedFoundationRole Role, string DisplayName, string PreferredLocale, bool IsFirstAdmin) +{ + public PermissionScope Scope => OrganizationId is null ? PermissionScope.Tenant : PermissionScope.Organization; +} public sealed record SeedCurriculum(ImmutableArray Locales, SeedContentType ContentType, SeedTaxonomy Taxonomy, SeedTheme Theme, ImmutableArray Courses); public sealed record SeedLocale(string Locale, bool IsEnabled, bool IsDefault, short Sort); diff --git a/backend/src/LearnStack.Tools.Seeder/SeedIdentityFoundationRunner.cs b/backend/src/LearnStack.Tools.Seeder/SeedIdentityFoundationRunner.cs new file mode 100644 index 000000000..4f037eb4e --- /dev/null +++ b/backend/src/LearnStack.Tools.Seeder/SeedIdentityFoundationRunner.cs @@ -0,0 +1,167 @@ +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using MediatR; +using Microsoft.Extensions.DependencyInjection; + +namespace LearnStack.Tools.Seeder; + +/// Separate root acts, with exact fresh preconditions before any mutation request. +public sealed class SeedIdentityFoundationRunner(Func compose, + FixedSeedIdentityFoundationAdmission admission) +{ + private static readonly IdentityFoundationManifest Manifest = IdentityFoundationManifest.Version1; + + public async Task RunAsync(CancellationToken cancellationToken = default) + { + foreach (var person in SeedData.IdentityUsers) + { + using var budget = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + budget.CancelAfter(TimeSpan.FromSeconds(10)); + await using var provider = compose(null); + await using var scope = provider.CreateAsyncScope(); + await scope.ServiceProvider.GetRequiredService().QualifyAsync(budget.Token); + var result = await scope.ServiceProvider.GetRequiredService() + .AdoptAsync(admission.Witness.Subjects[person.UserId], person.UserId, budget.Token); + if (!result.IsBound || result.Actor != person.UserId) throw Refused(); + admission.RecordAdopted(person.UserId); + } + // Every Role is a separate aggregate transaction. All sixteen precede Memberships. + foreach (var declaration in SeedData.IdentityRoles) + { + var context = new SeedIdentityTenantContext(declaration.Tenant.TenantId, null); + var fingerprint = Manifest.RoleFingerprint(declaration.Tenant.TenantId, declaration.RoleId, + declaration.BuiltInKey, declaration.Scope); + var query = new GetRoleSeedStateQuery(declaration.RoleId, declaration.BuiltInKey, + declaration.Scope, Manifest.Version, fingerprint); + var before = (await SendAsync(context, query, cancellationToken)).State; + if (MatchesRole(before, declaration)) continue; + await SendAsync(context, new InitializeSeedRoleCommand(declaration.RoleId, declaration.BuiltInKey, + declaration.Scope, Manifest.Version, fingerprint), cancellationToken); + if (!MatchesRole((await SendAsync(context, query, cancellationToken)).State, declaration)) throw Refused(); + } + // Establish both administrators first; an interruption retains every prior commit. + foreach (var declaration in SeedData.IdentityMemberships.OrderByDescending(member => member.IsFirstAdmin)) + { + var context = Context(declaration); + var fingerprint = MembershipFingerprint(declaration); + var query = MembershipQuery(declaration); + var before = (await SendAsync(context, query, cancellationToken)).State; + if (MatchesMembership(before, declaration)) continue; + if (declaration.IsFirstAdmin) + await SendAsync(context, new CreateFirstSeedAdminMembershipCommand(declaration.MembershipId, + declaration.Identity.UserId, declaration.Role.RoleId, Manifest.Version, fingerprint), cancellationToken); + else + await SendAsync(context, new CreateSeedMembershipCommand(declaration.MembershipId, + declaration.Identity.UserId, declaration.Role.RoleId, declaration.Scope, + Manifest.Version, fingerprint), cancellationToken); + if (!MatchesMembership((await SendAsync(context, query, cancellationToken)).State, declaration)) throw Refused(); + } + foreach (var declaration in SeedData.IdentityMemberships) + { + var context = Context(declaration); + var query = MembershipQuery(declaration); + var before = (await SendAsync(context, query, cancellationToken)).State; + if (!MatchesMembership(before, declaration)) throw Refused(); + if (MatchesProfile(before!, declaration)) continue; + await SendAsync(context, new SetSeedMembershipProfileCommand(declaration.MembershipId, + declaration.Identity.UserId, declaration.Role.RoleId, declaration.Scope, declaration.DisplayName, declaration.PreferredLocale, Manifest.Version, + Manifest.ProfileFingerprint(declaration.Identity.Tenant.TenantId, declaration.OrganizationId, + declaration.MembershipId, declaration.DisplayName, declaration.PreferredLocale)), cancellationToken); + var after = (await SendAsync(context, query, cancellationToken)).State; + if (!MatchesMembership(after, declaration) || !MatchesProfile(after!, declaration)) throw Refused(); + } + } + + private static bool MatchesRole(RoleSeedDto? row, SeedFoundationRole declaration) + { + if (row is null) return false; + var template = Manifest.FindTemplate(declaration.BuiltInKey, declaration.Scope)!; + if (row.Id != declaration.RoleId || row.TenantId != declaration.Tenant.TenantId + || row.BuiltInKey != declaration.BuiltInKey || row.PermissionScope != declaration.Scope + || row.Version != 0 || row.DeletedAt is not null || row.DeletedBy is not null + || row.Grants.Length != template.Grants.Length || !row.Grants.ToHashSet().SetEquals(template.Grants)) + throw Refused(); + return true; + } + + private static bool MatchesMembership(MembershipSeedDto? row, SeedFoundationMembership declaration) + { + if (row is null) return false; + var pristine = row.DisplayName is null && row.PreferredLocale is null && row.Version == 0; + if (row.Id != declaration.MembershipId || row.TenantId != declaration.Identity.Tenant.TenantId + || row.OrganizationId != declaration.OrganizationId || row.UserId != declaration.Identity.UserId + || row.Status != "Active" || row.DeletedAt is not null || row.DeletedBy is not null + || row.RoleIds.Length != 1 || row.RoleIds[0] != declaration.Role.RoleId + || !(pristine || MatchesProfile(row, declaration))) throw Refused(); + return true; + } + + private static bool MatchesProfile(MembershipSeedDto row, SeedFoundationMembership declaration) => + row.Version == 1 && string.Equals(row.DisplayName, declaration.DisplayName, StringComparison.Ordinal) + && string.Equals(row.PreferredLocale, declaration.PreferredLocale, StringComparison.Ordinal); + + private static string MembershipFingerprint(SeedFoundationMembership declaration) => + Manifest.MembershipFingerprint(declaration.Identity.Tenant.TenantId, declaration.OrganizationId, + declaration.MembershipId, declaration.Identity.UserId, declaration.Role.RoleId); + + private static GetMembershipSeedStateQuery MembershipQuery(SeedFoundationMembership declaration) => + new(declaration.MembershipId, declaration.Identity.UserId, declaration.Role.RoleId, + declaration.Scope, Manifest.Version, MembershipFingerprint(declaration)); + + private static SeedIdentityTenantContext Context(SeedFoundationMembership declaration) => + new(declaration.Identity.Tenant.TenantId, declaration.OrganizationId); + + private async Task SendAsync(ITenantContext context, IRequest> request, CancellationToken ct) + { + using var budget = CancellationTokenSource.CreateLinkedTokenSource(ct); + budget.CancelAfter(TimeSpan.FromSeconds(10)); + var act = Declaration(context, request); + if (!await admission.AllowsFoundationAsync(act, budget.Token)) throw Refused(); + await using var provider = compose(context); + await using var scope = provider.CreateAsyncScope(); + var result = await scope.ServiceProvider.GetRequiredService().Send(request, budget.Token); + if (!result.IsSuccess || result.Value is null) throw Refused(); + return result.Value; + } + + private static SeedIdentityFoundationAct Declaration(ITenantContext context, IRequest> request) => request switch + { + InitializeSeedRoleCommand value => Act(context, SeedIdentityFoundationOperation.InitializeRole, + value.RoleId, null, null, value.BuiltInKey, value.CapabilityScope, value.ManifestVersion, value.ExpectedFingerprint), + GetRoleSeedStateQuery value => Act(context, SeedIdentityFoundationOperation.VerifyRole, + value.RoleId, null, null, value.BuiltInKey, value.CapabilityScope, value.ManifestVersion, value.ExpectedFingerprint), + CreateFirstSeedAdminMembershipCommand value => Act(context, SeedIdentityFoundationOperation.CreateFirstAdmin, + value.MembershipId, value.UserId, value.RoleId, null, PermissionScope.Tenant, value.ManifestVersion, value.ExpectedFingerprint), + CreateSeedMembershipCommand value => Act(context, SeedIdentityFoundationOperation.CreateMembership, + value.MembershipId, value.UserId, value.RoleId, null, value.MembershipScope, value.ManifestVersion, value.ExpectedFingerprint), + GetMembershipSeedStateQuery value => Act(context, SeedIdentityFoundationOperation.VerifyMembership, + value.MembershipId, value.UserId, value.RoleId, null, value.MembershipScope, value.ManifestVersion, value.ExpectedFingerprint), + SetSeedMembershipProfileCommand value => Act(context, SeedIdentityFoundationOperation.SetProfile, + value.MembershipId, value.ExpectedUserId, value.ExpectedRoleId, null, value.MembershipScope, value.ManifestVersion, value.ExpectedFingerprint), + _ => throw Refused(), + }; + + private static SeedIdentityFoundationAct Act(ITenantContext context, SeedIdentityFoundationOperation operation, + Guid rootId, UserId? target, Guid? roleId, BuiltInRoleKey? key, PermissionScope scope, int version, string fingerprint) => + new(operation, context.TenantId, context.OrganizationId, context.UserId!.Value, rootId, + target, roleId, key, scope, version, fingerprint); + + private static InvalidOperationException Refused() => new("Development identity foundation was refused."); +} + +/// The trusted declaration supplies exact SQL scope; provider organization claims never select it. +public sealed class SeedIdentityTenantContext(TenantId tenantId, OrganizationId? organizationId) : ITenantContext +{ + public bool IsResolved => true; + public TenantContextOrigin? Origin => TenantContextOrigin.Ambient; + public TenantId TenantId => tenantId; + public OrganizationId? OrganizationId => organizationId; + public UserId? UserId => LearnStack.SharedKernel.Identifiers.UserId.SystemActor; + public string? CorrelationId => null; + public string? ModuleName => null; +} diff --git a/backend/src/LearnStack.Tools.Seeder/SeedProviderWitness.cs b/backend/src/LearnStack.Tools.Seeder/SeedProviderWitness.cs new file mode 100644 index 000000000..9a28d9c4c --- /dev/null +++ b/backend/src/LearnStack.Tools.Seeder/SeedProviderWitness.cs @@ -0,0 +1,79 @@ +using System.Text.Json; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; + +namespace LearnStack.Tools.Seeder; + +/// Bounded private provider facts supplied by the external development lock owner. +/// Facts are not authority; the fixed seed admission separately checks every declaration. +public sealed class SeedProviderWitness +{ + private SeedProviderWitness(IdentityAuthorityRegistration registration, IReadOnlyDictionary subjects) + { + Registration = registration; + Subjects = subjects; + } + + public IdentityAuthorityRegistration Registration { get; } + public IReadOnlyDictionary Subjects { get; } + + public static async Task ReadAsync(Stream input, + IdentityAuthorityRegistration registration, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(registration); + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + deadline.CancelAfter(TimeSpan.FromSeconds(5)); + var bytes = new byte[8193]; + var length = 0; + while (length < bytes.Length) + { + var count = await input.ReadAsync(bytes.AsMemory(length), deadline.Token).AsTask().WaitAsync(deadline.Token); + if (count == 0) break; + length += count; + } + if (length is 0 or > 8192) throw Refused(); + try + { + using var json = JsonDocument.Parse(bytes.AsMemory(0, length), new JsonDocumentOptions { MaxDepth = 4 }); + var root = json.RootElement; + ExactMembers(root, "version", "issuer", "users"); + if (!root.GetProperty("version").TryGetInt32(out var version) || version != 1 + || root.GetProperty("issuer").GetString() != registration.Issuer + || root.GetProperty("users").ValueKind != JsonValueKind.Array + || root.GetProperty("users").GetArrayLength() != 4) throw Refused(); + var subjects = new Dictionary(); + var providerIds = new HashSet(StringComparer.Ordinal); + foreach (var entry in root.GetProperty("users").EnumerateArray()) + { + ExactMembers(entry, "actorId", "opaqueSub"); + if (!entry.GetProperty("actorId").TryGetGuid(out var actorValue)) throw Refused(); + var actor = UserId.From(actorValue); + var subject = entry.GetProperty("opaqueSub").GetString(); + if (!SeedData.IdentityUsers.Any(person => person.UserId == actor) + || string.IsNullOrWhiteSpace(subject) || subject.Length > 255 + || !providerIds.Add(subject) + || !subjects.TryAdd(actor, new GlobalIdentitySubject(registration.AuthorityId, registration.Issuer, subject))) + throw Refused(); + } + if (subjects.Count != SeedData.IdentityUsers.Length) throw Refused(); + return new(registration, subjects.AsReadOnly()); + } + catch (JsonException) { throw Refused(); } + catch (InvalidOperationException) { throw Refused(); } + catch (FormatException) { throw Refused(); } + catch (ArgumentException) { throw Refused(); } + } + + private static void ExactMembers(JsonElement value, params string[] names) + { + if (value.ValueKind != JsonValueKind.Object) throw Refused(); + var actual = value.EnumerateObject().Select(property => property.Name).ToArray(); + if (actual.Length != names.Length || !actual.Order(StringComparer.Ordinal).SequenceEqual(names.Order(StringComparer.Ordinal))) + throw Refused(); + } + + public override string ToString() => nameof(SeedProviderWitness); + private static InvalidOperationException Refused() => new("Development identity witness was refused."); +} diff --git a/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/AuditDbContext.cs b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/AuditDbContext.cs index 596a6e3ab..8742c9cd6 100644 --- a/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/AuditDbContext.cs +++ b/backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/AuditDbContext.cs @@ -1,3 +1,4 @@ +using LearnStack.Infrastructure.DataProtection; using LearnStack.Infrastructure.Persistence; using LearnStack.Modules.Audit.Domain; using LearnStack.SharedKernel.Tenancy; @@ -57,6 +58,12 @@ public sealed class AuditDbContext( /// Per-tenant classification overrides. public DbSet AuditConfigs => Set(); + protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) + { + base.ConfigureConventions(configurationBuilder); + configurationBuilder.UsePersonalDataClassification(); + } + protected override void OnModelCreating(ModelBuilder modelBuilder) { ArgumentNullException.ThrowIfNull(modelBuilder); 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 650a8b4c5..322ac64ba 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 @@ -1,6 +1,8 @@ +using LearnStack.Infrastructure.DataProtection; using LearnStack.Infrastructure.Persistence; using LearnStack.SharedKernel.Audit; using LearnStack.Modules.Audit.Domain; +using LearnStack.SharedKernel.DataProtection; using LearnStack.SharedKernel.Identifiers; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; @@ -136,6 +138,26 @@ public void Configure(EntityTypeBuilder builder) builder.Property(x => x.UserAgent).HasMaxLength(512); + builder.DeclarePersonalData(PersonalDataCategory.Identity, + "Actor identity and originating address retained as audit evidence.", + nameof(AuditEntry.ActorUserId), nameof(AuditEntry.ActorEmail), nameof(AuditEntry.IpAddress)); + builder.DeclarePersonalData(PersonalDataCategory.Audit, + "Audit record identity, institution scope and subject linkage.", + nameof(AuditEntry.Id), nameof(AuditEntry.TenantId), nameof(AuditEntry.OrganizationId), + nameof(AuditEntry.EntityId), nameof(AuditEntry.Timestamp)); + builder.DeclarePersonalData(PersonalDataCategory.Audit, + "Captured operation evidence may contain personal references and redacted personal payloads.", + nameof(AuditEntry.Reason), nameof(AuditEntry.BeforeState), nameof(AuditEntry.AfterState), + nameof(AuditEntry.Changes), nameof(AuditEntry.Metadata)); + builder.DeclarePersonalData(PersonalDataCategory.Audit, + "Request correlation and client evidence can link an audited act to a person.", + nameof(AuditEntry.CorrelationId), nameof(AuditEntry.UserAgent)); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Closed operation, resource-type and outcome descriptors without person values.", + nameof(AuditEntry.ModuleName), nameof(AuditEntry.Operation), nameof(AuditEntry.OperationType), + nameof(AuditEntry.OperationClass), nameof(AuditEntry.EntityType), nameof(AuditEntry.Outcome), + nameof(AuditEntry.ErrorKey)); + // The tenant's own view, newest first — the shape every read in the admin API // takes, and the one the retention purge scans. builder.HasIndex(x => new { x.TenantId, x.Timestamp }) @@ -191,6 +213,13 @@ public void Configure(EntityTypeBuilder builder) builder.MapAuditColumns(); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Institution-scoped audit configuration identity, not a person identifier.", + nameof(AuditConfig.Id), nameof(AuditConfig.TenantId)); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Operation catalogue selector and coverage toggle; no person values.", + nameof(AuditConfig.ModuleName), nameof(AuditConfig.Operation), nameof(AuditConfig.IsEnabled)); + // One LIVE override per tenant per operation. Without it a second row for the same // slug makes the cached projection's answer depend on which one it read. Partial on // `deleted_at IS NULL`, for the reason ux_tenant_domains_host is: IsEnabled has no diff --git a/backend/src/Modules/Customization/LearnStack.Modules.Customization.Infrastructure/Persistence/Configurations.cs b/backend/src/Modules/Customization/LearnStack.Modules.Customization.Infrastructure/Persistence/Configurations.cs index 37ca0eace..378fe39f8 100644 --- a/backend/src/Modules/Customization/LearnStack.Modules.Customization.Infrastructure/Persistence/Configurations.cs +++ b/backend/src/Modules/Customization/LearnStack.Modules.Customization.Infrastructure/Persistence/Configurations.cs @@ -1,5 +1,7 @@ +using LearnStack.Infrastructure.DataProtection; using LearnStack.Infrastructure.Persistence; using LearnStack.Modules.Customization.Domain; +using LearnStack.SharedKernel.DataProtection; using LearnStack.SharedKernel.Domain; using LearnStack.SharedKernel.Identifiers; using LearnStack.SharedKernel.Localization; @@ -64,6 +66,11 @@ internal static void MapDefinition( .IsRequired(); builder.Property(x => x.Status).HasEnumAsText().IsRequired(); builder.Property(x => x.DisplayName).HasLocalizedText().IsRequired(); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Institution-authored definition key, version, lifecycle and localized concept label.", + nameof(CustomizationDefinition.TenantId), nameof(CustomizationDefinition.Key), + nameof(CustomizationDefinition.SchemaVersion), nameof(CustomizationDefinition.SchemaRevision), + nameof(CustomizationDefinition.Status), nameof(CustomizationDefinition.DisplayName)); // An alternate key rather than a unique index, and the distinction is not // cosmetic: `HasPrincipalKey` on the taxonomy's item collection needs a key @@ -151,6 +158,9 @@ public void Configure(EntityTypeBuilder builder) .IsRequired(); builder.MapAuditColumns(); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Institution content-shape identity, structural validation schema and renderer selection; no instance values.", + nameof(TenantContentType.Id), nameof(TenantContentType.JsonSchema), nameof(TenantContentType.RendererKey)); } } @@ -167,6 +177,9 @@ public void Configure(EntityTypeBuilder builder) builder.MapDefinition("tenant_level_taxonomies"); builder.MapAuditColumns(); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Identity of an institution-authored vocabulary revision, not a learner's achieved level.", + nameof(TenantLevelTaxonomy.Id)); // The containment the aggregate boundary decides, expressed for EF — and // NOT as an owned type. An owned mapping reads like the natural way to say @@ -219,6 +232,12 @@ public void Configure(EntityTypeBuilder builder) builder.Property(x => x.Sort).IsRequired(); builder.Property(x => x.DisplayName).HasLocalizedText().IsRequired(); builder.Property(x => x.Metadata).HasColumnType("jsonb"); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Institution vocabulary labels, ordering and presentation metadata; no learner assignments or progress.", + nameof(TenantLevelTaxonomyItem.TenantId), nameof(TenantLevelTaxonomyItem.TaxonomyKey), + nameof(TenantLevelTaxonomyItem.SchemaVersion), nameof(TenantLevelTaxonomyItem.Key), + nameof(TenantLevelTaxonomyItem.Sort), nameof(TenantLevelTaxonomyItem.DisplayName), + nameof(TenantLevelTaxonomyItem.Metadata)); // The aggregate refuses a duplicate sort with a message a tenant admin can // read; this is what holds it across two concurrent transactions, where an @@ -245,5 +264,8 @@ public void Configure(EntityTypeBuilder builder) .ValueGeneratedNever(); builder.Property(x => x.Generation).HasDefaultValue(1L).IsRequired(); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Institution customization cache-invalidation generation, without user activity or subject linkage.", + nameof(CustomizationGeneration.TenantId), nameof(CustomizationGeneration.Generation)); } } diff --git a/backend/src/Modules/Customization/LearnStack.Modules.Customization.Infrastructure/Persistence/CustomizationDbContext.cs b/backend/src/Modules/Customization/LearnStack.Modules.Customization.Infrastructure/Persistence/CustomizationDbContext.cs index 1efd57bda..776805e41 100644 --- a/backend/src/Modules/Customization/LearnStack.Modules.Customization.Infrastructure/Persistence/CustomizationDbContext.cs +++ b/backend/src/Modules/Customization/LearnStack.Modules.Customization.Infrastructure/Persistence/CustomizationDbContext.cs @@ -1,3 +1,4 @@ +using LearnStack.Infrastructure.DataProtection; using LearnStack.Infrastructure.Persistence; using LearnStack.Modules.Customization.Domain; using LearnStack.SharedKernel.Tenancy; @@ -54,6 +55,12 @@ public sealed class CustomizationDbContext( public DbSet CustomizationGenerations => Set(); + protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) + { + base.ConfigureConventions(configurationBuilder); + configurationBuilder.UsePersonalDataClassification(); + } + protected override void OnModelCreating(ModelBuilder modelBuilder) { ArgumentNullException.ThrowIfNull(modelBuilder); diff --git a/backend/src/Modules/Education/LearnStack.Modules.Education.Infrastructure/Persistence/Configurations.cs b/backend/src/Modules/Education/LearnStack.Modules.Education.Infrastructure/Persistence/Configurations.cs index 41553d971..113685bc8 100644 --- a/backend/src/Modules/Education/LearnStack.Modules.Education.Infrastructure/Persistence/Configurations.cs +++ b/backend/src/Modules/Education/LearnStack.Modules.Education.Infrastructure/Persistence/Configurations.cs @@ -1,5 +1,7 @@ +using LearnStack.Infrastructure.DataProtection; using LearnStack.Infrastructure.Persistence; using LearnStack.Modules.Education.Domain; +using LearnStack.SharedKernel.DataProtection; using LearnStack.SharedKernel.Identifiers; using LearnStack.SharedKernel.Localization; using LearnStack.SharedKernel.Persistence; @@ -70,6 +72,15 @@ public void Configure(EntityTypeBuilder builder) builder.Property(x => x.LevelTaxonomySchemaVersion); builder.Property(x => x.LevelBandKey).HasMaxLength(EducationPinKey.MaxLength); builder.MapAuditColumns(); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Curriculum record identity and institution scope, not a person identifier.", + nameof(Course.Id), nameof(Course.TenantId), nameof(Course.OrganizationId)); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Course catalogue handle, publication state and content-access configuration.", + nameof(Course.SlugKey), nameof(Course.Status), nameof(Course.ContentAccess)); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Pinned curriculum taxonomy definition and band references.", + nameof(Course.LevelTaxonomyKey), nameof(Course.LevelTaxonomySchemaVersion), nameof(Course.LevelBandKey)); builder.HasIndex(x => new { x.TenantId, x.SlugKey }) .IsUnique().HasFilter("deleted_at IS NULL") .HasDatabaseName("ux_courses_tenant_id_slug_key"); @@ -112,6 +123,15 @@ public void Configure(EntityTypeBuilder builder) builder.Property(x => x.ContentTypeKey).HasMaxLength(EducationPinKey.MaxLength).IsRequired(); builder.Property(x => x.ContentTypeSchemaVersion).IsRequired(); builder.MapAuditColumns(); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Curriculum record identity, parent course reference and institution scope.", + nameof(Lesson.Id), nameof(Lesson.TenantId), nameof(Lesson.OrganizationId), nameof(Lesson.CourseId)); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Lesson curriculum ordering and publication state.", + nameof(Lesson.Sort), nameof(Lesson.Status)); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Pinned lesson content-type definition reference.", + nameof(Lesson.ContentTypeKey), nameof(Lesson.ContentTypeSchemaVersion)); builder.HasOne().WithMany() .HasForeignKey(x => new { x.TenantId, x.CourseId }) .HasPrincipalKey(x => new { x.TenantId, x.Id }) @@ -147,6 +167,13 @@ public void Configure(EntityTypeBuilder builder) builder.Property(x => x.Title).HasColumnType("text").IsRequired(); builder.Property(x => x.Summary).HasColumnType("text"); builder.Property(x => x.Slug).HasMaxLength(EducationSlug.MaxLength).IsRequired(); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Translated curriculum parent reference, institution scope and content locale.", + nameof(CourseTranslation.CourseId), nameof(CourseTranslation.TenantId), + nameof(CourseTranslation.OrganizationId), nameof(CourseTranslation.Locale)); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Course catalogue content and route slug, not a learner or profile record.", + nameof(CourseTranslation.Title), nameof(CourseTranslation.Summary), nameof(CourseTranslation.Slug)); builder.HasAlternateKey(x => new { x.TenantId, x.Locale, x.Slug }) .HasName("ux_course_translations_tenant_id_locale_slug"); builder.HasIndex(x => new { x.TenantId, x.CourseId }) @@ -172,6 +199,13 @@ public void Configure(EntityTypeBuilder builder) builder.Property(x => x.Title).HasColumnType("text").IsRequired(); builder.Property(x => x.Slug).HasMaxLength(EducationSlug.MaxLength).IsRequired(); builder.Property(x => x.Body).HasColumnType("jsonb").IsRequired(); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Translated curriculum parent reference, institution scope and content locale.", + nameof(LessonTranslation.LessonId), nameof(LessonTranslation.TenantId), + nameof(LessonTranslation.OrganizationId), nameof(LessonTranslation.Locale)); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Lesson curriculum content and route slug, not a learner or profile record.", + nameof(LessonTranslation.Title), nameof(LessonTranslation.Slug), nameof(LessonTranslation.Body)); builder.HasAlternateKey(x => new { x.TenantId, x.Locale, x.Slug }) .HasName("ux_lesson_translations_tenant_id_locale_slug"); builder.HasIndex(x => new { x.TenantId, x.LessonId }) diff --git a/backend/src/Modules/Education/LearnStack.Modules.Education.Infrastructure/Persistence/EducationDbContext.cs b/backend/src/Modules/Education/LearnStack.Modules.Education.Infrastructure/Persistence/EducationDbContext.cs index 7ac50a22e..d434d9794 100644 --- a/backend/src/Modules/Education/LearnStack.Modules.Education.Infrastructure/Persistence/EducationDbContext.cs +++ b/backend/src/Modules/Education/LearnStack.Modules.Education.Infrastructure/Persistence/EducationDbContext.cs @@ -1,3 +1,4 @@ +using LearnStack.Infrastructure.DataProtection; using LearnStack.Infrastructure.Persistence; using LearnStack.Modules.Education.Domain; using LearnStack.SharedKernel.Tenancy; @@ -14,6 +15,12 @@ public sealed class EducationDbContext( public DbSet Lessons => Set(); + protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) + { + base.ConfigureConventions(configurationBuilder); + configurationBuilder.UsePersonalDataClassification(); + } + protected override void OnModelCreating(ModelBuilder modelBuilder) { ArgumentNullException.ThrowIfNull(modelBuilder); diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/Bindings/IIdentityBindingReader.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/Bindings/IIdentityBindingReader.cs new file mode 100644 index 000000000..60e66795d --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/Bindings/IIdentityBindingReader.cs @@ -0,0 +1,11 @@ +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; + +namespace LearnStack.Modules.Identity.Application.Contracts.Bindings; + +/// Existing-binding normalization only; the caller independently verifies the provider credential. +public interface IIdentityBindingReader +{ + Task ResolveExistingAsync(GlobalIdentitySubject subject, UserId? claimedActor = null, + CancellationToken cancellationToken = default); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/Bindings/IdentityBindingResult.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/Bindings/IdentityBindingResult.cs new file mode 100644 index 000000000..4e0cf5890 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/Bindings/IdentityBindingResult.cs @@ -0,0 +1,46 @@ +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.Modules.Identity.Application.Contracts.Bindings; + +public enum IdentityBindingOutcome +{ + Existing = 1, + Created = 2, + NotFound = 3, + NonAdmitting = 4, + Conflict = 5, + AdmissionDenied = 6, + AuthorityUnavailable = 7, + StorageUnavailable = 8, + Indeterminate = 9, +} + +/// Closed internal outcome; a refused or uncertain attempt authenticates no actor. +public sealed class IdentityBindingResult +{ + private IdentityBindingResult(IdentityBindingOutcome outcome, UserId? actor) + { + Outcome = outcome; + Actor = actor; + } + + public IdentityBindingOutcome Outcome { get; } + public UserId? Actor { get; } + public bool IsBound => Outcome is IdentityBindingOutcome.Existing or IdentityBindingOutcome.Created; + + public static IdentityBindingResult Bound(UserId actor, bool created) + { + if (!actor.IsInitialized() || actor.Value == Guid.Empty || actor.Value.Version != 7 || actor == UserId.SystemActor) + throw new ArgumentException("A binding requires an admitted actor.", nameof(actor)); + return new(created ? IdentityBindingOutcome.Created : IdentityBindingOutcome.Existing, actor); + } + + public static IdentityBindingResult Refused(IdentityBindingOutcome outcome) + { + if (!Enum.IsDefined(outcome) || outcome is IdentityBindingOutcome.Existing or IdentityBindingOutcome.Created) + throw new ArgumentException("A refusal requires a closed non-success outcome.", nameof(outcome)); + return new(outcome, null); + } + + public override string ToString() => nameof(IdentityBindingResult); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/Seeding/ISeedIdentityBindingAdopter.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/Seeding/ISeedIdentityBindingAdopter.cs new file mode 100644 index 000000000..5f513f80a --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/Seeding/ISeedIdentityBindingAdopter.cs @@ -0,0 +1,28 @@ +using LearnStack.Modules.Identity.Application.Contracts.Bindings; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; + +namespace LearnStack.Modules.Identity.Application.Contracts.Seeding; + +/// Fixed development adoption, independently gated; possession of subject facts grants no authority. +public interface ISeedIdentityBindingAdopter +{ + Task AdoptAsync(GlobalIdentitySubject subject, UserId declaredActor, + CancellationToken cancellationToken = default); +} + +/// The confined external seed owner supplies verified provider facts and exact declared actors. +public interface ISeedIdentityFoundationAdmission +{ + ValueTask AllowsFoundationAsync(SeedIdentityFoundationAct act, + CancellationToken cancellationToken = default) => ValueTask.FromResult(false); + + ValueTask AllowsAsync(GlobalIdentitySubject subject, UserId declaredActor, + CancellationToken cancellationToken = default); +} + +public sealed class DenyAllSeedIdentityFoundationAdmission : ISeedIdentityFoundationAdmission +{ + public ValueTask AllowsAsync(GlobalIdentitySubject subject, UserId declaredActor, + CancellationToken cancellationToken = default) => ValueTask.FromResult(false); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/Seeding/SeedIdentityFoundationAct.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/Seeding/SeedIdentityFoundationAct.cs new file mode 100644 index 000000000..f66811e46 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/Seeding/SeedIdentityFoundationAct.cs @@ -0,0 +1,16 @@ +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; + +namespace LearnStack.Modules.Identity.Application.Contracts.Seeding; + +public enum SeedIdentityFoundationOperation +{ + InitializeRole = 1, CreateFirstAdmin = 2, CreateMembership = 3, SetProfile = 4, + VerifyRole = 5, VerifyMembership = 6, +} + +/// Bounded declaration. A separate confined owner must also possess actual provider-adoption witnesses. +public sealed record SeedIdentityFoundationAct(SeedIdentityFoundationOperation Operation, + TenantId TenantId, OrganizationId? OrganizationId, UserId ActorUserId, Guid RootId, + UserId? TargetUserId, Guid? RoleId, BuiltInRoleKey? BuiltInKey, PermissionScope Scope, + int ManifestVersion, string ExpectedFingerprint); diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/Seeding/SeedIdentityFoundationCommands.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/Seeding/SeedIdentityFoundationCommands.cs new file mode 100644 index 000000000..5a05fa500 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/Seeding/SeedIdentityFoundationCommands.cs @@ -0,0 +1,34 @@ +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Results; +using MediatR; + +namespace LearnStack.Modules.Identity.Application.Contracts.Seeding; + +public sealed record InitializeSeedRoleCommand(Guid RoleId, BuiltInRoleKey BuiltInKey, + PermissionScope CapabilityScope, int ManifestVersion, string ExpectedFingerprint) + : IRequest>, IIdentityPermissionRequest +{ + public PermissionDefinition RequiredPermission => new(PermissionScope.Tenant, "identity.role.admin"); +} + +public sealed record CreateFirstSeedAdminMembershipCommand(Guid MembershipId, UserId UserId, Guid RoleId, + int ManifestVersion, string ExpectedFingerprint) : IRequest>, IIdentityPermissionRequest +{ + public PermissionDefinition RequiredPermission => new(PermissionScope.Tenant, "identity.membership.admin"); +} + +public sealed record CreateSeedMembershipCommand(Guid MembershipId, UserId UserId, Guid RoleId, + PermissionScope MembershipScope, int ManifestVersion, string ExpectedFingerprint) + : IRequest>, IIdentityPermissionRequest +{ + public PermissionDefinition RequiredPermission => new(MembershipScope, "identity.membership.admin"); +} + +public sealed record SetSeedMembershipProfileCommand(Guid MembershipId, UserId ExpectedUserId, Guid ExpectedRoleId, PermissionScope MembershipScope, + [property: PiiSensitive] string? DisplayName, [property: PiiSensitive] string? PreferredLocale, + int ManifestVersion, string ExpectedFingerprint) : IRequest>, IIdentityPermissionRequest +{ + public PermissionDefinition RequiredPermission => new(MembershipScope, "identity.membership_profile.write"); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/Seeding/SeedIdentityStateQueries.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/Seeding/SeedIdentityStateQueries.cs new file mode 100644 index 000000000..e006a1f68 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application.Contracts/Seeding/SeedIdentityStateQueries.cs @@ -0,0 +1,27 @@ +using System.Collections.Immutable; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Results; +using MediatR; + +namespace LearnStack.Modules.Identity.Application.Contracts.Seeding; + +public sealed record SeedLookup(T? State) where T : class; + +public sealed record RoleSeedDto(Guid Id, TenantId TenantId, BuiltInRoleKey BuiltInKey, + PermissionScope PermissionScope, long Version, DateTimeOffset? DeletedAt, UserId? DeletedBy, + ImmutableArray Grants); + +public sealed record MembershipSeedDto(Guid Id, TenantId TenantId, OrganizationId? OrganizationId, + UserId UserId, string Status, long Version, DateTimeOffset? DeletedAt, UserId? DeletedBy, + [property: PiiSensitive] string? DisplayName, [property: PiiSensitive] string? PreferredLocale, + ImmutableArray RoleIds); + +public sealed record GetRoleSeedStateQuery(Guid RoleId, BuiltInRoleKey BuiltInKey, + PermissionScope CapabilityScope, int ManifestVersion, string ExpectedFingerprint) + : IRequest>>; + +public sealed record GetMembershipSeedStateQuery(Guid MembershipId, UserId UserId, Guid RoleId, + PermissionScope MembershipScope, int ManifestVersion, string ExpectedFingerprint) + : IRequest>>; diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/ContextualIdentityStores.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/ContextualIdentityStores.cs new file mode 100644 index 000000000..79adada30 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/ContextualIdentityStores.cs @@ -0,0 +1,40 @@ +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Persistence; + +namespace LearnStack.Modules.Identity.Application.Abstractions; + +public interface IRoleWriteStore : IAggregateWriteStore +{ + /// Fresh tracked complete graph, including tombstones; repeated post-wait reads must not reuse stale tracked values. + Task FindAsync(RoleId roleId, CancellationToken cancellationToken = default); + Task HasMembershipHistoryAsync(CancellationToken cancellationToken = default); + Task ValidateGraphAsync(CancellationToken cancellationToken = default); +} + +public interface IRoleReadStore +{ + Task ReadAsync(RoleId roleId, CancellationToken cancellationToken = default); +} + +public interface IMembershipWriteStore : IAggregateWriteStore +{ + Task FindAsync(MembershipId membershipId, CancellationToken cancellationToken = default); + Task HasMembershipHistoryAsync(CancellationToken cancellationToken = default); + Task ValidateGraphAsync(CancellationToken cancellationToken = default); +} + +public interface ISeedStateReader +{ + Task ReadRoleAsync(RoleId roleId, CancellationToken cancellationToken = default); + Task ReadMembershipAsync(MembershipId membershipId, CancellationToken cancellationToken = default); +} + +public enum IdentityFoundationStorageFailure { Plan = 1, Target = 2, Invariant = 3, Graph = 4, Conflict = 5 } + +/// Adapter-owned fixed diagnostic; never retains database text or inner exceptions. +public sealed class IdentityFoundationStorageException(IdentityFoundationStorageFailure failure) + : Exception("Identity foundation storage refused the operation.") +{ + public IdentityFoundationStorageFailure Failure { get; } = failure; +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/IUserBindingStore.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/IUserBindingStore.cs new file mode 100644 index 000000000..3242883ea --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/IUserBindingStore.cs @@ -0,0 +1,16 @@ +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Persistence; + +namespace LearnStack.Modules.Identity.Application.Abstractions; + +/// Exact self-binding access on the already prepared global owner, never a directory. +public interface IUserBindingStore : IAggregateWriteStore +{ + Task FindExactAsync(GlobalIdentitySubject subject, CancellationToken cancellationToken = default); + + // The root remains countable; no User update owner or lifecycle grant is admitted. + Task IAggregateWriteStore.UpdateAsync(User aggregate, CancellationToken cancellationToken) => + throw new InvalidOperationException("Global identity binding updates are not admitted."); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/UserBindingStorageException.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/UserBindingStorageException.cs new file mode 100644 index 000000000..04f81cfb5 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Abstractions/UserBindingStorageException.cs @@ -0,0 +1,9 @@ +using LearnStack.SharedKernel.Errors; + +namespace LearnStack.Modules.Identity.Application.Abstractions; + +/// A fixed adapter failure; it retains no provider values or original inner payload. +public sealed class UserBindingStorageException : InfrastructureException +{ + public UserBindingStorageException() : base("Identity binding storage is unavailable.") { } +} 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 new file mode 100644 index 000000000..e870e0563 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Audit/IdentityAuditCatalogSource.cs @@ -0,0 +1,22 @@ +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.SharedKernel.Audit; + +namespace LearnStack.Modules.Identity.Application.Audit; + +public sealed class IdentityAuditCatalogSource : IAuditCatalogSource +{ + public string ModuleName => "identity"; + + public void Describe(IAuditCatalogBuilder builder) + { + ArgumentNullException.ThrowIfNull(builder); + builder.MustAudit("identity.role.initialize", OperationType.SecurityEvent, typeof(Role)); + builder.MustAudit("identity.membership.create_first_seed_admin", OperationType.SecurityEvent, typeof(Membership)); + builder.MustAudit("identity.membership.create_seed", OperationType.SecurityEvent, typeof(Membership)); + builder.MustAudit("identity.membership_profile.set_seed_profile", OperationType.Update, typeof(Membership)); + builder.Off(); + builder.Off(); + builder.DeclareOffPath("identity.user.create", OperationType.SecurityEvent, OperationClass.Must, typeof(User)); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Bindings/CreateUserBindingHandler.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Bindings/CreateUserBindingHandler.cs new file mode 100644 index 000000000..26f9d05e5 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Bindings/CreateUserBindingHandler.cs @@ -0,0 +1,23 @@ +using LearnStack.Modules.Identity.Application.Abstractions; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Time; + +namespace LearnStack.Modules.Identity.Application.Bindings; + +/// Deferred tracked User creation; the common owner supplies identity and creation-audit attribution. +public sealed class CreateUserBindingHandler(IUserBindingStore store, IClock clock) +{ + public async Task> HandleAsync(GlobalIdentitySubject subject, + GlobalIdentityCreationReference creation, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(subject); + ArgumentNullException.ThrowIfNull(creation); + var user = User.Create(subject, creation, clock.UtcNow, UserId.SystemActor); + await store.AddAsync(user, cancellationToken); + return Result.Ok(user.Id); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/LearnStack.Modules.Identity.Application.csproj b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/LearnStack.Modules.Identity.Application.csproj index f263e6b43..7626e1a51 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/LearnStack.Modules.Identity.Application.csproj +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/LearnStack.Modules.Identity.Application.csproj @@ -7,6 +7,7 @@ + diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/CreateSeedMembershipCommandHandlers.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/CreateSeedMembershipCommandHandlers.cs new file mode 100644 index 000000000..d5dae8933 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/CreateSeedMembershipCommandHandlers.cs @@ -0,0 +1,97 @@ +using LearnStack.Modules.Identity.Application.Abstractions; +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Tenancy.Application.Contracts.IdentityLifecycle; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using MediatR; + +namespace LearnStack.Modules.Identity.Application.Seeding; + +public sealed class CreateFirstSeedAdminMembershipCommandHandler(IMembershipWriteStore store, IRoleReadStore roles, + ITenantContext context, ISeedIdentityFoundationAdmission admission, IIdentityScopeLifecycleReader lifecycle, + IIdentityMutationLocks locks, IClock clock) + : IRequestHandler> +{ + public Task> Handle(CreateFirstSeedAdminMembershipCommand request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + return SeedMembershipCreation.CreateAsync(request.MembershipId, request.UserId, request.RoleId, + PermissionScope.Tenant, request.ManifestVersion, request.ExpectedFingerprint, true, + store, roles, context, admission, lifecycle, locks, clock, cancellationToken); + } +} + +public sealed class CreateSeedMembershipCommandHandler(IMembershipWriteStore store, IRoleReadStore roles, + ITenantContext context, ISeedIdentityFoundationAdmission admission, IIdentityScopeLifecycleReader lifecycle, + IIdentityMutationLocks locks, IClock clock) : IRequestHandler> +{ + public Task> Handle(CreateSeedMembershipCommand request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + return SeedMembershipCreation.CreateAsync(request.MembershipId, request.UserId, request.RoleId, + request.MembershipScope, request.ManifestVersion, request.ExpectedFingerprint, false, + store, roles, context, admission, lifecycle, locks, clock, cancellationToken); + } +} + +internal static class SeedMembershipCreation +{ + internal static async Task> CreateAsync(Guid membershipId, UserId userId, Guid roleId, + PermissionScope scope, int manifestVersion, string fingerprint, bool firstAdmin, + IMembershipWriteStore store, IRoleReadStore roles, ITenantContext context, + ISeedIdentityFoundationAdmission admission, IIdentityScopeLifecycleReader lifecycle, + IIdentityMutationLocks locks, IClock clock, CancellationToken cancellationToken) + { + if (!SeedFoundationGate.HasActor(context) || scope != SeedFoundationGate.Scope(context) + || !SeedFoundationGate.ValidRoot(membershipId) || !SeedFoundationGate.ValidRoot(roleId) + || !SeedFoundationGate.ValidUser(userId) || firstAdmin && context.OrganizationId is not null) + return Result.Fail(IdentityFailures.Refused()); + var operation = firstAdmin ? SeedIdentityFoundationOperation.CreateFirstAdmin : SeedIdentityFoundationOperation.CreateMembership; + var act = SeedFoundationGate.Act(context, operation, membershipId, userId, roleId, null, + scope, manifestVersion, fingerprint); + if (!await SeedFoundationGate.AllowsAsync(context, admission, lifecycle, act, + IdentityFoundationManifest.Version1.MembershipFingerprint(context.TenantId, context.OrganizationId, + membershipId, userId, roleId), cancellationToken)) + return Result.Fail(IdentityFailures.Refused()); + try + { + var id = MembershipId.From(membershipId); + var referencedRoleId = RoleId.From(roleId); + var role = await roles.ReadAsync(referencedRoleId, cancellationToken); + if (!IsDeclaredRole(role, context.TenantId, scope, firstAdmin) + || await store.FindAsync(id, cancellationToken) is not null + || firstAdmin && await store.HasMembershipHistoryAsync(cancellationToken)) + return Result.Fail(IdentityFailures.Refused()); + // Classification comes from the actual referenced complete Role, never the command's scope label. + var mode = role!.IsTenantAdministrator ? IdentityTenantLockMode.Exclusive : IdentityTenantLockMode.Shared; + var plan = new IdentityMutationLockPlan([userId], context.TenantId, mode); + await locks.AcquireAsync(plan, cancellationToken); + var freshRole = await roles.ReadAsync(referencedRoleId, cancellationToken); + if (!IsDeclaredRole(freshRole, context.TenantId, scope, firstAdmin) + || freshRole!.IsTenantAdministrator != role.IsTenantAdministrator + || await store.FindAsync(id, cancellationToken) is not null + || firstAdmin && await store.HasMembershipHistoryAsync(cancellationToken)) + return Result.Fail(IdentityFailures.Refused()); + locks.RequireCurrent(plan); + var membership = Membership.Create(id, context.TenantId, context.OrganizationId, userId, + freshRole, clock.UtcNow, context.UserId!.Value); + if (membership.IsFailure) return Result.Fail(membership.Error); + await store.AddAsync(membership.Value, cancellationToken); + await store.ValidateGraphAsync(cancellationToken); + return Result.Ok(membershipId); + } + catch (Exception failure) when (failure is IdentityFoundationStorageException or IdentityMutationLockException) + { + return Result.Fail(IdentityFailures.Refused()); + } + } + + private static bool IsDeclaredRole(Role? role, TenantId tenant, PermissionScope scope, bool firstAdmin) => + role is { Version: 0 } && role.TenantId == tenant && role.PermissionScope == scope && role.MatchesInitialTemplate() + && (firstAdmin ? role.IsTenantAdministrator : role.BuiltInKey == BuiltInRoleKey.Learner); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/InitializeSeedRoleCommandHandler.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/InitializeSeedRoleCommandHandler.cs new file mode 100644 index 000000000..79db9bd37 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/InitializeSeedRoleCommandHandler.cs @@ -0,0 +1,55 @@ +using LearnStack.Modules.Identity.Application.Abstractions; +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Tenancy.Application.Contracts.IdentityLifecycle; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using MediatR; + +namespace LearnStack.Modules.Identity.Application.Seeding; + +public sealed class InitializeSeedRoleCommandHandler(IRoleWriteStore store, ITenantContext context, + ISeedIdentityFoundationAdmission admission, IIdentityScopeLifecycleReader lifecycle, + IIdentityMutationLocks locks, IClock clock) : IRequestHandler> +{ + public async Task> Handle(InitializeSeedRoleCommand request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + if (!SeedFoundationGate.HasActor(context) || context.OrganizationId is not null + || !SeedFoundationGate.ValidRoot(request.RoleId) + || IdentityFoundationManifest.Version1.FindTemplate(request.BuiltInKey, request.CapabilityScope) is null) + return Result.Fail(IdentityFailures.Refused()); + var act = SeedFoundationGate.Act(context, SeedIdentityFoundationOperation.InitializeRole, request.RoleId, + null, null, request.BuiltInKey, request.CapabilityScope, request.ManifestVersion, request.ExpectedFingerprint); + if (!await SeedFoundationGate.AllowsAsync(context, admission, lifecycle, act, + IdentityFoundationManifest.Version1.RoleFingerprint(context.TenantId, request.RoleId, + request.BuiltInKey, request.CapabilityScope), cancellationToken)) + return Result.Fail(IdentityFailures.Refused()); + try + { + var id = RoleId.From(request.RoleId); + if (await store.FindAsync(id, cancellationToken) is not null + || await store.HasMembershipHistoryAsync(cancellationToken)) + return Result.Fail(IdentityFailures.Refused()); + var plan = new IdentityMutationLockPlan([], context.TenantId, IdentityTenantLockMode.Shared); + await locks.AcquireAsync(plan, cancellationToken); + if (await store.FindAsync(id, cancellationToken) is not null + || await store.HasMembershipHistoryAsync(cancellationToken)) + return Result.Fail(IdentityFailures.Refused()); + locks.RequireCurrent(plan); + var role = Role.Create(id, context.TenantId, request.BuiltInKey, request.CapabilityScope, + clock.UtcNow, context.UserId!.Value); + if (role.IsFailure) return Result.Fail(role.Error); + await store.AddAsync(role.Value, cancellationToken); + await store.ValidateGraphAsync(cancellationToken); + return Result.Ok(request.RoleId); + } + catch (Exception failure) when (failure is IdentityFoundationStorageException or IdentityMutationLockException) + { + return Result.Fail(IdentityFailures.Refused()); + } + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/SeedFoundationGate.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/SeedFoundationGate.cs new file mode 100644 index 000000000..6997d1f23 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/SeedFoundationGate.cs @@ -0,0 +1,38 @@ +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Tenancy.Application.Contracts.IdentityLifecycle; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Tenancy; + +namespace LearnStack.Modules.Identity.Application.Seeding; + +internal static class SeedFoundationGate +{ + internal static bool ValidRoot(Guid value) => value != Guid.Empty && value.Version == 7; + internal static bool ValidUser(UserId value) => value.IsInitialized() && value.Value != Guid.Empty + && value.Value.Version == 7 && value != UserId.SystemActor; + internal static PermissionScope Scope(ITenantContext context) => + context.OrganizationId is null ? PermissionScope.Tenant : PermissionScope.Organization; + + internal static bool HasActor(ITenantContext context) => context.IsResolved && context.UserId is { } actor + && actor.IsInitialized() && actor.Value != Guid.Empty; + + internal static async Task AllowsAsync(ITenantContext context, ISeedIdentityFoundationAdmission admission, + IIdentityScopeLifecycleReader lifecycle, SeedIdentityFoundationAct act, string expectedFingerprint, + CancellationToken cancellationToken) + { + if (act.ManifestVersion != IdentityFoundationManifest.Version1.Version + || !string.Equals(act.ExpectedFingerprint, expectedFingerprint, StringComparison.Ordinal) + || !await admission.AllowsFoundationAsync(act, cancellationToken)) return false; + // Closed seed admission precedes any lifecycle SQL or lock acquisition. + var facts = await lifecycle.ReadAsync(context.TenantId, context.OrganizationId, cancellationToken); + return facts.TenantExistsAndNotDeleted && facts.TenantAllowsOrdinaryWork + && (context.OrganizationId is null || facts.OrganizationBelongsToTenant && facts.OrganizationAllowsOrdinaryWork); + } + + internal static SeedIdentityFoundationAct Act(ITenantContext context, SeedIdentityFoundationOperation operation, + Guid rootId, UserId? targetUserId, Guid? roleId, BuiltInRoleKey? builtInKey, PermissionScope scope, + int version, string fingerprint) => new(operation, context.TenantId, context.OrganizationId, + context.UserId!.Value, rootId, targetUserId, roleId, builtInKey, scope, version, fingerprint); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/SeedFoundationValidators.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/SeedFoundationValidators.cs new file mode 100644 index 000000000..332d4833e --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/SeedFoundationValidators.cs @@ -0,0 +1,89 @@ +using FluentValidation; +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Permissions; + +namespace LearnStack.Modules.Identity.Application.Seeding; + +public sealed class InitializeSeedRoleCommandValidator : AbstractValidator +{ + public InitializeSeedRoleCommandValidator() + { + RuleFor(request => request.RoleId).Must(SeedFoundationGate.ValidRoot); + RuleFor(request => request).Must(request => IdentityFoundationManifest.Version1.FindTemplate( + request.BuiltInKey, request.CapabilityScope) is not null); + RuleFor(request => request.ManifestVersion).Equal(1); + RuleFor(request => request.ExpectedFingerprint).Must(SeedFoundationValidation.IsFingerprint); + } +} + +public sealed class CreateFirstSeedAdminMembershipCommandValidator : AbstractValidator +{ + public CreateFirstSeedAdminMembershipCommandValidator() + { + RuleFor(request => request.MembershipId).Must(SeedFoundationGate.ValidRoot); + RuleFor(request => request.UserId).Must(SeedFoundationGate.ValidUser); + RuleFor(request => request.RoleId).Must(SeedFoundationGate.ValidRoot); + RuleFor(request => request.ManifestVersion).Equal(1); + RuleFor(request => request.ExpectedFingerprint).Must(SeedFoundationValidation.IsFingerprint); + } +} + +public sealed class CreateSeedMembershipCommandValidator : AbstractValidator +{ + public CreateSeedMembershipCommandValidator() + { + RuleFor(request => request.MembershipId).Must(SeedFoundationGate.ValidRoot); + RuleFor(request => request.UserId).Must(SeedFoundationGate.ValidUser); + RuleFor(request => request.RoleId).Must(SeedFoundationGate.ValidRoot); + RuleFor(request => request.MembershipScope).Must(SeedFoundationValidation.IsContextualScope); + RuleFor(request => request.ManifestVersion).Equal(1); + RuleFor(request => request.ExpectedFingerprint).Must(SeedFoundationValidation.IsFingerprint); + } +} + +public sealed class SetSeedMembershipProfileCommandValidator : AbstractValidator +{ + public SetSeedMembershipProfileCommandValidator() + { + RuleFor(request => request.ExpectedUserId).Must(SeedFoundationGate.ValidUser); + RuleFor(request => request.ExpectedRoleId).Must(SeedFoundationGate.ValidRoot); + RuleFor(request => request.MembershipId).Must(SeedFoundationGate.ValidRoot); + RuleFor(request => request.MembershipScope).Must(SeedFoundationValidation.IsContextualScope); + RuleFor(request => request).Must(request => MembershipProfile.IsValid(request.DisplayName, request.PreferredLocale)); + RuleFor(request => request.ManifestVersion).Equal(1); + RuleFor(request => request.ExpectedFingerprint).Must(SeedFoundationValidation.IsFingerprint); + } +} + +public sealed class GetRoleSeedStateQueryValidator : AbstractValidator +{ + public GetRoleSeedStateQueryValidator() + { + RuleFor(request => request.RoleId).Must(SeedFoundationGate.ValidRoot); + RuleFor(request => request).Must(request => IdentityFoundationManifest.Version1.FindTemplate( + request.BuiltInKey, request.CapabilityScope) is not null); + RuleFor(request => request.ManifestVersion).Equal(1); + RuleFor(request => request.ExpectedFingerprint).Must(SeedFoundationValidation.IsFingerprint); + } +} + +public sealed class GetMembershipSeedStateQueryValidator : AbstractValidator +{ + public GetMembershipSeedStateQueryValidator() + { + RuleFor(request => request.MembershipId).Must(SeedFoundationGate.ValidRoot); + RuleFor(request => request.UserId).Must(SeedFoundationGate.ValidUser); + RuleFor(request => request.RoleId).Must(SeedFoundationGate.ValidRoot); + RuleFor(request => request.MembershipScope).Must(SeedFoundationValidation.IsContextualScope); + RuleFor(request => request.ManifestVersion).Equal(1); + RuleFor(request => request.ExpectedFingerprint).Must(SeedFoundationValidation.IsFingerprint); + } +} + +internal static class SeedFoundationValidation +{ + internal static bool IsContextualScope(PermissionScope scope) => scope is PermissionScope.Tenant or PermissionScope.Organization; + internal static bool IsFingerprint(string? value) => value is { Length: 64 } + && value.All(character => character is >= '0' and <= '9' or >= 'a' and <= 'f'); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/SeedIdentityStateQueryHandlers.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/SeedIdentityStateQueryHandlers.cs new file mode 100644 index 000000000..938f921d6 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/SeedIdentityStateQueryHandlers.cs @@ -0,0 +1,54 @@ +using LearnStack.Modules.Identity.Application.Abstractions; +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Tenancy.Application.Contracts.IdentityLifecycle; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using MediatR; + +namespace LearnStack.Modules.Identity.Application.Seeding; + +public sealed class GetRoleSeedStateQueryHandler(ISeedStateReader reader, ITenantContext context, + ISeedIdentityFoundationAdmission admission, IIdentityScopeLifecycleReader lifecycle) + : IRequestHandler>> +{ + public async Task>> Handle(GetRoleSeedStateQuery request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + if (!SeedFoundationGate.HasActor(context) || context.OrganizationId is not null + || !SeedFoundationGate.ValidRoot(request.RoleId) + || IdentityFoundationManifest.Version1.FindTemplate(request.BuiltInKey, request.CapabilityScope) is null) + return Result>.Fail(IdentityFailures.Refused()); + var act = SeedFoundationGate.Act(context, SeedIdentityFoundationOperation.VerifyRole, request.RoleId, + null, null, request.BuiltInKey, request.CapabilityScope, request.ManifestVersion, request.ExpectedFingerprint); + if (!await SeedFoundationGate.AllowsAsync(context, admission, lifecycle, act, + IdentityFoundationManifest.Version1.RoleFingerprint(context.TenantId, request.RoleId, + request.BuiltInKey, request.CapabilityScope), cancellationToken)) + return Result>.Fail(IdentityFailures.Refused()); + return Result>.Ok(new(await reader.ReadRoleAsync(RoleId.From(request.RoleId), cancellationToken))); + } +} + +public sealed class GetMembershipSeedStateQueryHandler(ISeedStateReader reader, ITenantContext context, + ISeedIdentityFoundationAdmission admission, IIdentityScopeLifecycleReader lifecycle) + : IRequestHandler>> +{ + public async Task>> Handle(GetMembershipSeedStateQuery request, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + if (!SeedFoundationGate.HasActor(context) || request.MembershipScope != SeedFoundationGate.Scope(context) + || !SeedFoundationGate.ValidRoot(request.MembershipId) || !SeedFoundationGate.ValidRoot(request.RoleId) + || !SeedFoundationGate.ValidUser(request.UserId)) + return Result>.Fail(IdentityFailures.Refused()); + var act = SeedFoundationGate.Act(context, SeedIdentityFoundationOperation.VerifyMembership, request.MembershipId, + request.UserId, request.RoleId, null, request.MembershipScope, request.ManifestVersion, request.ExpectedFingerprint); + if (!await SeedFoundationGate.AllowsAsync(context, admission, lifecycle, act, + IdentityFoundationManifest.Version1.MembershipFingerprint(context.TenantId, context.OrganizationId, + request.MembershipId, request.UserId, request.RoleId), cancellationToken)) + return Result>.Fail(IdentityFailures.Refused()); + return Result>.Ok(new(await reader.ReadMembershipAsync( + MembershipId.From(request.MembershipId), cancellationToken))); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/SetSeedMembershipProfileCommandHandler.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/SetSeedMembershipProfileCommandHandler.cs new file mode 100644 index 000000000..6b70699cf --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Application/Seeding/SetSeedMembershipProfileCommandHandler.cs @@ -0,0 +1,69 @@ +using LearnStack.Modules.Identity.Application.Abstractions; +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Tenancy.Application.Contracts.IdentityLifecycle; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using MediatR; + +namespace LearnStack.Modules.Identity.Application.Seeding; + +public sealed class SetSeedMembershipProfileCommandHandler(IMembershipWriteStore store, ITenantContext context, + ISeedIdentityFoundationAdmission admission, IIdentityScopeLifecycleReader lifecycle, + IIdentityMutationLocks locks, IClock clock) : IRequestHandler> +{ + public async Task> Handle(SetSeedMembershipProfileCommand request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + if (!SeedFoundationGate.HasActor(context) || request.MembershipScope != SeedFoundationGate.Scope(context) + || !SeedFoundationGate.ValidRoot(request.MembershipId) + || !SeedFoundationGate.ValidUser(request.ExpectedUserId) || !SeedFoundationGate.ValidRoot(request.ExpectedRoleId) + || !MembershipProfile.IsValid(request.DisplayName, request.PreferredLocale)) + return Result.Fail(IdentityFailures.Refused()); + var act = SeedFoundationGate.Act(context, SeedIdentityFoundationOperation.SetProfile, request.MembershipId, + request.ExpectedUserId, request.ExpectedRoleId, null, request.MembershipScope, request.ManifestVersion, request.ExpectedFingerprint); + if (!await SeedFoundationGate.AllowsAsync(context, admission, lifecycle, act, + IdentityFoundationManifest.Version1.ProfileFingerprint(context.TenantId, context.OrganizationId, + request.MembershipId, request.DisplayName, request.PreferredLocale), cancellationToken)) + return Result.Fail(IdentityFailures.Refused()); + try + { + var id = MembershipId.From(request.MembershipId); + var before = await store.FindAsync(id, cancellationToken); + if (!CanSet(before, request)) return Result.Fail(IdentityFailures.Refused()); + var originalVersion = before!.Version; + var originalUser = before.UserId; + var plan = new IdentityMutationLockPlan([], context.TenantId, IdentityTenantLockMode.Shared); + await locks.AcquireAsync(plan, cancellationToken); + var membership = await store.FindAsync(id, cancellationToken); + if (!CanSet(membership, request) || membership!.Version != originalVersion || membership.UserId != originalUser) + return Result.Fail(IdentityFailures.Refused()); + locks.RequireCurrent(plan); + var changed = membership.SetProfile(request.DisplayName, request.PreferredLocale, + clock.UtcNow, context.UserId!.Value); + if (changed.IsFailure) return changed; + if (membership.Version != originalVersion) + { + await store.UpdateAsync(membership, cancellationToken); + await store.ValidateGraphAsync(cancellationToken); + } + return Result.Ok(None.Value); + } + catch (Exception failure) when (failure is IdentityFoundationStorageException or IdentityMutationLockException) + { + return Result.Fail(IdentityFailures.Refused()); + } + } + + private bool CanSet(Membership? membership, SetSeedMembershipProfileCommand request) => + membership is { Status: MembershipStatus.Active, DeletedAt: null, DeletedBy: null } + && membership.UserId == request.ExpectedUserId + && membership.RoleAssignments.Count == 1 && membership.RoleAssignments.Single().RoleId.Value == request.ExpectedRoleId + && membership.TenantId == context.TenantId && membership.OrganizationId == context.OrganizationId + && (membership.Version == 0 && membership.Profile.DisplayName is null && membership.Profile.PreferredLocale is null + || membership.Version == 1 && membership.Profile.DisplayName == request.DisplayName + && membership.Profile.PreferredLocale == request.PreferredLocale); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/Identifiers.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/Identifiers.cs new file mode 100644 index 000000000..f6ee5337a --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/Identifiers.cs @@ -0,0 +1,11 @@ +using LearnStack.SharedKernel; +using LearnStack.SharedKernel.Identifiers; +using Vogen; + +namespace LearnStack.Modules.Identity.Domain; + +[ValueObject(LearnStackVogenDefaults.IdMask)] +public readonly partial record struct MembershipId : IStronglyTypedId; + +[ValueObject(LearnStackVogenDefaults.IdMask)] +public readonly partial record struct RoleId : IStronglyTypedId; diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/IdentityAuthority.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/IdentityAuthority.cs new file mode 100644 index 000000000..ddb98abef --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/IdentityAuthority.cs @@ -0,0 +1,13 @@ +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.Modules.Identity.Domain; + +/// Deployment-owned singleton. Runtime has no writer or rebind operation. +public sealed class IdentityAuthority +{ + private IdentityAuthority() { Issuer = null!; } + + public int Id { get; private set; } + public IdentityAuthorityId AuthorityId { get; private set; } + public string Issuer { get; private set; } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/IdentityFailures.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/IdentityFailures.cs new file mode 100644 index 000000000..36680822e --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/IdentityFailures.cs @@ -0,0 +1,11 @@ +using LearnStack.SharedKernel.Localization; +using LearnStack.SharedKernel.Results; + +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"))); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/IdentityFoundationManifest.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/IdentityFoundationManifest.cs new file mode 100644 index 000000000..bbcf17c85 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/IdentityFoundationManifest.cs @@ -0,0 +1,103 @@ +using System.Buffers.Binary; +using System.Collections.Immutable; +using System.Globalization; +using System.Security.Cryptography; +using System.Text; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; + +namespace LearnStack.Modules.Identity.Domain; + +public sealed record BuiltInRoleTemplate(BuiltInRoleKey BuiltInKey, PermissionScope Scope, + ImmutableArray Grants); + +/// The retained, finite v1 registry, template grants and administrator minimum. +public sealed class IdentityFoundationManifest +{ + public const string MembershipAdmin = "identity.membership.admin"; + public const string RoleAdmin = "identity.role.admin"; + public const string ProfileWrite = "identity.membership_profile.write"; + + public static IdentityFoundationManifest Version1 { get; } = new(); + + private IdentityFoundationManifest() + { + var memberTenant = new PermissionDefinition(PermissionScope.Tenant, MembershipAdmin); + var memberOrganization = new PermissionDefinition(PermissionScope.Organization, MembershipAdmin); + var roleTenant = new PermissionDefinition(PermissionScope.Tenant, RoleAdmin); + var profileTenant = new PermissionDefinition(PermissionScope.Tenant, ProfileWrite); + var profileOrganization = new PermissionDefinition(PermissionScope.Organization, ProfileWrite); + Definitions = [memberTenant, memberOrganization, roleTenant, profileTenant, profileOrganization]; + Templates = + [ + new(BuiltInRoleKey.TenantAdmin, PermissionScope.Tenant, [memberTenant, roleTenant, profileTenant]), + new(BuiltInRoleKey.Instructor, PermissionScope.Tenant, []), + new(BuiltInRoleKey.Learner, PermissionScope.Tenant, [profileTenant]), + new(BuiltInRoleKey.Guardian, PermissionScope.Tenant, []), + new(BuiltInRoleKey.Editor, PermissionScope.Tenant, []), + new(BuiltInRoleKey.OrgAdmin, PermissionScope.Organization, [memberOrganization, profileOrganization]), + new(BuiltInRoleKey.OrgInstructor, PermissionScope.Organization, []), + new(BuiltInRoleKey.Learner, PermissionScope.Organization, [profileOrganization]), + ]; + TenantAdminKernel = [memberTenant, roleTenant]; + Fingerprint = Hash(["learnstack.identity.foundation.manifest.v1", .. Definitions.Select(DefinitionToken), + .. Templates.Select(template => $"{template.BuiltInKey}:{template.Scope}:{string.Join(',', template.Grants.Select(DefinitionToken))}"), + .. TenantAdminKernel.Select(DefinitionToken)]); + TenantAdminKernelSqlValues = string.Join(", ", TenantAdminKernel.Select(definition => + $"('{definition.Scope}', '{definition.Key}')")); + } + + public int Version { get; } = 1; + public string Fingerprint { get; } + public ImmutableArray Definitions { get; } + public ImmutableArray Templates { get; } + public ImmutableArray TenantAdminKernel { get; } + // Generated from the same immutable values used by registry and seed verification. + public string TenantAdminKernelSqlValues { get; } + + public string RolePairsSqlValues => string.Join(", ", Templates.Select(template => + $"('{template.BuiltInKey}', '{template.Scope}')")); + public string RegistrySqlValues => string.Join(", ", Definitions.Select(definition => + $"('{definition.Scope}', '{definition.Key}')")); + public string GrantSqlValues => string.Join(", ", Templates.SelectMany(template => template.Grants.Select(definition => + $"('{template.BuiltInKey}', '{template.Scope}', '{definition.Key}')"))); + public string KernelSqlValues => TenantAdminKernelSqlValues; + + public BuiltInRoleTemplate? FindTemplate(BuiltInRoleKey key, PermissionScope scope) => + Templates.SingleOrDefault(template => template.BuiltInKey == key && template.Scope == scope); + + public bool IsActive(PermissionScope scope, string key) => + Definitions.Any(definition => definition.IsActive && definition.Scope == scope && definition.Key == key); + + public string RoleFingerprint(TenantId tenantId, Guid roleId, BuiltInRoleKey key, PermissionScope scope) => + Hash([Fingerprint, "role", Id(tenantId.Value), Id(roleId), key.ToString(), scope.ToString()]); + + public string MembershipFingerprint(TenantId tenantId, OrganizationId? organizationId, Guid membershipId, + UserId userId, Guid roleId) => Hash([Fingerprint, "membership", Id(tenantId.Value), + organizationId is { } organization ? Id(organization.Value) : "", Id(membershipId), Id(userId.Value), Id(roleId)]); + + public string ProfileFingerprint(TenantId tenantId, OrganizationId? organizationId, Guid membershipId, + string? displayName, string? preferredLocale) => Hash([Fingerprint, "profile", Id(tenantId.Value), + organizationId is { } organization ? Id(organization.Value) : "", Id(membershipId), + displayName is null ? "null" : "value:" + displayName, + preferredLocale is null ? "null" : "value:" + preferredLocale]); + + private static string DefinitionToken(PermissionDefinition definition) => + $"{definition.Scope}:{definition.Key}:{definition.IsActive}"; + + private static string Id(Guid value) => value.ToString("D", CultureInfo.InvariantCulture); + + private static string Hash(IEnumerable fields) + { + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + Span length = stackalloc byte[4]; + foreach (var field in fields) + { + var bytes = Encoding.UTF8.GetBytes(field); + BinaryPrimitives.WriteInt32BigEndian(length, bytes.Length); + hash.AppendData(length); + hash.AppendData(bytes); + } + return Convert.ToHexStringLower(hash.GetHashAndReset()); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/Membership.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/Membership.cs new file mode 100644 index 000000000..b79a1301a --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/Membership.cs @@ -0,0 +1,145 @@ +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Domain; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Localization; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Results; + +namespace LearnStack.Modules.Identity.Domain; + +public enum MembershipStatus { Active = 1, Suspended = 2, Revoked = 3 } + +[TenantOwned] +[OrganizationScoped] +public sealed class Membership : AuditableEntity, IAggregateRoot, IOrganizationScoped +{ + private readonly List _roleAssignments = []; + private Membership() { Profile = null!; } + + public TenantId TenantId { get; private set; } + public OrganizationId? OrganizationId { get; private set; } + public UserId UserId { get; private set; } + public MembershipStatus Status { get; private set; } + public MembershipProfile Profile { get; private set; } + public IReadOnlyCollection RoleAssignments => _roleAssignments.AsReadOnly(); + + public static Result Create(MembershipId id, TenantId tenantId, OrganizationId? organizationId, + UserId userId, Role role, DateTimeOffset at, UserId actor) + { + ArgumentNullException.ThrowIfNull(role); + if (!id.IsInitialized() || id.Value == Guid.Empty || id.Value.Version != 7) + throw new ArgumentException("Membership identifier is invalid.", nameof(id)); + TenantOwnership.EnsureRealTenant(tenantId, "Membership tenant is invalid.", nameof(tenantId)); + if (organizationId is { } organization && (!organization.IsInitialized() || organization.Value == Guid.Empty)) + throw new ArgumentException("Membership organization is invalid.", nameof(organizationId)); + if (!userId.IsInitialized() || userId.Value == Guid.Empty || userId.Value.Version != 7 || userId == UserId.SystemActor) + return Result.Fail(IdentityFailures.Refused()); + if (role.TenantId != tenantId || role.IsDeleted + || role.PermissionScope != (organizationId is null ? PermissionScope.Tenant : PermissionScope.Organization)) + return Result.Fail(IdentityFailures.Refused()); + var membership = new Membership + { + Id = id, + TenantId = tenantId, + OrganizationId = organizationId, + UserId = userId, + Status = MembershipStatus.Active, + }; + membership.MarkCreated(at, actor); + membership.Profile = new MembershipProfile(membership); + membership._roleAssignments.Add(new MembershipRoleAssignment(membership, role.Id)); + return Result.Ok(membership); + } + + public Result SetProfile(string? displayName, string? preferredLocale, DateTimeOffset at, UserId actor) + { + if (Status != MembershipStatus.Active || IsDeleted || !MembershipProfile.IsValid(displayName, preferredLocale)) + return IdentityFailures.BusinessRule(); + if (Profile.DisplayName == displayName && Profile.PreferredLocale == preferredLocale) + return Result.Ok(None.Value); + MarkUpdated(at, actor); + Profile.Set(displayName, preferredLocale); + return Result.Ok(None.Value); + } + + public Result Suspend(DateTimeOffset at, UserId actor) + { + if (Status != MembershipStatus.Active || IsDeleted) return IdentityFailures.BusinessRule(); + MarkUpdated(at, actor); + Status = MembershipStatus.Suspended; + return Result.Ok(None.Value); + } + + public Result Reactivate(DateTimeOffset at, UserId actor) + { + if (Status != MembershipStatus.Suspended || IsDeleted) return IdentityFailures.BusinessRule(); + MarkUpdated(at, actor); + Status = MembershipStatus.Active; + return Result.Ok(None.Value); + } + + public Result Revoke(DateTimeOffset at, UserId actor) + { + if (Status == MembershipStatus.Revoked || IsDeleted) return IdentityFailures.BusinessRule(); + SoftDelete(at, actor); + Status = MembershipStatus.Revoked; + return Result.Ok(None.Value); + } +} + +[TenantOwned] +[OrganizationScoped] +public sealed class MembershipProfile : IOrganizationScoped +{ + private MembershipProfile() { Membership = null!; } + internal MembershipProfile(Membership membership) + { + Membership = membership; + TenantId = membership.TenantId; + MembershipId = membership.Id; + OrganizationId = membership.OrganizationId; + } + + public const int MaximumDisplayNameLength = 128; + public const int MaximumLocaleLength = 35; + public TenantId TenantId { get; private set; } + public MembershipId MembershipId { get; private set; } + public OrganizationId? OrganizationId { get; private set; } + [PiiSensitive] + public string? DisplayName { get; private set; } + [PiiSensitive] + public string? PreferredLocale { get; private set; } + public Membership Membership { get; private set; } + + public static bool IsValid(string? displayName, string? preferredLocale) => + (displayName is null || displayName.Length is > 0 and <= MaximumDisplayNameLength + && !displayName.Any(char.IsControl) && !string.IsNullOrWhiteSpace(displayName) && JsonValue.IsStorableText(displayName)) + && (preferredLocale is null || preferredLocale.Length <= MaximumLocaleLength && LocaleTag.IsWellFormed(preferredLocale)); + + internal void Set(string? displayName, string? preferredLocale) + { + DisplayName = displayName; + PreferredLocale = preferredLocale; + } +} + +[TenantOwned] +[OrganizationScoped] +public sealed class MembershipRoleAssignment : IOrganizationScoped +{ + private MembershipRoleAssignment() { Membership = null!; } + internal MembershipRoleAssignment(Membership membership, RoleId roleId) + { + Membership = membership; + TenantId = membership.TenantId; + MembershipId = membership.Id; + OrganizationId = membership.OrganizationId; + RoleId = roleId; + } + public TenantId TenantId { get; private set; } + public MembershipId MembershipId { get; private set; } + public RoleId RoleId { get; private set; } + public OrganizationId? OrganizationId { get; private set; } + public Membership Membership { get; private set; } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/Role.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/Role.cs new file mode 100644 index 000000000..87609c16e --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/Role.cs @@ -0,0 +1,65 @@ +using LearnStack.SharedKernel.Domain; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Results; + +namespace LearnStack.Modules.Identity.Domain; + +[TenantOwned] +public sealed class Role : AuditableEntity, IAggregateRoot, ITenantOwned +{ + private readonly List _grants = []; + private Role() { } + + public TenantId TenantId { get; private set; } + public BuiltInRoleKey BuiltInKey { get; private set; } + public PermissionScope PermissionScope { get; private set; } + public IReadOnlyCollection Grants => _grants.AsReadOnly(); + + public static Result Create(RoleId id, TenantId tenantId, BuiltInRoleKey builtInKey, + PermissionScope permissionScope, DateTimeOffset at, UserId actor) + { + if (!id.IsInitialized() || id.Value == Guid.Empty || id.Value.Version != 7) + throw new ArgumentException("Role identifier is invalid.", nameof(id)); + TenantOwnership.EnsureRealTenant(tenantId, "Role tenant is invalid.", nameof(tenantId)); + var template = IdentityFoundationManifest.Version1.FindTemplate(builtInKey, permissionScope); + if (template is null) return Result.Fail(IdentityFailures.Refused()); + var role = new Role { Id = id, TenantId = tenantId, BuiltInKey = builtInKey, PermissionScope = permissionScope }; + role.MarkCreated(at, actor); + foreach (var definition in template.Grants) role._grants.Add(new RolePermissionGrant(role, definition)); + return Result.Ok(role); + } + + public bool MatchesInitialTemplate() + { + var template = IdentityFoundationManifest.Version1.FindTemplate(BuiltInKey, PermissionScope); + return !IsDeleted && template is not null && _grants.Count == template.Grants.Length + && template.Grants.All(definition => _grants.Any(grant => grant.PermissionScope == definition.Scope + && grant.PermissionKey == definition.Key)); + } + + public bool IsTenantAdministrator => !IsDeleted && BuiltInKey == BuiltInRoleKey.TenantAdmin + && PermissionScope == PermissionScope.Tenant + && IdentityFoundationManifest.Version1.TenantAdminKernel.All(definition => + _grants.Any(grant => grant.PermissionScope == definition.Scope && grant.PermissionKey == definition.Key)); +} + +[TenantOwned] +public sealed class RolePermissionGrant : ITenantOwned +{ + private RolePermissionGrant() { PermissionKey = null!; Role = null!; } + internal RolePermissionGrant(Role role, PermissionDefinition definition) + { + Role = role; + TenantId = role.TenantId; + RoleId = role.Id; + PermissionScope = definition.Scope; + PermissionKey = definition.Key; + } + public TenantId TenantId { get; private set; } + public RoleId RoleId { get; private set; } + public PermissionScope PermissionScope { get; private set; } + public string PermissionKey { get; private set; } + public Role Role { get; private set; } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/User.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/User.cs new file mode 100644 index 000000000..7a19c5142 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Domain/User.cs @@ -0,0 +1,43 @@ +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Domain; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; + +namespace LearnStack.Modules.Identity.Domain; + +public enum UserStatus { Active = 1, Closing = 2, Closed = 3 } + +/// A permanent provider-subject binding; it contains no tenant-authored profile. +public sealed class User : AuditableEntity, IAggregateRoot +{ + private User() { SubjectKey = null!; } + + public IdentityAuthorityId AuthorityId { get; private set; } + public IdentitySubjectKey SubjectKey { get; private set; } + [PiiSensitive] + public string? ProviderSubject { get; private set; } + public UserStatus Status { get; private set; } + public AuditEntryId CreationAuditId { get; private set; } + public DateTimeOffset CreationAuditTimestamp { get; private set; } + + public static User Create(GlobalIdentitySubject subject, GlobalIdentityCreationReference creation, + DateTimeOffset at, UserId createdBy) + { + ArgumentNullException.ThrowIfNull(subject); + ArgumentNullException.ThrowIfNull(creation); + creation.RequireSubject(subject); + var user = new User + { + Id = creation.TargetUserId, + AuthorityId = subject.AuthorityId, + SubjectKey = subject.SubjectKey, + ProviderSubject = subject.Subject, + Status = UserStatus.Active, + CreationAuditId = creation.AuditId, + CreationAuditTimestamp = creation.Timestamp, + }; + user.MarkCreated(at, createdBy); + return user; + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/GlobalIdentityBindingService.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/GlobalIdentityBindingService.cs new file mode 100644 index 000000000..28f1c5ddc --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/GlobalIdentityBindingService.cs @@ -0,0 +1,152 @@ +using LearnStack.Application.Audit; +using LearnStack.Application.Persistence; +using LearnStack.Modules.Identity.Application.Abstractions; +using LearnStack.Modules.Identity.Application.Bindings; +using LearnStack.Modules.Identity.Application.Contracts.Bindings; +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Domain; +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.Tenancy; +using Microsoft.Extensions.Logging; +using Npgsql; + +namespace LearnStack.Modules.Identity.Infrastructure.Bindings; + +/// The sole production descriptor minter; facts alone never admit seed adoption. +public sealed class GlobalIdentityBindingService( + IGlobalIdentityUnitOfWork unit, + IAuditStateCapture capture, + ITenantContextAccessor tenantAccessor, + Func audit, + Func transaction, + IdentityAuthorityQualification qualification, + ISeedIdentityFoundationAdmission seedAdmission, + Func store, + Func handler, + ILogger logger) + : GlobalIdentityOwnerDescriptor.MintingSource, IIdentityBindingReader, ISeedIdentityBindingAdopter +{ + public async Task ResolveExistingAsync(GlobalIdentitySubject subject, UserId? claimedActor = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(subject); + if (HasInheritedAuthority()) return Refused(IdentityBindingOutcome.AdmissionDenied); + if (claimedActor is { } claimed && !ValidActor(claimed)) return Refused(IdentityBindingOutcome.Conflict); + if (qualification.Current?.Matches(subject) is not true) return Refused(IdentityBindingOutcome.AuthorityUnavailable); + var descriptor = ForLookup(subject, typeof(IdentityDbContext), typeof(User)); + IUnitOfWorkScope? frame = null; + IdentityBindingResult result; + bool cleanupSucceeded; + try + { + frame = await unit.BeginGlobalIdentityTransactionAsync(descriptor, TransactionMode.ReadOnly, cancellationToken); + result = Resolve(await store().FindExactAsync(subject, cancellationToken), subject, claimedActor); + await frame.CompleteAsync(cancellationToken); + } + catch (NpgsqlException) { result = Refused(IdentityBindingOutcome.StorageUnavailable); } + catch (UserBindingStorageException) { result = Refused(IdentityBindingOutcome.StorageUnavailable); } + catch (TimeoutException) { result = Refused(IdentityBindingOutcome.StorageUnavailable); } + finally { cleanupSucceeded = await DisposeOwnerAsync(frame); } + return cleanupSucceeded ? result : Refused(IdentityBindingOutcome.StorageUnavailable); + } + + public async Task AdoptAsync(GlobalIdentitySubject subject, UserId declaredActor, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(subject); + if (HasInheritedAuthority()) return Refused(IdentityBindingOutcome.AdmissionDenied); + if (!ValidActor(declaredActor)) return Refused(IdentityBindingOutcome.Conflict); + if (!await seedAdmission.AllowsAsync(subject, declaredActor, cancellationToken)) + return Refused(IdentityBindingOutcome.AdmissionDenied); + if (qualification.Current?.Matches(subject) is not true) return Refused(IdentityBindingOutcome.AuthorityUnavailable); + var descriptor = ForSeedAdoption(subject, declaredActor, typeof(IdentityDbContext), typeof(User)); + TransactionExecutionCoordinator.PreparedGlobalIdentityOwner? owner = null; + IdentityBindingResult result; + bool cleanupSucceeded; + try + { + owner = await TransactionExecutionCoordinator.PrepareGlobalIdentityOwnerAsync( + unit, capture, CurrentTenantContext, descriptor, cancellationToken); + var current = await store().FindExactAsync(subject, cancellationToken); + if (current is not null) + { + result = Resolve(current, subject, declaredActor); + await owner.CompleteExistingAsync(cancellationToken); + } + else + { + owner.AdmitSerializedAbsence(); + var response = await audit().ExecuteGlobalIdentityAsync(owner, + reference => transaction().ExecutePreparedGlobalIdentityAsync(owner, reference, + () => handler().HandleAsync(subject, reference, cancellationToken), cancellationToken), cancellationToken); + if (response.IsFailure && response.Error.Code == AuditErrors.UnclassifiedOperation.Code) + throw new InvalidOperationException("Global identity creation requires its classified audit operation."); + result = response.IsSuccess && owner.RecordedOutcome == AuditIntentState.Committed + ? IdentityBindingResult.Bound(response.Value, created: true) + : StorageFailure(owner); + } + } + catch (NpgsqlException) { result = StorageFailure(owner); } + catch (AuditWriteFailedException) { result = StorageFailure(owner); } + catch (UserBindingStorageException) { result = StorageFailure(owner); } + catch (IOException) { result = StorageFailure(owner); } + catch (TimeoutException) { result = StorageFailure(owner); } + finally { cleanupSucceeded = await DisposeOwnerAsync(owner); } + return cleanupSucceeded ? result : StorageFailure(owner); + } + + private static IdentityBindingResult StorageFailure(TransactionExecutionCoordinator.PreparedGlobalIdentityOwner? owner) => + Refused(owner?.RecordedOutcome == AuditIntentState.Indeterminate + ? IdentityBindingOutcome.Indeterminate : IdentityBindingOutcome.StorageUnavailable); + + private ITenantContext CurrentTenantContext => tenantAccessor.Current ?? UnresolvedTenantContext.Instance; + + private bool HasInheritedAuthority() + { + var context = CurrentTenantContext; + return context.IsResolved || context is EventTenantContext or JobTenantContext + || unit.HasActiveTransaction || unit.IsRollbackOnly || capture.HasOpenFrame || capture.Intents.Count != 0 + || capture.Changes.Count != 0 || capture.State != AuditIntentState.None; + } + + private async ValueTask DisposeOwnerAsync(IAsyncDisposable? owner) + { + if (owner is null) return true; + try + { + await owner.DisposeAsync(); + return true; + } +#pragma warning disable CA1031 // Cleanup is awaited without replacing a primary failure or cancellation. + catch (Exception) +#pragma warning restore CA1031 + { + LogCleanupFailure(logger, null); + return false; + } + } + + private static readonly Action LogCleanupFailure = LoggerMessage.Define( + LogLevel.Error, new EventId(1, "GlobalIdentityOwnerCleanupFailed"), + "Global identity owner cleanup failed; its scope retains connection cleanup responsibility."); + + private static IdentityBindingResult Resolve(User? user, GlobalIdentitySubject subject, UserId? claimedActor) + { + if (user is null) return Refused(IdentityBindingOutcome.NotFound); + if (user.Status != UserStatus.Active) return Refused(IdentityBindingOutcome.NonAdmitting); + if (user.AuthorityId != subject.AuthorityId || !user.SubjectKey.Equals(subject.SubjectKey) + || !string.Equals(user.ProviderSubject, subject.Subject, StringComparison.Ordinal) + || (claimedActor is { } actor && actor != user.Id)) return Refused(IdentityBindingOutcome.Conflict); + return IdentityBindingResult.Bound(user.Id, created: false); + } + + private static bool ValidActor(UserId actor) => actor.IsInitialized() && actor.Value != Guid.Empty + && actor.Value.Version == 7 && actor != UserId.SystemActor; + + private static IdentityBindingResult Refused(IdentityBindingOutcome outcome) => IdentityBindingResult.Refused(outcome); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityAuthorityDeploymentInstaller.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityAuthorityDeploymentInstaller.cs new file mode 100644 index 000000000..790ff97f1 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityAuthorityDeploymentInstaller.cs @@ -0,0 +1,48 @@ +using Npgsql; + +namespace LearnStack.Modules.Identity.Infrastructure.Bindings; + +/// Explicit deployment-only anchor installation on the caller's migration connection; never registered in API DI. +public static class IdentityAuthorityDeploymentInstaller +{ + public static async Task InstallAsync(NpgsqlConnection connection, IdentityAuthorityRegistration registration, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(connection); + ArgumentNullException.ThrowIfNull(registration); + await using var transaction = await connection.BeginTransactionAsync(cancellationToken); + try + { + await using (var role = new NpgsqlCommand("SELECT current_user", connection, transaction)) + if (await role.ExecuteScalarAsync(cancellationToken) is not "learnstack_migration") throw Refused(); + await using (var tableLock = new NpgsqlCommand( + "LOCK TABLE public.identity_authority IN SHARE ROW EXCLUSIVE MODE", connection, transaction)) + await tableLock.ExecuteNonQueryAsync(cancellationToken); + var exists = false; + await using (var read = new NpgsqlCommand( + "SELECT authority_id, issuer FROM public.identity_authority WHERE id = 1", connection, transaction)) + await using (var reader = await read.ExecuteReaderAsync(cancellationToken)) + { + exists = await reader.ReadAsync(cancellationToken); + if (exists && (reader.GetGuid(0) != registration.AuthorityId.Value + || !string.Equals(reader.GetString(1), registration.Issuer, StringComparison.Ordinal))) throw Refused(); + } + if (!exists) + { + await using var insert = new NpgsqlCommand( + "INSERT INTO public.identity_authority (id, authority_id, issuer) VALUES (1, @authority, @issuer)", + connection, transaction); + insert.Parameters.AddWithValue("authority", registration.AuthorityId.Value); + insert.Parameters.AddWithValue("issuer", registration.Issuer); + await insert.ExecuteNonQueryAsync(cancellationToken); + } + await transaction.CommitAsync(cancellationToken); + } + catch (NpgsqlException) + { + throw Refused(); + } + } + + private static InvalidOperationException Refused() => new("Identity authority deployment installation was refused."); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityAuthorityQualification.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityAuthorityQualification.cs new file mode 100644 index 000000000..8b15caa41 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityAuthorityQualification.cs @@ -0,0 +1,55 @@ +using System.Data; +using Npgsql; + +namespace LearnStack.Modules.Identity.Infrastructure.Bindings; + +/// Explicit startup qualification; request-time binding access only consumes its immutable result. +public sealed class IdentityAuthorityQualification( + Lazy dataSource, IdentityAuthorityRegistration? registration) +{ + private readonly object _gate = new(); + private Task? _qualification; + private IdentityAuthorityRegistration? _current; + + public IdentityAuthorityRegistration? Current => Volatile.Read(ref _current); + + public Task QualifyAsync(CancellationToken cancellationToken = default) + { + lock (_gate) return _qualification ??= QualifyCoreAsync(cancellationToken); + } + + private async Task QualifyCoreAsync(CancellationToken cancellationToken) + { + if (registration is null) throw Unavailable(); + try + { + await using var connection = await dataSource.Value.OpenConnectionAsync(cancellationToken); + await using var transaction = await connection.BeginTransactionAsync(IsolationLevel.ReadCommitted, cancellationToken); + await using (var readOnly = new NpgsqlCommand("SET TRANSACTION READ ONLY", connection, transaction)) + await readOnly.ExecuteNonQueryAsync(cancellationToken); + await using (var command = new NpgsqlCommand( + "SELECT current_user, authority_id, issuer FROM public.identity_authority WHERE id = 1", connection, transaction)) + await using (var reader = await command.ExecuteReaderAsync(cancellationToken)) + { + if (!await reader.ReadAsync(cancellationToken) + || reader.GetString(0) != "learnstack_app" + || reader.GetGuid(1) != registration.AuthorityId.Value + || !string.Equals(reader.GetString(2), registration.Issuer, StringComparison.Ordinal)) + throw Unavailable(); + } + await transaction.CommitAsync(cancellationToken); + Volatile.Write(ref _current, registration); + } + catch (NpgsqlException) + { + throw Unavailable(); + } + catch (TimeoutException) + { + throw Unavailable(); + } + } + + private static InvalidOperationException Unavailable() => + new("Identity authority startup qualification is unavailable or does not match deployment configuration."); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityAuthorityRegistration.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityAuthorityRegistration.cs new file mode 100644 index 000000000..d25d5bdd1 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityAuthorityRegistration.cs @@ -0,0 +1,44 @@ +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; + +namespace LearnStack.Modules.Identity.Infrastructure.Bindings; + +/// Deployment-pinned configuration; this value neither installs nor changes the stored authority. +public sealed class IdentityAuthorityRegistration +{ + public IdentityAuthorityRegistration(IdentityAuthorityId authorityId, string issuer) + { + if (!authorityId.IsInitialized() || authorityId.Value == Guid.Empty + || string.IsNullOrEmpty(issuer) || issuer.Length > 2048 + || !Uri.TryCreate(issuer, UriKind.Absolute, out var address) + || !address.IsWellFormedOriginalString() + || !string.Equals(address.AbsoluteUri, issuer, StringComparison.Ordinal) + || !(address.Scheme == Uri.UriSchemeHttps || (address.Scheme == Uri.UriSchemeHttp && address.IsLoopback)) + || address.UserInfo.Length != 0 || address.Query.Length != 0 || address.Fragment.Length != 0 + || !HasUnambiguousPath(address) + || !address.AbsolutePath.EndsWith("/realms/learnstack", StringComparison.Ordinal)) + throw new ArgumentException("Identity authority configuration is invalid."); + AuthorityId = authorityId; + Issuer = issuer; + } + + public IdentityAuthorityId AuthorityId { get; } + public string Issuer { get; } + + public bool Matches(GlobalIdentitySubject subject) => subject is not null + && subject.AuthorityId == AuthorityId && string.Equals(subject.Issuer, Issuer, StringComparison.Ordinal); + + // Keep deployment qualification compatible with the existing API issuer + // address grammar. Deployment-mode admission remains at the composition root. + private static bool HasUnambiguousPath(Uri address) => + !address.AbsolutePath.Contains("//", StringComparison.Ordinal) + && address.Segments.Skip(1).All(segment => + { + var decoded = Uri.UnescapeDataString(segment.TrimEnd('/')); + var pathPart = decoded.Split(';', 2)[0].TrimEnd(); + return pathPart is not ("." or "..") && !decoded.Any(char.IsControl) + && !decoded.Contains('/') && !decoded.Contains('\\') && !decoded.Contains('%'); + }); + + public override string ToString() => nameof(IdentityAuthorityRegistration); +} 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 new file mode 100644 index 000000000..f39fbe8e9 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Bindings/IdentityFoundationRegistration.cs @@ -0,0 +1,54 @@ +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Application.Abstractions; +using LearnStack.Modules.Identity.Application.Audit; +using LearnStack.Modules.Identity.Application.Bindings; +using LearnStack.Modules.Identity.Application.Contracts.Bindings; +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Persistence; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Npgsql; + +namespace LearnStack.Modules.Identity.Infrastructure.Bindings; + +public static class IdentityFoundationRegistration +{ + public static IServiceCollection AddIdentityContextualFoundation(this IServiceCollection services) + { + ArgumentNullException.ThrowIfNull(services); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + return services; + } + + /// Registers internal consumers only; qualification is an explicit startup act before admission activation. + public static IServiceCollection AddIdentityGlobalFoundation(this IServiceCollection services, + IdentityAuthorityRegistration? registration = null) + { + ArgumentNullException.ThrowIfNull(services); + services.TryAddScoped(provider => + provider.GetRequiredService() as IGlobalIdentityUnitOfWork + ?? throw new InvalidOperationException("The registered unit of work lacks global identity ownership.")); + services.TryAddScoped(); + services.AddModuleDbContext(); + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped>(provider => () => provider.GetRequiredService()); + services.TryAddScoped>(provider => () => provider.GetRequiredService()); + services.TryAddSingleton(provider => new IdentityAuthorityQualification( + provider.GetRequiredService>(), registration)); + services.TryAddSingleton(); + services.TryAddScoped(); + services.TryAddScoped(provider => provider.GetRequiredService()); + services.TryAddScoped(provider => provider.GetRequiredService()); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + return services; + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/LearnStack.Modules.Identity.Infrastructure.csproj b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/LearnStack.Modules.Identity.Infrastructure.csproj index 1328f095d..91c83d7c2 100644 --- a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/LearnStack.Modules.Identity.Infrastructure.csproj +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/LearnStack.Modules.Identity.Infrastructure.csproj @@ -5,6 +5,9 @@ + + + diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Configurations.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Configurations.cs new file mode 100644 index 000000000..2d1497cd2 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Configurations.cs @@ -0,0 +1,82 @@ +using LearnStack.Infrastructure.DataProtection; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +internal sealed class UserConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("users", table => + { + table.HasCheckConstraint("ck_users_actor", "uuid_extract_version(id) = 7 AND id <> '00000000-0000-7000-8000-000000000001'::uuid"); + table.HasCheckConstraint("ck_users_subject_key", "octet_length(subject_key) = 32"); + table.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'))"); + table.HasCheckConstraint("ck_users_status", "status IN ('Active', 'Closing', 'Closed')"); + table.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)"); + table.HasCheckConstraint("ck_users_no_soft_delete", "deleted_at IS NULL AND deleted_by IS NULL"); + }); + builder.HasKey(user => user.Id).HasName("pk_users"); + builder.Property(user => user.Id) + .HasConversion().ValueGeneratedNever(); + builder.Property(user => user.AuthorityId) + .HasConversion(); + builder.Property(user => user.SubjectKey).HasConversion( + new ValueConverter(value => value.ToByteArray(), value => IdentitySubjectKey.FromBytes(value)), + new ValueComparer((left, right) => left != null && left.Equals(right), + value => value.GetHashCode(), value => value)).HasColumnType("bytea").IsRequired(); + builder.Property(user => user.ProviderSubject).HasMaxLength(255); + builder.Property(user => user.Status).HasEnumAsText().IsRequired(); + builder.Property(user => user.CreationAuditId) + .HasConversion(); + builder.Property(user => user.CreationAuditTimestamp).IsRequired(); + builder.HasIndex(user => new { user.AuthorityId, user.SubjectKey }) + .IsUnique().HasDatabaseName("ux_users_authority_id_subject_key"); + builder.HasOne().WithMany().HasForeignKey(user => user.AuthorityId) + .HasPrincipalKey(authority => authority.AuthorityId).OnDelete(DeleteBehavior.Restrict) + .HasConstraintName("fk_users_identity_authority"); + builder.MapAuditColumns(); + // The app's INSERT grant covers initial creation only. EF otherwise + // explicitly inserts the four NULL update/deletion fields as well. + foreach (var name in new[] { nameof(User.UpdatedAt), nameof(User.UpdatedBy), + nameof(User.DeletedAt), nameof(User.DeletedBy) }) + builder.Metadata.FindProperty(name)!.SetBeforeSaveBehavior(PropertySaveBehavior.Ignore); + builder.DeclarePersonalData(PersonalDataCategory.Identity, + "Permanent actor/provider binding and creation-audit linkage; retained to prevent recreation after closure.", + nameof(User.Id), nameof(User.AuthorityId), nameof(User.SubjectKey), nameof(User.ProviderSubject), + nameof(User.CreationAuditId), nameof(User.CreationAuditTimestamp)); + builder.DeclarePersonalData(PersonalDataCategory.Identity, + "Admission lifecycle of the bound person; no tenant membership or profile is implied.", nameof(User.Status)); + } +} + +internal sealed class IdentityAuthorityConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("identity_authority", table => + { + table.HasCheckConstraint("ck_identity_authority_singleton", "id = 1"); + table.HasCheckConstraint("ck_identity_authority_assigned", "authority_id <> '00000000-0000-0000-0000-000000000000'::uuid"); + }); + builder.HasKey(authority => authority.Id).HasName("pk_identity_authority"); + builder.Property(authority => authority.Id).ValueGeneratedNever(); + builder.Property(authority => authority.AuthorityId) + .HasConversion(); + builder.HasAlternateKey(authority => authority.AuthorityId).HasName("ux_identity_authority_authority_id"); + builder.Property(authority => authority.Issuer).HasMaxLength(2048).IsRequired(); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Deployment authority registration: one stable authority UUID and exact configured issuer address, without person fields.", + nameof(IdentityAuthority.Id), nameof(IdentityAuthority.AuthorityId), nameof(IdentityAuthority.Issuer)); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualConfigurations.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualConfigurations.cs new file mode 100644 index 000000000..d345f6151 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualConfigurations.cs @@ -0,0 +1,139 @@ +using LearnStack.Infrastructure.DataProtection; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Persistence; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +internal static class ContextualIdentityMapping +{ + internal static void Tenant(this EntityTypeBuilder builder) where TEntity : class, ITenantOwned + => builder.Property(entity => entity.TenantId) + .HasConversion(); + + internal static void Scope(this EntityTypeBuilder builder, string table) where TEntity : class, IOrganizationScoped + { + builder.Tenant(); + builder.Property(entity => entity.OrganizationId) + .HasConversion(); + builder.HasIndex(entity => new { entity.TenantId, entity.OrganizationId }) + .HasDatabaseName($"ix_{table}_tenant_id_organization_id"); + } +} + +internal sealed class MembershipConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("memberships", table => + { + table.HasCheckConstraint("ck_memberships_status", "status IN ('Active','Suspended','Revoked')"); + table.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)"); + }); + builder.HasKey(entity => entity.Id).HasName("pk_memberships"); + builder.Property(entity => entity.Id).HasConversion().ValueGeneratedNever(); + builder.Scope("memberships"); + builder.HasAlternateKey(entity => new { entity.TenantId, entity.Id }).HasName("ux_memberships_tenant_id_id"); + builder.Property(entity => entity.UserId).HasConversion(); + builder.Property(entity => entity.Status).HasEnumAsText(); + builder.HasOne().WithMany().HasForeignKey(entity => entity.UserId).OnDelete(DeleteBehavior.Restrict).HasConstraintName("fk_memberships_user"); + builder.HasIndex(entity => entity.UserId).HasDatabaseName("ix_memberships_user_id"); + builder.HasIndex(entity => new { entity.TenantId, entity.UserId, entity.OrganizationId }).IsUnique() + .AreNullsDistinct(false).HasFilter("deleted_at IS NULL").HasDatabaseName("ux_memberships_current_scope"); + builder.HasOne(entity => entity.Profile).WithOne(entity => entity.Membership) + .HasForeignKey(entity => new { entity.TenantId, entity.MembershipId }) + .HasPrincipalKey(entity => new { entity.TenantId, entity.Id }) + .OnDelete(DeleteBehavior.Restrict).HasConstraintName("fk_membership_profiles_membership"); + builder.HasMany(entity => entity.RoleAssignments).WithOne(entity => entity.Membership) + .HasForeignKey(entity => new { entity.TenantId, entity.MembershipId }) + .HasPrincipalKey(entity => new { entity.TenantId, entity.Id }) + .OnDelete(DeleteBehavior.Restrict).HasConstraintName("fk_membership_role_assignments_membership"); + builder.Navigation(entity => entity.RoleAssignments).HasField("_roleAssignments").UsePropertyAccessMode(PropertyAccessMode.Field); + builder.MapAuditColumns(); + builder.DeclarePersonalData(PersonalDataCategory.Identity, + "Contextual person membership, immutable scope and admission lifecycle.", + nameof(Membership.Id), nameof(Membership.TenantId), nameof(Membership.OrganizationId), nameof(Membership.UserId), nameof(Membership.Status)); + } +} + +internal sealed class MembershipProfileConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("membership_profiles"); + builder.HasKey(entity => new { entity.TenantId, entity.MembershipId }).HasName("pk_membership_profiles"); + builder.Scope("membership_profiles"); + builder.Property(entity => entity.MembershipId).HasConversion().ValueGeneratedNever(); + builder.Property(entity => entity.DisplayName).HasMaxLength(128); + builder.Property(entity => entity.PreferredLocale).HasMaxLength(35); + builder.DeclarePersonalData(PersonalDataCategory.Identity, + "Contained contextual profile identity, scope and optional personal display and locale preferences.", + nameof(MembershipProfile.TenantId), nameof(MembershipProfile.OrganizationId), nameof(MembershipProfile.MembershipId), + nameof(MembershipProfile.DisplayName), nameof(MembershipProfile.PreferredLocale)); + } +} + +internal sealed class MembershipRoleAssignmentConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("membership_role_assignments"); + builder.HasKey(entity => new { entity.TenantId, entity.MembershipId, entity.RoleId }).HasName("pk_membership_role_assignments"); + builder.Scope("membership_role_assignments"); + builder.Property(entity => entity.MembershipId).HasConversion().ValueGeneratedNever(); + builder.Property(entity => entity.RoleId).HasConversion().ValueGeneratedNever(); + builder.HasOne().WithMany().HasForeignKey(entity => new { entity.TenantId, entity.RoleId }) + .HasPrincipalKey(entity => new { entity.TenantId, entity.Id }).OnDelete(DeleteBehavior.Restrict) + .HasConstraintName("fk_membership_role_assignments_role"); + builder.HasIndex(entity => new { entity.TenantId, entity.RoleId }).HasDatabaseName("ix_membership_role_assignments_tenant_id_role_id"); + builder.DeclarePersonalData(PersonalDataCategory.Identity, + "Contained person's contextual role assignment and exact Membership scope.", + nameof(MembershipRoleAssignment.TenantId), nameof(MembershipRoleAssignment.OrganizationId), + nameof(MembershipRoleAssignment.MembershipId), nameof(MembershipRoleAssignment.RoleId)); + } +} + +internal sealed class RoleConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("roles"); + builder.HasKey(entity => entity.Id).HasName("pk_roles"); + builder.Property(entity => entity.Id).HasConversion().ValueGeneratedNever(); + builder.Tenant(); + builder.HasAlternateKey(entity => new { entity.TenantId, entity.Id }).HasName("ux_roles_tenant_id_id"); + builder.Property(entity => entity.BuiltInKey).HasEnumAsText(); + builder.Property(entity => entity.PermissionScope).HasEnumAsText(); + builder.HasIndex(entity => new { entity.TenantId, entity.PermissionScope, entity.BuiltInKey }).IsUnique() + .HasFilter("deleted_at IS NULL").HasDatabaseName("ux_roles_current_builtin_scope"); + builder.HasMany(entity => entity.Grants).WithOne(entity => entity.Role) + .HasForeignKey(entity => new { entity.TenantId, entity.RoleId }) + .HasPrincipalKey(entity => new { entity.TenantId, entity.Id }).OnDelete(DeleteBehavior.Restrict) + .HasConstraintName("fk_role_permission_grants_role"); + builder.Navigation(entity => entity.Grants).HasField("_grants").UsePropertyAccessMode(PropertyAccessMode.Field); + builder.MapAuditColumns(); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Institution-owned built-in authorization template identity and capability scope, without person fields.", + nameof(Role.Id), nameof(Role.TenantId), nameof(Role.BuiltInKey), nameof(Role.PermissionScope)); + } +} + +internal sealed class RolePermissionGrantConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("role_permission_grants"); + builder.HasKey(entity => new { entity.TenantId, entity.RoleId, entity.PermissionScope, entity.PermissionKey }).HasName("pk_role_permission_grants"); + builder.Tenant(); + builder.Property(entity => entity.RoleId).HasConversion().ValueGeneratedNever(); + builder.Property(entity => entity.PermissionScope).HasEnumAsText(); + builder.Property(entity => entity.PermissionKey).HasMaxLength(128); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Contained finite template capability grant, without a person assignment.", + nameof(RolePermissionGrant.TenantId), nameof(RolePermissionGrant.RoleId), nameof(RolePermissionGrant.PermissionScope), nameof(RolePermissionGrant.PermissionKey)); + } +} 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 new file mode 100644 index 000000000..e95778efc --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualIdentityStorageDdl.cs @@ -0,0 +1,429 @@ +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Permissions; +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +/// Contextual Identity guards. Lock observations never acquire authority. +public static class ContextualIdentityStorageDdl +{ + public static void Install(MigrationBuilder migration) + { + ArgumentNullException.ThrowIfNull(migration); + // Keep the original migration's SQL unchanged; each forward correction + // replaces only its function on both existing and fresh databases. + migration.Sql(Guards.Replace("__MEMBERSHIP_ADMISSION_GUARD__", + "CREATE " + MembershipAdmissionGuardSql(correctParentMirror: false), StringComparison.Ordinal) + + "\n\nCREATE " + MutationGuardSql(correctParentMirror: false) + + "\n" + MutationGuardRevocation); + migration.Sql(CompleteGraphGuard()); + foreach (var table in new[] { "memberships", "membership_profiles", "membership_role_assignments" }) + { + 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(); + """); + } + foreach (var table in new[] { "roles", "role_permission_grants" }) + { + 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) + WITH CHECK (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid); + """); + } + foreach (var table in new[] { "memberships", "membership_profiles", "membership_role_assignments", "roles", "role_permission_grants" }) + { + migration.Sql($""" + REVOKE ALL ON public.{table} FROM PUBLIC, learnstack_app, learnstack_platform, learnstack_outbox_admin; + CREATE TRIGGER tg_{table}_mutation_guard BEFORE INSERT OR UPDATE OR DELETE ON public.{table} + FOR EACH ROW EXECUTE FUNCTION public.fn_identity_contextual_mutation_guard(); + CREATE CONSTRAINT TRIGGER tg_{table}_complete_graph AFTER INSERT OR UPDATE OR DELETE ON public.{table} + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION public.fn_identity_complete_graph_guard(); + """); + } + migration.Sql(""" + GRANT SELECT, INSERT, UPDATE ON public.memberships, public.membership_profiles, public.roles TO learnstack_app; + GRANT SELECT, INSERT, DELETE ON public.membership_role_assignments, public.role_permission_grants TO learnstack_app; + CREATE TRIGGER tg_memberships_admission BEFORE INSERT OR UPDATE ON public.memberships + FOR EACH ROW EXECUTE FUNCTION public.fn_identity_membership_admission_guard(); + CREATE TRIGGER tg_membership_role_assignments_admission BEFORE INSERT ON public.membership_role_assignments + FOR EACH ROW EXECUTE FUNCTION public.fn_identity_membership_admission_guard(); + """); + } + + public static void Remove(MigrationBuilder migration) + { + ArgumentNullException.ThrowIfNull(migration); + foreach (var table in new[] { "memberships", "membership_profiles", "membership_role_assignments", "roles", "role_permission_grants" }) + migration.Sql($"DROP TRIGGER tg_{table}_complete_graph ON public.{table}; DROP TRIGGER tg_{table}_mutation_guard ON public.{table};"); + migration.Sql(""" + DROP TRIGGER tg_memberships_admission ON public.memberships; + DROP TRIGGER tg_membership_role_assignments_admission ON public.membership_role_assignments; + DROP FUNCTION public.fn_identity_complete_graph_guard(); + DROP FUNCTION public.fn_identity_contextual_mutation_guard(); + DROP FUNCTION public.fn_identity_membership_admission_guard(); + DROP FUNCTION public.fn_identity_admin_admission_state(uuid, uuid); + DROP FUNCTION public.fn_identity_assert_tenant_fence(uuid, boolean); + DROP FUNCTION public.fn_identity_lock_held(text, uuid, boolean); + DROP FUNCTION public.fn_identity_contextual_lock_key(text, uuid); + """); + } + + internal static void CorrectParentMirrorSqlState(MigrationBuilder migration) + { + ArgumentNullException.ThrowIfNull(migration); + migration.Sql("CREATE OR REPLACE " + MutationGuardSql(correctParentMirror: true)); + } + + internal static void RestoreLegacyParentMirrorSqlState(MigrationBuilder migration) + { + ArgumentNullException.ThrowIfNull(migration); + migration.Sql("CREATE OR REPLACE " + MutationGuardSql(correctParentMirror: false)); + } + + internal static void CorrectAdmissionParentMirrorSqlState(MigrationBuilder migration) + { + ArgumentNullException.ThrowIfNull(migration); + migration.Sql("CREATE OR REPLACE " + MembershipAdmissionGuardSql(correctParentMirror: true)); + } + + internal static void RestoreLegacyAdmissionParentMirrorSqlState(MigrationBuilder migration) + { + ArgumentNullException.ThrowIfNull(migration); + migration.Sql("CREATE OR REPLACE " + MembershipAdmissionGuardSql(correctParentMirror: false)); + } + + internal static void SerializeParentLifecycle(MigrationBuilder migration) + { + ArgumentNullException.ThrowIfNull(migration); + migration.Sql("CREATE OR REPLACE " + MutationGuardSql(correctParentMirror: true, serializeParentLifecycle: true)); + } + + internal static void RestoreLegacyParentLifecycleLock(MigrationBuilder migration) + { + ArgumentNullException.ThrowIfNull(migration); + migration.Sql("CREATE OR REPLACE " + MutationGuardSql(correctParentMirror: true)); + } + + private static string MembershipAdmissionGuardSql(bool correctParentMirror) => MembershipAdmissionGuardDefinition + .Replace("__MISSING_MEMBERSHIP_REFUSAL__", + correctParentMirror ? MembershipParentRefusal : LegacyMembershipParentRefusal, StringComparison.Ordinal); + + private static string MutationGuardSql(bool correctParentMirror, bool serializeParentLifecycle = false) => MutationGuardDefinition + .Replace("__PARENT_MIRROR_CHECK__", correctParentMirror ? ParentMirrorCheck : LegacyParentMirrorCheck, + StringComparison.Ordinal) + .Replace("__ROLE_ADMIN_KEY__", IdentityFoundationManifest.RoleAdmin, StringComparison.Ordinal) + // KEY SHARE protects references but permits a concurrent status UPDATE. + // The forward migration pins lifecycle through the fresh read and commit. + .Replace("target_member FOR KEY SHARE;", serializeParentLifecycle + ? "target_member FOR NO KEY UPDATE;" : "target_member FOR KEY SHARE;", StringComparison.Ordinal); + + private static string CompleteGraphGuard() + { + var manifest = IdentityFoundationManifest.Version1; + return $$""" + ALTER TABLE public.roles ADD CONSTRAINT ck_roles_finite_template + CHECK ((built_in_key,permission_scope) IN ({{manifest.RolePairsSqlValues}})); + ALTER TABLE public.role_permission_grants ADD CONSTRAINT ck_role_permission_grants_registry + CHECK ((permission_scope,permission_key) IN ({{manifest.RegistrySqlValues}})); + CREATE FUNCTION public.fn_identity_complete_graph_guard() RETURNS trigger + LANGUAGE plpgsql VOLATILE SECURITY INVOKER SET search_path = pg_catalog + AS $guard$ + DECLARE target_tenant uuid; target_member uuid; target_role uuid; has_history boolean; + BEGIN + target_tenant := CASE WHEN TG_OP = 'DELETE' THEN OLD.tenant_id ELSE NEW.tenant_id END; + PERFORM public.fn_identity_assert_tenant_fence(target_tenant,false); + IF TG_TABLE_NAME IN ('memberships','membership_profiles','membership_role_assignments') THEN + IF TG_TABLE_NAME = 'memberships' THEN + target_member := CASE WHEN TG_OP = 'DELETE' THEN OLD.id ELSE NEW.id END; + ELSE + target_member := CASE WHEN TG_OP = 'DELETE' THEN OLD.membership_id ELSE NEW.membership_id END; + END IF; + IF NOT EXISTS (SELECT 1 FROM public.memberships AS member + JOIN public.membership_profiles AS profile ON profile.tenant_id = member.tenant_id AND profile.membership_id = member.id + WHERE member.tenant_id = target_tenant AND member.id = target_member + AND profile.organization_id IS NOT DISTINCT FROM member.organization_id) THEN + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; + END IF; + END IF; + SELECT EXISTS (SELECT 1 FROM public.memberships WHERE tenant_id = target_tenant) INTO has_history; + IF NOT has_history AND TG_TABLE_NAME IN ('roles','role_permission_grants') THEN + IF TG_TABLE_NAME = 'roles' THEN target_role := NEW.id; ELSE target_role := NEW.role_id; END IF; + IF TG_OP <> 'INSERT' OR NOT EXISTS (SELECT 1 FROM public.roles AS role + WHERE role.tenant_id = target_tenant AND role.id = target_role + AND role.xmin = pg_current_xact_id()::text::xid AND role.deleted_at IS NULL AND role.deleted_by IS NULL + AND NOT EXISTS ( + (SELECT expected.scope, expected.permission_key FROM (VALUES {{manifest.GrantSqlValues}}) AS expected(built_in_key,scope,permission_key) + WHERE expected.built_in_key = role.built_in_key AND expected.scope = role.permission_scope + EXCEPT SELECT grant_row.permission_scope, grant_row.permission_key FROM public.role_permission_grants AS grant_row + WHERE grant_row.tenant_id = target_tenant AND grant_row.role_id = target_role) + UNION ALL + (SELECT grant_row.permission_scope, grant_row.permission_key FROM public.role_permission_grants AS grant_row + WHERE grant_row.tenant_id = target_tenant AND grant_row.role_id = target_role + EXCEPT SELECT expected.scope, expected.permission_key FROM (VALUES {{manifest.GrantSqlValues}}) AS expected(built_in_key,scope,permission_key) + WHERE expected.built_in_key = role.built_in_key AND expected.scope = role.permission_scope))) THEN + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304', CONSTRAINT = 'identity_initial_template'; + END IF; + RETURN NULL; + END IF; + IF NOT EXISTS (SELECT 1 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 = target_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 {{manifest.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 public.fn_identity_admin_admission_state(member.user_id,target_tenant)) THEN + RAISE EXCEPTION 'identity administration is unavailable' USING ERRCODE = 'P0303'; + END IF; + RETURN NULL; + END; + $guard$; + COMMENT ON FUNCTION public.fn_identity_complete_graph_guard() IS 'Identity foundation v{{manifest.Version}} {{manifest.Fingerprint}}'; + REVOKE ALL ON FUNCTION public.fn_identity_complete_graph_guard() FROM PUBLIC, learnstack_app, learnstack_platform, learnstack_outbox_admin; + """; + } + + private const string Guards = """ + CREATE FUNCTION public.fn_identity_contextual_lock_key(kind text, target uuid) RETURNS bigint + LANGUAGE sql IMMUTABLE STRICT SECURITY INVOKER SET search_path = pg_catalog + AS $$ + SELECT ('x' || substr(encode(sha256( + int4send(octet_length(convert_to('learnstack.identity.lock.v1','UTF8'))) + || convert_to('learnstack.identity.lock.v1','UTF8') + || int4send(octet_length(convert_to(kind,'UTF8'))) || convert_to(kind,'UTF8') + || int4send(16) || uuid_send(target)), 'hex'),1,16))::bit(64)::bigint + WHERE kind IN ('user','tenant'); + $$; + REVOKE ALL ON FUNCTION public.fn_identity_contextual_lock_key(text, uuid) FROM PUBLIC; + GRANT EXECUTE ON FUNCTION public.fn_identity_contextual_lock_key(text, uuid) TO learnstack_app; + + CREATE FUNCTION public.fn_identity_lock_held(kind text, target uuid, exclusive_required boolean) RETURNS boolean + LANGUAGE sql VOLATILE STRICT SECURITY INVOKER SET search_path = pg_catalog + AS $$ + SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_locks AS held + WHERE held.pid = pg_catalog.pg_backend_pid() + AND held.database = (SELECT oid FROM pg_catalog.pg_database WHERE datname = pg_catalog.current_database()) + AND held.locktype = 'advisory' AND held.granted + AND (held.mode = 'ExclusiveLock' OR (NOT exclusive_required AND held.mode = 'ShareLock')) + AND held.objsubid = 1 + AND ((held.classid::bigint << 32) | held.objid::bigint) = public.fn_identity_contextual_lock_key(kind,target)); + $$; + REVOKE ALL ON FUNCTION public.fn_identity_lock_held(text, uuid, boolean) FROM PUBLIC; + GRANT EXECUTE ON FUNCTION public.fn_identity_lock_held(text, uuid, boolean) TO learnstack_app; + + CREATE FUNCTION public.fn_identity_assert_tenant_fence(target uuid, exclusive_required boolean) RETURNS void + LANGUAGE plpgsql VOLATILE SECURITY INVOKER SET search_path = pg_catalog + AS $$ + BEGIN + IF current_setting('transaction_isolation') <> 'read committed' + OR target IS DISTINCT FROM NULLIF(current_setting('app.tenant_id',true),'')::uuid + OR public.fn_identity_lock_held('tenant',target,exclusive_required) IS NOT TRUE THEN + RAISE EXCEPTION 'identity mutation plan is unavailable' USING ERRCODE = 'P0301', CONSTRAINT = 'identity_tenant_fence'; + END IF; + END; + $$; + REVOKE ALL ON FUNCTION public.fn_identity_assert_tenant_fence(uuid, boolean) FROM PUBLIC; + GRANT EXECUTE ON FUNCTION public.fn_identity_assert_tenant_fence(uuid, boolean) TO learnstack_app; + + __MEMBERSHIP_ADMISSION_GUARD__ + ALTER FUNCTION public.fn_identity_membership_admission_guard() OWNER TO learnstack_migration; + REVOKE ALL ON FUNCTION public.fn_identity_membership_admission_guard() FROM PUBLIC, learnstack_app, learnstack_platform, learnstack_outbox_admin; + + CREATE FUNCTION public.fn_identity_admin_admission_state(target_user uuid, target_tenant uuid) RETURNS boolean + LANGUAGE plpgsql VOLATILE SECURITY DEFINER SET search_path = pg_catalog + AS $$ + DECLARE eligible boolean; + BEGIN + IF pg_catalog.pg_trigger_depth() < 1 THEN RETURN false; END IF; + PERFORM public.fn_identity_assert_tenant_fence(target_tenant, false); + IF NOT EXISTS (SELECT 1 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 = target_tenant AND member.user_id = target_user + 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) THEN + RETURN false; + END IF; + SELECT person.status = 'Active' AND person.deleted_at IS NULL AND person.deleted_by IS NULL + INTO eligible FROM public.users AS person WHERE person.id = target_user; + RETURN COALESCE(eligible,false); + END; + $$; + ALTER FUNCTION public.fn_identity_admin_admission_state(uuid, uuid) OWNER TO learnstack_migration; + REVOKE ALL ON FUNCTION public.fn_identity_admin_admission_state(uuid, uuid) FROM PUBLIC, learnstack_platform, learnstack_outbox_admin; + GRANT EXECUTE ON FUNCTION public.fn_identity_admin_admission_state(uuid, uuid) TO learnstack_app; + """; + + private const string MembershipAdmissionGuardDefinition = """ + FUNCTION public.fn_identity_membership_admission_guard() RETURNS trigger + LANGUAGE plpgsql VOLATILE SECURITY DEFINER SET search_path = pg_catalog + AS $$ + DECLARE target_user uuid; target_tenant uuid; eligible boolean; + BEGIN + IF TG_TABLE_SCHEMA <> 'public' THEN + RAISE EXCEPTION 'identity mutation plan is unavailable' USING ERRCODE = 'P0301'; + END IF; + IF TG_TABLE_NAME = 'memberships' AND TG_OP IN ('INSERT','UPDATE') THEN + IF TG_OP = 'UPDATE' AND NOT (OLD.status = 'Suspended' AND NEW.status = 'Active') THEN RETURN NEW; END IF; + target_user := NEW.user_id; + target_tenant := NEW.tenant_id; + ELSIF TG_TABLE_NAME = 'membership_role_assignments' AND TG_OP = 'INSERT' THEN + SELECT member.user_id, member.tenant_id INTO target_user, target_tenant + FROM public.memberships AS member + WHERE member.tenant_id = NEW.tenant_id AND member.id = NEW.membership_id; + IF NOT FOUND THEN + __MISSING_MEMBERSHIP_REFUSAL__ + END IF; + ELSE + RAISE EXCEPTION 'identity mutation plan is unavailable' USING ERRCODE = 'P0301'; + END IF; + PERFORM public.fn_identity_assert_tenant_fence(target_tenant, false); + IF public.fn_identity_lock_held('user',target_user,true) IS NOT TRUE THEN + RAISE EXCEPTION 'identity mutation plan is unavailable' USING ERRCODE = 'P0301', CONSTRAINT = 'identity_user_fence'; + END IF; + SELECT person.status = 'Active' AND person.deleted_at IS NULL AND person.deleted_by IS NULL + INTO eligible FROM public.users AS person WHERE person.id = target_user; + IF eligible IS NOT TRUE THEN + RAISE EXCEPTION 'identity membership target is unavailable' USING ERRCODE = 'P0302'; + END IF; + RETURN NEW; + END; + $$; + """; + + private const string LegacyMembershipParentRefusal = + " RAISE EXCEPTION 'identity membership target is unavailable' USING ERRCODE = 'P0302';"; + + private const string MembershipParentRefusal = + " RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = '23514', CONSTRAINT = 'membership_parent_scope';"; + + private const string MutationGuardDefinition = """ + FUNCTION public.fn_identity_contextual_mutation_guard() RETURNS trigger + LANGUAGE plpgsql VOLATILE SECURITY INVOKER SET search_path = pg_catalog + AS $$ + 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; + 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 + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; + END IF; + IF TG_TABLE_NAME = 'memberships' THEN + IF TG_OP = 'DELETE' OR (TG_OP = 'INSERT' AND (NEW.status <> 'Active' OR NEW.deleted_at IS NOT NULL OR NEW.deleted_by IS NOT NULL)) THEN + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; + END IF; + IF TG_OP = 'UPDATE' AND (NEW.id IS DISTINCT FROM OLD.id OR NEW.user_id IS DISTINCT FROM OLD.user_id + OR OLD.status = 'Revoked' OR NEW.status NOT IN ('Active','Suspended','Revoked')) THEN + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; + END IF; + IF TG_OP = 'INSERT' THEN + require_exclusive := NOT EXISTS (SELECT 1 FROM public.memberships WHERE tenant_id = target_tenant); + ELSIF NEW.status IS DISTINCT FROM OLD.status OR NEW.deleted_at IS DISTINCT FROM OLD.deleted_at THEN + SELECT EXISTS (SELECT 1 FROM public.membership_role_assignments AS assignment + JOIN public.roles AS role ON role.tenant_id = assignment.tenant_id AND role.id = assignment.role_id + WHERE assignment.tenant_id = target_tenant AND assignment.membership_id = OLD.id + AND OLD.organization_id IS NULL AND role.built_in_key = 'TenantAdmin' AND role.permission_scope = 'Tenant') INTO require_exclusive; + END IF; + ELSIF TG_TABLE_NAME IN ('membership_profiles','membership_role_assignments') THEN + target_member := CASE WHEN TG_OP = 'DELETE' THEN OLD.membership_id ELSE NEW.membership_id END; + 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 + FROM public.memberships AS member WHERE member.tenant_id = target_tenant AND member.id = target_member FOR KEY SHARE; + __PARENT_MIRROR_CHECK__ + 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 + IF TG_OP = 'UPDATE' THEN RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; END IF; + target_role := CASE WHEN TG_OP = 'DELETE' THEN OLD.role_id ELSE NEW.role_id END; + SELECT role.permission_scope, role.built_in_key INTO role_scope, role_key FROM public.roles AS role + WHERE role.tenant_id = target_tenant AND role.id = target_role FOR KEY SHARE; + IF NOT FOUND OR (parent_org IS NULL AND role_scope <> 'Tenant') OR (parent_org IS NOT NULL AND role_scope <> 'Organization') THEN + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; + END IF; + require_exclusive := parent_org IS NULL AND role_key = 'TenantAdmin'; + END IF; + ELSIF TG_TABLE_NAME IN ('roles','role_permission_grants') THEN + IF NULLIF(current_setting('app.organization_id',true),'') IS NOT NULL THEN + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; + END IF; + SELECT EXISTS (SELECT 1 FROM public.memberships WHERE tenant_id = target_tenant) INTO has_history; + IF TG_TABLE_NAME = 'roles' THEN + IF TG_OP = 'DELETE' OR (TG_OP = 'UPDATE' AND (NEW.id IS DISTINCT FROM OLD.id + OR NEW.built_in_key IS DISTINCT FROM OLD.built_in_key OR NEW.permission_scope IS DISTINCT FROM OLD.permission_scope)) THEN + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; + END IF; + IF NOT has_history AND TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; + END IF; + require_exclusive := has_history AND NEW.built_in_key = 'TenantAdmin'; + ELSE + IF TG_OP = 'UPDATE' THEN RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; END IF; + target_role := CASE WHEN TG_OP = 'DELETE' THEN OLD.role_id ELSE NEW.role_id END; + SELECT role.permission_scope, role.built_in_key, role.xmin = pg_current_xact_id()::text::xid + INTO role_scope, role_key, parent_fresh FROM public.roles AS role + WHERE role.tenant_id = target_tenant AND role.id = target_role FOR KEY SHARE; + IF NOT FOUND OR role_scope IS DISTINCT FROM (CASE WHEN TG_OP = 'DELETE' THEN OLD.permission_scope ELSE NEW.permission_scope END) + OR (NOT has_history AND (TG_OP <> 'INSERT' OR NOT parent_fresh)) + OR (TG_OP = 'INSERT' AND NEW.permission_key = '__ROLE_ADMIN_KEY__' AND role_key <> 'TenantAdmin') THEN + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; + END IF; + require_exclusive := has_history AND role_key = 'TenantAdmin'; + END IF; + ELSE + RAISE EXCEPTION 'identity mutation plan is unavailable' USING ERRCODE = 'P0301'; + END IF; + PERFORM public.fn_identity_assert_tenant_fence(target_tenant,require_exclusive); + IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; + RETURN NEW; + END; + $$; + """; + + private const string MutationGuardRevocation = + "REVOKE ALL ON FUNCTION public.fn_identity_contextual_mutation_guard() FROM PUBLIC, learnstack_app, learnstack_platform, learnstack_outbox_admin;"; + + private const string LegacyParentMirrorCheck = """ + IF NOT FOUND OR parent_org IS DISTINCT FROM (CASE WHEN TG_OP = 'DELETE' THEN OLD.organization_id ELSE NEW.organization_id END) + OR (TG_OP <> 'DELETE' AND parent_status = 'Revoked') THEN + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; + END IF; + """; + + private const string ParentMirrorCheck = """ + 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 + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; + END IF; + """; +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualIdentityStores.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualIdentityStores.cs new file mode 100644 index 000000000..caf5f06da --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/ContextualIdentityStores.cs @@ -0,0 +1,224 @@ +using System.Collections.Immutable; +using System.Data.Common; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Application.Abstractions; +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Persistence; +using Microsoft.EntityFrameworkCore; +using Npgsql; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +/// One scoped graph preflight on the existing owner; never interprets a physical COMMIT failure. +public sealed class ContextualIdentityStorageControl(IdentityDbContext db, IUnitOfWork unit) +{ + private bool _validated; + private bool _reportedPlanFault; + + public void PrepareFreshRead() + { + if (_validated || db.ChangeTracker.Entries().Any(entry => entry.State is EntityState.Added or EntityState.Modified or EntityState.Deleted)) + throw new InvalidOperationException("An Identity graph cannot be reread after mutation or validation."); + // Pre/post-wait reads must materialize fresh facts; a cached tracked entity + // would retain the earlier classification even after SQL returned new values. + db.ChangeTracker.Clear(); + } + + internal static async Task ReadAsync(Func> read) + { + // Only provider failures cross this boundary. Cancellation and source + // invariants keep their original meaning; reads never classify a COMMIT. + try { return await read(); } + catch (InvalidOperationException failure) when ( + failure.InnerException is NpgsqlException { IsTransient: true } or TimeoutException) + { + throw new IdentityStorageProviderException(); + } + catch (Exception failure) when (failure is DbException or TimeoutException) + { + throw new IdentityStorageProviderException(); + } + } + + public async Task SaveAsync(CancellationToken cancellationToken) + { + if (_validated) throw new InvalidOperationException("An Identity graph cannot change after validation."); + // The common owner must roll back this complete aggregate act on every + // failure. A private EF subtransaction supplies no recoverable boundary + // and gives a new Role a child xmin, defeating the exact first-act proof. + // Confine the setting to this save; global Identity keeps its own behavior. + var savepoints = db.Database.AutoSavepointsEnabled; + db.Database.AutoSavepointsEnabled = false; + try { await db.SaveChangesAsync(cancellationToken); } + catch (DbUpdateException failure) when (failure.InnerException is PostgresException postgres && IsOwned(postgres)) + { + unit.MarkRollbackOnly(); + throw Translate((PostgresException)failure.InnerException!); + } + catch (InvalidOperationException failure) when ( + failure.InnerException is DbUpdateException { InnerException: PostgresException postgres } && IsOwned(postgres)) + { + // Npgsql's non-retrying execution strategy wraps transient save + // failures. Translate only the same exact owned provider states. + unit.MarkRollbackOnly(); + throw Translate((PostgresException)failure.InnerException.InnerException!); + } + catch (InvalidOperationException failure) when (failure.InnerException is + DbUpdateException { InnerException: NpgsqlException { IsTransient: true } or TimeoutException } + or NpgsqlException { IsTransient: true } or TimeoutException) + { + unit.MarkRollbackOnly(); + throw new IdentityStorageProviderException(); + } + catch (DbUpdateConcurrencyException) + { + unit.MarkRollbackOnly(); + throw new IdentityFoundationStorageException(IdentityFoundationStorageFailure.Conflict); + } + catch (Exception failure) when (failure is DbUpdateException or DbException or TimeoutException) + { + unit.MarkRollbackOnly(); + throw new IdentityStorageProviderException(); + } + catch + { + unit.MarkRollbackOnly(); + throw; + } + finally { db.Database.AutoSavepointsEnabled = savepoints; } + } + + public async Task ValidateGraphAsync(CancellationToken cancellationToken) + { + if (_validated || !unit.HasActiveTransaction || unit.Mode != TransactionMode.ReadWrite + || !unit.IsTenantContextIssuedOn(unit.Transaction)) + throw new InvalidOperationException("Identity graph validation requires its active tenant owner."); + try + { + await using var command = unit.Connection.CreateCommand(); + command.Transaction = unit.Transaction; + command.CommandText = "SET CONSTRAINTS ALL IMMEDIATE"; + command.CommandTimeout = 10; + await command.ExecuteNonQueryAsync(cancellationToken); + _validated = true; + } + catch (PostgresException failure) when (IsOwned(failure)) + { + unit.MarkRollbackOnly(); + throw Translate(failure); + } + catch (Exception failure) when (failure is DbException or TimeoutException) + { + unit.MarkRollbackOnly(); + throw new IdentityStorageProviderException(); + } + } + + // These states are translated only while saving/preflighting the owned graph, + // never at the physical COMMIT boundary whose outcome may be uncertain. + private static bool IsOwned(PostgresException failure) => failure.SqlState is "P0301" or "P0302" or "P0303" or "P0304" + or PostgresErrorCodes.LockNotAvailable or PostgresErrorCodes.SerializationFailure + or PostgresErrorCodes.DeadlockDetected or PostgresErrorCodes.QueryCanceled + || failure.SqlState is "23505" or "23514" or "23503" + && failure.ConstraintName is { } name + && (name.Contains("membership", StringComparison.Ordinal) || name.Contains("roles", StringComparison.Ordinal) + || name.Contains("role_permission_grants", StringComparison.Ordinal)); + + private IdentityFoundationStorageException Translate(PostgresException failure) + { + var reason = failure.SqlState switch + { + "P0301" => IdentityFoundationStorageFailure.Plan, + "P0302" => IdentityFoundationStorageFailure.Target, + "P0303" => IdentityFoundationStorageFailure.Invariant, + "P0304" or "23514" or "23503" => IdentityFoundationStorageFailure.Graph, + _ => IdentityFoundationStorageFailure.Conflict, + }; + if (reason == IdentityFoundationStorageFailure.Plan && !_reportedPlanFault) + { + IdentityLockObservation.PlanFault(failure.ConstraintName == "identity_user_fence" ? IdentityLockKind.User : IdentityLockKind.Tenant); + _reportedPlanFault = true; + } + return new IdentityFoundationStorageException(reason); + } +} + +public sealed class RoleWriteStore(IdentityDbContext db, ContextualIdentityStorageControl control) : IRoleWriteStore +{ + public async Task FindAsync(RoleId roleId, CancellationToken cancellationToken = default) + { + control.PrepareFreshRead(); + return await ContextualIdentityStorageControl.ReadAsync(() => db.Roles.Include(role => role.Grants) + .SingleOrDefaultAsync(role => role.Id == roleId, cancellationToken)); + } + + public Task HasMembershipHistoryAsync(CancellationToken cancellationToken = default) => + ContextualIdentityStorageControl.ReadAsync(() => db.Memberships.AnyAsync(cancellationToken)); + public Task ValidateGraphAsync(CancellationToken cancellationToken = default) => control.ValidateGraphAsync(cancellationToken); + public Task AddAsync(Role aggregate, CancellationToken cancellationToken = default) + { + db.Roles.Add(aggregate); + return control.SaveAsync(cancellationToken); + } + public Task UpdateAsync(Role aggregate, CancellationToken cancellationToken = default) + { + WriteStoreTracking.EnsureTracked(db, aggregate); + return control.SaveAsync(cancellationToken); + } +} + +public sealed class MembershipWriteStore(IdentityDbContext db, ContextualIdentityStorageControl control) : IMembershipWriteStore +{ + public async Task FindAsync(MembershipId membershipId, CancellationToken cancellationToken = default) + { + control.PrepareFreshRead(); + return await ContextualIdentityStorageControl.ReadAsync(() => db.Memberships.Include(member => member.Profile) + .Include(member => member.RoleAssignments).SingleOrDefaultAsync(member => member.Id == membershipId, cancellationToken)); + } + + public Task HasMembershipHistoryAsync(CancellationToken cancellationToken = default) => + ContextualIdentityStorageControl.ReadAsync(() => db.Memberships.AnyAsync(cancellationToken)); + public Task ValidateGraphAsync(CancellationToken cancellationToken = default) => control.ValidateGraphAsync(cancellationToken); + public Task AddAsync(Membership aggregate, CancellationToken cancellationToken = default) + { + db.Memberships.Add(aggregate); + return control.SaveAsync(cancellationToken); + } + public Task UpdateAsync(Membership aggregate, CancellationToken cancellationToken = default) + { + WriteStoreTracking.EnsureTracked(db, aggregate); + return control.SaveAsync(cancellationToken); + } +} + +public sealed class SeedStateReader(IdentityDbContext db) : ISeedStateReader +{ + public async Task ReadRoleAsync(RoleId roleId, CancellationToken cancellationToken = default) + { + var role = await ContextualIdentityStorageControl.ReadAsync(() => db.Roles.AsNoTracking().Include(role => role.Grants) + .SingleOrDefaultAsync(role => role.Id == roleId, cancellationToken)); + return role is null ? null : new(role.Id.Value, role.TenantId, role.BuiltInKey, role.PermissionScope, + role.Version, role.DeletedAt, role.DeletedBy, + role.Grants.Select(grant => new PermissionDefinition(grant.PermissionScope, grant.PermissionKey)).ToImmutableArray()); + } + + public async Task ReadMembershipAsync(MembershipId membershipId, CancellationToken cancellationToken = default) + { + var member = await ContextualIdentityStorageControl.ReadAsync(() => db.Memberships.AsNoTracking() + .Include(member => member.Profile).Include(member => member.RoleAssignments) + .SingleOrDefaultAsync(member => member.Id == membershipId, cancellationToken)); + return member is null ? null : new(member.Id.Value, member.TenantId, member.OrganizationId, member.UserId, + member.Status.ToString(), member.Version, member.DeletedAt, member.DeletedBy, + member.Profile.DisplayName, member.Profile.PreferredLocale, + member.RoleAssignments.Select(assignment => assignment.RoleId.Value).ToImmutableArray()); + } +} + +public sealed class RoleReadStore(IdentityDbContext db) : IRoleReadStore +{ + public Task ReadAsync(RoleId roleId, CancellationToken cancellationToken = default) => + ContextualIdentityStorageControl.ReadAsync(() => db.Roles.AsNoTracking().Include(role => role.Grants) + .SingleOrDefaultAsync(role => role.Id == roleId, cancellationToken)); +} 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 new file mode 100644 index 000000000..9cdd59b9b --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityDbContext.cs @@ -0,0 +1,62 @@ +using LearnStack.Infrastructure.DataProtection; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +/// One Identity model/chain for global bindings and later contextual membership. +public sealed class IdentityDbContext(DbContextOptions options, + ITenantContextAccessor tenantContext, IGlobalIdentityScopeAccessor identityScope) + : TenantScopedDbContext(options, tenantContext) +{ + public DbSet Users => Set(); + public DbSet IdentityAuthorities => Set(); + public DbSet Memberships => Set(); + public DbSet MembershipProfiles => Set(); + public DbSet MembershipRoleAssignments => Set(); + public DbSet Roles => Set(); + public DbSet RolePermissionGrants => Set(); + + public IdentityAuthorityId CurrentIdentityAuthorityId => identityScope.Current is { } current + && current.Generation > 0 + && current.Descriptor.ContextType == typeof(IdentityDbContext) + && current.Descriptor.EntityType == typeof(User) + ? current.Descriptor.Subject.AuthorityId : IdentityAuthorityId.From(Guid.Empty); + + public IdentitySubjectKey CurrentIdentitySubjectKey => identityScope.Current is { } current + && current.Generation > 0 + && current.Descriptor.ContextType == typeof(IdentityDbContext) + && current.Descriptor.EntityType == typeof(User) + ? current.Descriptor.Subject.SubjectKey : IdentitySubjectKey.FromBytes(new byte[32]); + + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + base.OnConfiguring(optionsBuilder); + // EF reports the original provider payload before the Identity adapter + // can translate it. Replace only this context's save/query-failure events; + // ordinary command diagnostics and other module contexts stay enabled. + optionsBuilder.ConfigureWarnings(warnings => warnings.Ignore(CoreEventId.SaveChangesFailed, CoreEventId.QueryIterationFailed)); + optionsBuilder.AddInterceptors(IdentityStorageDiagnostics.Instance, new IdentityStorageTraceInterceptor()); + } + + protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) + { + base.ConfigureConventions(configurationBuilder); + configurationBuilder.UsePersonalDataClassification(); + } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + ArgumentNullException.ThrowIfNull(modelBuilder); + modelBuilder.ApplyConfigurationsFromAssembly(typeof(IdentityDbContext).Assembly); + base.OnModelCreating(modelBuilder); + modelBuilder.Entity().HasQueryFilter(user => user.AuthorityId == CurrentIdentityAuthorityId + && user.SubjectKey == CurrentIdentitySubjectKey); + modelBuilder.ApplySnakeCaseNames(); + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityDbContextFactory.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityDbContextFactory.cs new file mode 100644 index 000000000..c82675424 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityDbContextFactory.cs @@ -0,0 +1,29 @@ +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Design; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +public sealed class IdentityDbContextFactory : IDesignTimeDbContextFactory +{ + public const string HistoryTable = "__ef_migrations_history_identity"; + + public IdentityDbContext CreateDbContext(string[] args) + { + var connection = Environment.GetEnvironmentVariable("ConnectionStrings__Migration"); + if (string.IsNullOrWhiteSpace(connection)) + throw new InvalidOperationException("ConnectionStrings__Migration is required for Identity migrations."); + return new IdentityDbContext(new DbContextOptionsBuilder() + .UseNpgsql(connection, provider => provider.MigrationsHistoryTable(HistoryTable)).Options, + StaticTenantContextAccessor.Unresolved, EmptyIdentityScope.Instance); + } +} + +/// Design/model inspection supplies no verified subject or runtime authority. +public sealed class EmptyIdentityScope : IGlobalIdentityScopeAccessor +{ + public static EmptyIdentityScope Instance { get; } = new(); + private EmptyIdentityScope() { } + public GlobalIdentityContextAnnouncement? Current => null; +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityStorageDdl.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityStorageDdl.cs new file mode 100644 index 000000000..b047e3518 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityStorageDdl.cs @@ -0,0 +1,55 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +/// Exact Identity-owned storage guards; global audit installation has its separate central owner. +internal static class IdentityStorageDdl +{ + internal static void Install(MigrationBuilder migrationBuilder) => migrationBuilder.Sql(""" + ALTER TABLE public.identity_authority ENABLE ROW LEVEL SECURITY; + ALTER TABLE public.identity_authority FORCE ROW LEVEL SECURITY; + CREATE POLICY identity_authority_read ON public.identity_authority FOR SELECT + USING (current_user IN ('learnstack_app','learnstack_migration')); + CREATE POLICY identity_authority_install ON public.identity_authority FOR INSERT + WITH CHECK (current_user='learnstack_migration' AND id=1); + REVOKE ALL ON public.identity_authority FROM PUBLIC,learnstack_app,learnstack_platform,learnstack_outbox_admin; + GRANT SELECT ON public.identity_authority TO learnstack_app; + + ALTER TABLE public.users ENABLE ROW LEVEL SECURITY; + ALTER TABLE public.users FORCE ROW LEVEL SECURITY; + CREATE POLICY users_isolation ON public.users + USING ((current_user='learnstack_app' + AND authority_id::text=NULLIF(current_setting('app.identity_authority_id',true),'') + AND encode(subject_key,'hex')=NULLIF(current_setting('app.identity_subject_key',true),'')) + OR current_user='learnstack_migration') + WITH CHECK (current_user='learnstack_app' + AND authority_id::text=NULLIF(current_setting('app.identity_authority_id',true),'') + AND encode(subject_key,'hex')=NULLIF(current_setting('app.identity_subject_key',true),'') + AND status='Active' AND provider_subject IS NOT NULL + AND deleted_at IS NULL AND deleted_by IS NULL); + REVOKE ALL ON public.users FROM PUBLIC,learnstack_app,learnstack_platform,learnstack_outbox_admin; + GRANT SELECT ON public.users TO learnstack_app; + GRANT INSERT (id,authority_id,subject_key,provider_subject,status,creation_audit_id, + creation_audit_timestamp,created_at,created_by,row_version) ON public.users TO learnstack_app; + + CREATE FUNCTION public.fn_identity_user_immutable() RETURNS trigger + LANGUAGE plpgsql SECURITY INVOKER SET search_path=pg_catalog AS $$ + BEGIN + RAISE EXCEPTION 'Identity bindings have no admitted update or removal owner.' USING ERRCODE='23514'; + END $$; + REVOKE ALL ON FUNCTION public.fn_identity_user_immutable() FROM PUBLIC; + CREATE TRIGGER tg_users_no_update BEFORE UPDATE ON public.users + FOR EACH ROW EXECUTE FUNCTION public.fn_identity_user_immutable(); + CREATE TRIGGER tg_users_no_delete BEFORE DELETE ON public.users + FOR EACH ROW EXECUTE FUNCTION public.fn_identity_user_immutable(); + CREATE TRIGGER tg_users_no_truncate BEFORE TRUNCATE ON public.users + FOR EACH STATEMENT EXECUTE FUNCTION public.fn_identity_user_immutable(); + """); + + internal static void Remove(MigrationBuilder migrationBuilder) => migrationBuilder.Sql(""" + DROP TRIGGER IF EXISTS tg_users_no_update ON public.users; + DROP TRIGGER IF EXISTS tg_users_no_delete ON public.users; + DROP TRIGGER IF EXISTS tg_users_no_truncate ON public.users; + DROP FUNCTION IF EXISTS public.fn_identity_user_immutable(); + """); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityStorageDiagnostics.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityStorageDiagnostics.cs new file mode 100644 index 000000000..0d31d0014 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/IdentityStorageDiagnostics.cs @@ -0,0 +1,114 @@ +using System.Data.Common; +using System.Diagnostics; +using LearnStack.SharedKernel.Errors; +using Microsoft.EntityFrameworkCore.Diagnostics; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.Logging; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +/// Unexpected database failures retain a fixed operational signal, never a provider payload. +public sealed class IdentityStorageProviderException() + : ProviderException("identity-storage", "Identity storage operation failed.", isClientError: false); + +/// Source-owned, nonexported classification of Identity's actual EF command spans. +public static class IdentityStorageTraceBoundary +{ + private const string MarkerKey = "LearnStack.Identity.StorageCommand"; + private static readonly object Marker = new(); + private const string EfSource = "OpenTelemetry.Instrumentation.EntityFrameworkCore"; + + internal static void MarkCreatedCommand(Activity? current, Activity? caller) + { + // Multiple tracing compositions create nested EF spans for one command. + // First validate the entire creation interval against its exact caller; + // an existing EF caller belongs to another command and must stay untouched. + for (var activity = current; !ReferenceEquals(activity, caller); activity = activity.Parent) + if (activity is null || activity.Source.Name != EfSource) return; + + for (var activity = current; !ReferenceEquals(activity, caller); activity = activity!.Parent) + activity!.SetCustomProperty(MarkerKey, Marker); + } + + /// The pinned EF instrumentation ends a failed span before the adapter can translate its exception. + public static void ApplyBeforeExport(Activity activity) + { + ArgumentNullException.ThrowIfNull(activity); + if (activity.Source.Name == EfSource && ReferenceEquals(activity.GetCustomProperty(MarkerKey), Marker) + && activity.Status == ActivityStatusCode.Error) + activity.SetStatus(ActivityStatusCode.Error, "Identity storage command failed."); + } +} + +internal sealed class IdentityStorageTraceInterceptor : DbCommandInterceptor +{ + private (Guid CommandId, Activity? Caller)? _creation; + + public override InterceptionResult CommandCreating(CommandCorrelatedEventData eventData, + InterceptionResult result) + { + _creation = eventData.Context is IdentityDbContext ? (eventData.CommandId, Activity.Current) : null; + return result; + } + + public override DbCommand CommandCreated(CommandEndEventData eventData, DbCommand result) + { + var creation = _creation; + _creation = null; + // EF 10 creates commands synchronously in both execution modes. Its + // CommandCreated broadcast starts all instrumentation spans before this + // hook; the per-context state brackets only this matching command. + if (eventData.Context is IdentityDbContext && creation is { } started + && started.CommandId == eventData.CommandId) + IdentityStorageTraceBoundary.MarkCreatedCommand(Activity.Current, started.Caller); + return result; + } + + public override void CommandFailed(DbCommand command, CommandErrorEventData eventData) => + IdentityStorageDiagnostics.ReportReadFailure(eventData); + + public override Task CommandFailedAsync(DbCommand command, CommandErrorEventData eventData, + CancellationToken cancellationToken = default) + { + IdentityStorageDiagnostics.ReportReadFailure(eventData); + return Task.CompletedTask; + } +} + +/// Replaces Identity's pre-adapter EF failure messages under ADR-0073 G19. +internal sealed class IdentityStorageDiagnostics : SaveChangesInterceptor +{ + internal static readonly IdentityStorageDiagnostics Instance = new(); + + public override void SaveChangesFailed(DbContextErrorEventData eventData) => Report(eventData); + + public override Task SaveChangesFailedAsync(DbContextErrorEventData eventData, + CancellationToken cancellationToken = default) + { + Report(eventData); + return Task.CompletedTask; + } + + private static void Report(DbContextErrorEventData eventData) + { + if (eventData.Context is { } context) + LogSaveFailed(context.GetService().CreateLogger(), null); + } + + internal static void ReportReadFailure(CommandErrorEventData eventData) + { + // Classify the EF source, not SQL text. All Identity query adapters keep + // an operational signal; existing provider/refusal/cancellation handling + // receives the original exception unchanged and remains its sole owner. + if (eventData.Context is IdentityDbContext context + && eventData.CommandSource is CommandSource.LinqQuery or CommandSource.FromSqlQuery + && eventData.Exception is not OperationCanceledException) + LogReadFailed(context.GetService().CreateLogger(), null); + } + + private static readonly Action LogSaveFailed = LoggerMessage.Define( + LogLevel.Error, new EventId(3191, "IdentityStorageSaveFailed"), "Identity storage save failed."); + + private static readonly Action LogReadFailed = LoggerMessage.Define( + LogLevel.Error, new EventId(3192, "IdentityStorageReadFailed"), "Identity storage read failed."); +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261025201338_create_identity_schema.Designer.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261025201338_create_identity_schema.Designer.cs new file mode 100644 index 000000000..d8e4f002b --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261025201338_create_identity_schema.Designer.cs @@ -0,0 +1,193 @@ +// +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("20261025201338_create_identity_schema")] + partial class create_identity_schema + { + /// + 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.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.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.User", b => + { + b.HasOne("LearnStack.Modules.Identity.Domain.IdentityAuthority", null) + .WithMany() + .HasForeignKey("AuthorityId") + .HasPrincipalKey("AuthorityId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("fk_users_identity_authority"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261025201338_create_identity_schema.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261025201338_create_identity_schema.cs new file mode 100644 index 000000000..03284cb47 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261025201338_create_identity_schema.cs @@ -0,0 +1,91 @@ +using System; +using LearnStack.Infrastructure.Audit; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations +{ + /// + public partial class create_identity_schema : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "identity_authority", + columns: table => new + { + id = table.Column(type: "integer", nullable: false), + authority_id = table.Column(type: "uuid", nullable: false), + issuer = table.Column(type: "character varying(2048)", maxLength: 2048, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("pk_identity_authority", x => x.id); + table.UniqueConstraint("ux_identity_authority_authority_id", x => x.authority_id); + table.CheckConstraint("ck_identity_authority_assigned", "authority_id <> '00000000-0000-0000-0000-000000000000'::uuid"); + table.CheckConstraint("ck_identity_authority_singleton", "id = 1"); + }); + + migrationBuilder.CreateTable( + name: "users", + columns: table => new + { + id = table.Column(type: "uuid", nullable: false), + authority_id = table.Column(type: "uuid", nullable: false), + subject_key = table.Column(type: "bytea", nullable: false), + provider_subject = table.Column(type: "character varying(255)", maxLength: 255, nullable: true), + status = table.Column(type: "text", nullable: false), + creation_audit_id = table.Column(type: "uuid", nullable: false), + creation_audit_timestamp = table.Column(type: "timestamp with time zone", nullable: false), + 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_users", x => x.id); + table.CheckConstraint("ck_users_actor", "uuid_extract_version(id) = 7 AND id <> '00000000-0000-7000-8000-000000000001'::uuid"); + table.CheckConstraint("ck_users_no_soft_delete", "deleted_at IS NULL AND deleted_by IS NULL"); + table.CheckConstraint("ck_users_status", "status IN ('Active', 'Closing', 'Closed')"); + table.CheckConstraint("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'))"); + table.CheckConstraint("ck_users_subject_key", "octet_length(subject_key) = 32"); + table.CheckConstraint("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)"); + table.ForeignKey( + name: "fk_users_identity_authority", + column: x => x.authority_id, + principalTable: "identity_authority", + principalColumn: "authority_id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateIndex( + name: "ux_users_authority_id_subject_key", + table: "users", + columns: new[] { "authority_id", "subject_key" }, + unique: true); + + IdentityStorageDdl.Install(migrationBuilder); + IdentityCreationWitnessInstaller.Install(migrationBuilder); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + // Disposable-schema reversal only. Live recovery is forward-only; + // this is not an admitted binding-retirement operation. + IdentityCreationWitnessInstaller.Remove(migrationBuilder); + IdentityStorageDdl.Remove(migrationBuilder); + migrationBuilder.DropTable( + name: "users"); + + migrationBuilder.DropTable( + name: "identity_authority"); + } + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261025232309_add_contextual_identity.Designer.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261025232309_add_contextual_identity.Designer.cs new file mode 100644 index 000000000..e04f0b455 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261025232309_add_contextual_identity.Designer.cs @@ -0,0 +1,567 @@ +// +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("20261025232309_add_contextual_identity")] + partial class add_contextual_identity + { + /// + 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.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.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("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("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", (string)null); + }); + + 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.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("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.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/20261025232309_add_contextual_identity.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261025232309_add_contextual_identity.cs new file mode 100644 index 000000000..02b3ca94d --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261025232309_add_contextual_identity.cs @@ -0,0 +1,197 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations +{ + /// + public partial class add_contextual_identity : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "memberships", + 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), + user_id = table.Column(type: "uuid", nullable: false), + status = table.Column(type: "text", nullable: false), + 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_memberships", x => x.id); + table.UniqueConstraint("ux_memberships_tenant_id_id", x => new { x.tenant_id, x.id }); + table.CheckConstraint("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)"); + table.CheckConstraint("ck_memberships_status", "status IN ('Active','Suspended','Revoked')"); + table.ForeignKey( + name: "fk_memberships_user", + column: x => x.user_id, + principalTable: "users", + principalColumn: "id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateTable( + name: "roles", + columns: table => new + { + id = table.Column(type: "uuid", nullable: false), + tenant_id = table.Column(type: "uuid", nullable: false), + built_in_key = table.Column(type: "text", nullable: false), + permission_scope = table.Column(type: "text", nullable: false), + 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_roles", x => x.id); + table.UniqueConstraint("ux_roles_tenant_id_id", x => new { x.tenant_id, x.id }); + }); + + migrationBuilder.CreateTable( + name: "membership_profiles", + columns: table => new + { + tenant_id = table.Column(type: "uuid", nullable: false), + membership_id = table.Column(type: "uuid", nullable: false), + organization_id = table.Column(type: "uuid", nullable: true), + display_name = table.Column(type: "character varying(128)", maxLength: 128, nullable: true), + preferred_locale = table.Column(type: "character varying(35)", maxLength: 35, nullable: true) + }, + constraints: table => + { + table.PrimaryKey("pk_membership_profiles", x => new { x.tenant_id, x.membership_id }); + table.ForeignKey( + name: "fk_membership_profiles_membership", + columns: x => new { x.tenant_id, x.membership_id }, + principalTable: "memberships", + principalColumns: new[] { "tenant_id", "id" }, + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateTable( + name: "membership_role_assignments", + columns: table => new + { + tenant_id = table.Column(type: "uuid", nullable: false), + membership_id = table.Column(type: "uuid", nullable: false), + role_id = table.Column(type: "uuid", nullable: false), + organization_id = table.Column(type: "uuid", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("pk_membership_role_assignments", x => new { x.tenant_id, x.membership_id, x.role_id }); + table.ForeignKey( + name: "fk_membership_role_assignments_membership", + columns: x => new { x.tenant_id, x.membership_id }, + principalTable: "memberships", + principalColumns: new[] { "tenant_id", "id" }, + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "fk_membership_role_assignments_role", + columns: x => new { x.tenant_id, x.role_id }, + principalTable: "roles", + principalColumns: new[] { "tenant_id", "id" }, + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateTable( + name: "role_permission_grants", + columns: table => new + { + tenant_id = table.Column(type: "uuid", nullable: false), + role_id = table.Column(type: "uuid", nullable: false), + permission_scope = table.Column(type: "text", nullable: false), + permission_key = table.Column(type: "character varying(128)", maxLength: 128, nullable: false) + }, + constraints: table => + { + table.PrimaryKey("pk_role_permission_grants", x => new { x.tenant_id, x.role_id, x.permission_scope, x.permission_key }); + table.ForeignKey( + name: "fk_role_permission_grants_role", + columns: x => new { x.tenant_id, x.role_id }, + principalTable: "roles", + principalColumns: new[] { "tenant_id", "id" }, + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateIndex( + name: "ix_membership_profiles_tenant_id_organization_id", + table: "membership_profiles", + columns: new[] { "tenant_id", "organization_id" }); + + migrationBuilder.CreateIndex( + name: "ix_membership_role_assignments_tenant_id_organization_id", + table: "membership_role_assignments", + columns: new[] { "tenant_id", "organization_id" }); + + migrationBuilder.CreateIndex( + name: "ix_membership_role_assignments_tenant_id_role_id", + table: "membership_role_assignments", + columns: new[] { "tenant_id", "role_id" }); + + migrationBuilder.CreateIndex( + name: "ix_memberships_tenant_id_organization_id", + table: "memberships", + columns: new[] { "tenant_id", "organization_id" }); + + migrationBuilder.CreateIndex( + name: "ix_memberships_user_id", + table: "memberships", + column: "user_id"); + + migrationBuilder.CreateIndex( + name: "ux_memberships_current_scope", + table: "memberships", + columns: new[] { "tenant_id", "user_id", "organization_id" }, + unique: true, + filter: "deleted_at IS NULL") + .Annotation("Npgsql:NullsDistinct", false); + + migrationBuilder.CreateIndex( + name: "ux_roles_current_builtin_scope", + table: "roles", + columns: new[] { "tenant_id", "permission_scope", "built_in_key" }, + unique: true, + filter: "deleted_at IS NULL"); + + ContextualIdentityStorageDdl.Install(migrationBuilder); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + ContextualIdentityStorageDdl.Remove(migrationBuilder); + migrationBuilder.DropTable( + name: "membership_profiles"); + + migrationBuilder.DropTable( + name: "membership_role_assignments"); + + migrationBuilder.DropTable( + name: "role_permission_grants"); + + migrationBuilder.DropTable( + name: "memberships"); + + migrationBuilder.DropTable( + name: "roles"); + } + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261026035353_correct_identity_parent_mirror_sqlstate.Designer.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261026035353_correct_identity_parent_mirror_sqlstate.Designer.cs new file mode 100644 index 000000000..12d611f76 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261026035353_correct_identity_parent_mirror_sqlstate.Designer.cs @@ -0,0 +1,567 @@ +// +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("20261026035353_correct_identity_parent_mirror_sqlstate")] + partial class correct_identity_parent_mirror_sqlstate + { + /// + 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.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.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("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("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", (string)null); + }); + + 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.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("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.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/20261026035353_correct_identity_parent_mirror_sqlstate.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261026035353_correct_identity_parent_mirror_sqlstate.cs new file mode 100644 index 000000000..86ecd21c0 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261026035353_correct_identity_parent_mirror_sqlstate.cs @@ -0,0 +1,24 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations +{ + /// + public partial class correct_identity_parent_mirror_sqlstate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + // Preserve the applied schema and function permissions while aligning + // only missing/mismatched Membership parent scope with Standards 05. + ContextualIdentityStorageDdl.CorrectParentMirrorSqlState(migrationBuilder); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + ContextualIdentityStorageDdl.RestoreLegacyParentMirrorSqlState(migrationBuilder); + } + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261026043921_correct_identity_admission_parent_sqlstate.Designer.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261026043921_correct_identity_admission_parent_sqlstate.Designer.cs new file mode 100644 index 000000000..abb0c8a9a --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261026043921_correct_identity_admission_parent_sqlstate.Designer.cs @@ -0,0 +1,567 @@ +// +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("20261026043921_correct_identity_admission_parent_sqlstate")] + partial class correct_identity_admission_parent_sqlstate + { + /// + 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.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.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("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("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", (string)null); + }); + + 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.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("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.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/20261026043921_correct_identity_admission_parent_sqlstate.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261026043921_correct_identity_admission_parent_sqlstate.cs new file mode 100644 index 000000000..cdc41eb9e --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261026043921_correct_identity_admission_parent_sqlstate.cs @@ -0,0 +1,24 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations +{ + /// + public partial class correct_identity_admission_parent_sqlstate : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + // The admission trigger runs before the mutation guard for assignment + // inserts. Keep its missing/hidden parent refusal identical to that guard. + ContextualIdentityStorageDdl.CorrectAdmissionParentMirrorSqlState(migrationBuilder); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + ContextualIdentityStorageDdl.RestoreLegacyAdmissionParentMirrorSqlState(migrationBuilder); + } + } +} diff --git a/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261026102944_serialize_identity_parent_lifecycle.Designer.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261026102944_serialize_identity_parent_lifecycle.Designer.cs new file mode 100644 index 000000000..faec3f5c9 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261026102944_serialize_identity_parent_lifecycle.Designer.cs @@ -0,0 +1,567 @@ +// +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("20261026102944_serialize_identity_parent_lifecycle")] + partial class serialize_identity_parent_lifecycle + { + /// + 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.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.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("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("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", (string)null); + }); + + 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.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("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.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/20261026102944_serialize_identity_parent_lifecycle.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261026102944_serialize_identity_parent_lifecycle.cs new file mode 100644 index 000000000..0e3e7780e --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/20261026102944_serialize_identity_parent_lifecycle.cs @@ -0,0 +1,22 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations +{ + /// + public partial class serialize_identity_parent_lifecycle : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + ContextualIdentityStorageDdl.SerializeParentLifecycle(migrationBuilder); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + ContextualIdentityStorageDdl.RestoreLegacyParentLifecycleLock(migrationBuilder); + } + } +} 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 new file mode 100644 index 000000000..0ee204b88 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/Migrations/IdentityDbContextModelSnapshot.cs @@ -0,0 +1,564 @@ +// +using System; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.DataProtection; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations +{ + [DbContext(typeof(IdentityDbContext))] + partial class IdentityDbContextModelSnapshot : ModelSnapshot + { + 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); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + 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.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("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("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", (string)null); + }); + + 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.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("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.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/UserBindingStore.cs b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/UserBindingStore.cs new file mode 100644 index 000000000..160250140 --- /dev/null +++ b/backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure/Persistence/UserBindingStore.cs @@ -0,0 +1,53 @@ +using LearnStack.Modules.Identity.Application.Abstractions; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Persistence; +using Microsoft.EntityFrameworkCore; +using Npgsql; + +namespace LearnStack.Modules.Identity.Infrastructure.Persistence; + +public sealed class UserBindingStore(IdentityDbContext context, IGlobalIdentityUnitOfWork unit) : IUserBindingStore +{ + public async Task FindExactAsync(GlobalIdentitySubject subject, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(subject); + EnrollCurrentOwner(); + try + { + return await context.Users.AsNoTracking().SingleOrDefaultAsync(user => + user.AuthorityId == subject.AuthorityId && user.SubjectKey == subject.SubjectKey, cancellationToken); + } + catch (InvalidOperationException failure) when (failure.InnerException is NpgsqlException { IsTransient: true } or TimeoutException) + { + throw new UserBindingStorageException(); + } + } + + public async Task AddAsync(User user, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(user); + try + { + context.Users.Add(user); + await context.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateException) + { + throw new UserBindingStorageException(); + } + catch (InvalidOperationException failure) when ( + failure.InnerException is DbUpdateException { InnerException: NpgsqlException { IsTransient: true } or TimeoutException }) + { + throw new UserBindingStorageException(); + } + } + + private void EnrollCurrentOwner() + { + var announcement = unit.GetGlobalIdentityAnnouncement(unit.Transaction) + ?? throw new InvalidOperationException("The binding store requires its current global identity owner."); + unit.EnrollGlobalIdentityContext(context, announcement.Descriptor); + context.Database.UseTransaction(unit.Transaction); + } +} 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 new file mode 100644 index 000000000..49153aba7 --- /dev/null +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Application.Contracts/IdentityLifecycle/IIdentityScopeLifecycleReader.cs @@ -0,0 +1,16 @@ +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.Modules.Tenancy.Application.Contracts.IdentityLifecycle; + +/// Four fresh lifecycle facts for the current trusted announced scope; no row or directory projection. +public sealed record IdentityScopeLifecycle( + bool TenantExistsAndNotDeleted, + bool TenantAllowsOrdinaryWork, + bool OrganizationBelongsToTenant, + bool OrganizationAllowsOrdinaryWork); + +public interface IIdentityScopeLifecycleReader +{ + Task ReadAsync(TenantId tenantId, OrganizationId? organizationId, + CancellationToken cancellationToken = default); +} diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/Configurations.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/Configurations.cs index c1cb25616..3225c2876 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/Configurations.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/Configurations.cs @@ -1,5 +1,7 @@ +using LearnStack.Infrastructure.DataProtection; using LearnStack.Infrastructure.Persistence; using LearnStack.Modules.Tenancy.Domain; +using LearnStack.SharedKernel.DataProtection; using LearnStack.SharedKernel.Identifiers; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; @@ -31,6 +33,10 @@ public void Configure(EntityTypeBuilder builder) builder.HasIndex(x => x.Slug).IsUnique().HasDatabaseName("ux_tenants_slug"); builder.MapAuditColumns(); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Institution registration, public naming, lifecycle and default branch routing.", + nameof(Tenant.Id), nameof(Tenant.Slug), nameof(Tenant.DisplayName), + nameof(Tenant.Status), nameof(Tenant.DefaultOrganizationId)); // The containment the aggregate boundary decides, expressed for EF — and NOT as // owned types. An owned mapping looks like the natural way to say "part of the @@ -113,6 +119,11 @@ public void Configure(EntityTypeBuilder builder) .HasDatabaseName("ix_organizations_tenant_id_reporting_parent_id"); builder.MapAuditColumns(); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Institution branch identity, public naming, lifecycle and reporting structure.", + nameof(Organization.Id), nameof(Organization.TenantId), nameof(Organization.Slug), + nameof(Organization.DisplayName), nameof(Organization.CustomSubdomain), + nameof(Organization.Status), nameof(Organization.ReportingParentId)); } } @@ -156,6 +167,14 @@ public void Configure(EntityTypeBuilder builder) builder.HasIndex(x => x.TenantId).HasDatabaseName("ix_tenant_domains_tenant_id"); builder.MapAuditColumns(); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Institution domain ownership and verification state, rather than a person's address.", + nameof(TenantDomain.Id), nameof(TenantDomain.TenantId), nameof(TenantDomain.Host), + nameof(TenantDomain.Kind), nameof(TenantDomain.Status), nameof(TenantDomain.VerifiedAt), + nameof(TenantDomain.VerificationAttempts)); + builder.DeclarePersonalData(PersonalDataCategory.Identity, + "Retained free-text verification diagnostics may contain operator or contact identifiers.", + nameof(TenantDomain.LastVerificationError)); } } @@ -192,6 +211,10 @@ public void Configure(EntityTypeBuilder builder) .IsUnique() .HasFilter("is_default") .HasDatabaseName("ux_tenant_locales_tenant_id_is_default"); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Institution publication languages, enabled state and language-switcher ordering.", + nameof(TenantLocale.TenantId), nameof(TenantLocale.Locale), nameof(TenantLocale.IsDefault), + nameof(TenantLocale.IsEnabled), nameof(TenantLocale.Sort)); } } @@ -232,6 +255,13 @@ public void Configure(EntityTypeBuilder builder) .HasDatabaseName("ix_tenant_settings_tenant_id_organization_id"); builder.MapAuditColumns(); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Institution and branch configuration addressing; the payload is classified separately.", + nameof(TenantSetting.Id), nameof(TenantSetting.TenantId), + nameof(TenantSetting.OrganizationId), nameof(TenantSetting.Key)); + builder.DeclarePersonalData(PersonalDataCategory.Identity, + "Generic configuration JSON may contain contact or other person-identifying values.", + nameof(TenantSetting.Value)); } } @@ -256,6 +286,16 @@ public void Configure(EntityTypeBuilder builder) builder.Property(x => x.UpdatedBy) .HasConversion() .IsRequired(); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Institution capability overrides: declared feature key and rollout value.", + nameof(TenantFeatureFlag.TenantId), nameof(TenantFeatureFlag.Key), + nameof(TenantFeatureFlag.Value)); + builder.DeclarePersonalData(PersonalDataCategory.Identity, + "Actor attribution for the latest institution feature-flag change.", + nameof(TenantFeatureFlag.UpdatedBy)); + builder.DeclarePersonalData(PersonalDataCategory.Audit, + "Timestamp of the attributed institution feature-flag change.", + nameof(TenantFeatureFlag.UpdatedAt)); } } @@ -288,6 +328,13 @@ public void Configure(EntityTypeBuilder builder) // Closed set, so text + CHECK rather than a length cap. builder.Property(x => x.Source).HasColumnType("text").IsRequired(); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Institution plan capabilities, numeric limits, compliance settings and projection freshness.", + nameof(PlatformEntitlement.TenantId), nameof(PlatformEntitlement.PlanCode), + nameof(PlatformEntitlement.Features), nameof(PlatformEntitlement.Limits), + nameof(PlatformEntitlement.Compliance), nameof(PlatformEntitlement.ValidUntil), + nameof(PlatformEntitlement.GraceUntil), nameof(PlatformEntitlement.Generation), + nameof(PlatformEntitlement.RefreshedAt), nameof(PlatformEntitlement.Source)); } } @@ -311,6 +358,15 @@ public void Configure(EntityTypeBuilder builder) // No conversion and no foreign key: see PlatformKillswitch.ToggledBy. builder.Property(x => x.ToggledBy); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Deployment-wide capability key and enabled state, with no subject or tenant value.", + nameof(PlatformKillswitch.Key), nameof(PlatformKillswitch.IsEnabled)); + builder.DeclarePersonalData(PersonalDataCategory.Identity, + "Operator attribution and free-text explanation of a deployment-wide capability change.", + nameof(PlatformKillswitch.ToggledBy), nameof(PlatformKillswitch.Reason)); + builder.DeclarePersonalData(PersonalDataCategory.Audit, + "Timestamp of the attributed deployment-wide capability change.", + nameof(PlatformKillswitch.ToggledAt)); } } @@ -345,5 +401,10 @@ public void Configure(EntityTypeBuilder builder) // RESTRICT scan, it just narrows it to the tenant. builder.HasIndex(x => new { x.TenantId, x.OrganizationId }) .HasDatabaseName("ix_platform_host_to_tenant_tenant_id_organization_id"); + builder.DeclarePersonalData(PersonalDataCategory.None, + "Institution host-to-branch routing and public serving eligibility.", + nameof(PlatformHostMapping.Host), nameof(PlatformHostMapping.TenantId), + nameof(PlatformHostMapping.OrganizationId), nameof(PlatformHostMapping.IsActive), + nameof(PlatformHostMapping.IsPubliclyLive)); } } 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 new file mode 100644 index 000000000..da6cdf09e --- /dev/null +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/IdentityScopeLifecycleReader.cs @@ -0,0 +1,50 @@ +using System.Data; +using LearnStack.Modules.Tenancy.Application.Contracts.IdentityLifecycle; +using LearnStack.SharedKernel.Errors; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Persistence; +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. +public sealed class IdentityScopeLifecycleReader(IUnitOfWork unit) : IIdentityScopeLifecycleReader +{ + public async Task ReadAsync(TenantId tenantId, OrganizationId? organizationId, + CancellationToken cancellationToken = default) + { + if (!tenantId.IsInitialized() || tenantId.Value == Guid.Empty || tenantId == TenantId.PlatformSentinel + || !unit.HasActiveTransaction || unit.IsRollbackOnly + || unit.Transaction is not { IsolationLevel: IsolationLevel.ReadCommitted } transaction + || unit.GetTenantContextAnnouncement(transaction) is not { Generation: > 0 } announced + || announced.TenantId != tenantId || announced.OrganizationId != organizationId) + throw new InfrastructureException("Identity scope lifecycle is unavailable."); + + try + { + await using var command = new NpgsqlCommand(""" + SELECT t.deleted_at IS NULL, + 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', + current_setting('transaction_isolation') = 'read committed' + FROM public.tenants AS t + LEFT JOIN public.organizations AS o + ON o.tenant_id = t.id AND o.id = @organization + WHERE t.id = @tenant + """, (NpgsqlConnection)unit.Connection, (NpgsqlTransaction)transaction) { CommandTimeout = 10 }; + command.Parameters.AddWithValue("tenant", tenantId.Value); + command.Parameters.AddWithValue("organization", NpgsqlDbType.Uuid, organizationId is { } org + ? org.Value : DBNull.Value); + await using var reader = await command.ExecuteReaderAsync(cancellationToken); + if (!await reader.ReadAsync(cancellationToken)) return new(false, false, false, false); + if (!reader.GetBoolean(4)) throw new InfrastructureException("Identity scope lifecycle is unavailable."); + return new(reader.GetBoolean(0), reader.GetBoolean(1), reader.GetBoolean(2), reader.GetBoolean(3)); + } + catch (NpgsqlException) + { + throw new InfrastructureException("Identity scope lifecycle is unavailable."); + } + } +} diff --git a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/TenancyDbContext.cs b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/TenancyDbContext.cs index b80a4efe7..7a559b96f 100644 --- a/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/TenancyDbContext.cs +++ b/backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/TenancyDbContext.cs @@ -1,3 +1,4 @@ +using LearnStack.Infrastructure.DataProtection; using LearnStack.Infrastructure.Persistence; using LearnStack.Modules.Tenancy.Domain; using LearnStack.SharedKernel.Tenancy; @@ -64,6 +65,12 @@ public sealed class TenancyDbContext( /// public DbSet PlatformKillswitches => Set(); + protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) + { + base.ConfigureConventions(configurationBuilder); + configurationBuilder.UsePersonalDataClassification(); + } + protected override void OnModelCreating(ModelBuilder modelBuilder) { ArgumentNullException.ThrowIfNull(modelBuilder); diff --git a/backend/tests/LearnStack.Tests.Architecture/AggregateWriteTests.cs b/backend/tests/LearnStack.Tests.Architecture/AggregateWriteTests.cs index 5e348b592..d6171d61b 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AggregateWriteTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AggregateWriteTests.cs @@ -103,6 +103,11 @@ public void Write_Port_Census_Distinguishes_Typed_Read_Keys_From_Wrapped_Domain_ TakesDomainObject(typeof(ITranslationCollisionReader), domains).Should().BeFalse(); TakesDomainObject(typeof(LearnStack.Modules.Education.Application.Abstractions.ISeedStateReader), domains).Should().BeFalse(); TakesDomainObject(typeof(IPublicEducationReadStore), domains).Should().BeFalse(); + var identityDomains = new HashSet { typeof(LearnStack.Modules.Identity.Domain.Role).Assembly }; + TakesDomainObject(typeof(LearnStack.Modules.Identity.Application.Abstractions.IRoleReadStore), identityDomains) + .Should().BeFalse("the exact untracked Role lookup is a read, not a second aggregate writer"); + TakesDomainObject(typeof(LearnStack.Modules.Identity.Application.Abstractions.ISeedStateReader), identityDomains) + .Should().BeFalse("the exact seed DTO lookups do not write their typed keys"); TakesDomainObject(typeof(IWrappedKeyReader), domains).Should().BeTrue("an unenumerated key-only port must not escape; Fix: enumerate genuine read methods explicitly"); foreach (var writer in new[] { typeof(IDirectWriter), typeof(IBulkWriter), typeof(IArrayWriter), typeof(IByRefWriter), typeof(IMixedWriter), typeof(IInheritedWriter), typeof(IIdOnlyWriteProbe), typeof(IValueReturningKeyWriter) }) { @@ -180,6 +185,9 @@ private static bool IsTypedId(Type type) => type.GetInterfaces().Any(contract => typeof(LearnStack.Modules.Tenancy.Application.Abstractions.ISeedStateReader).GetMethod("ReadSettingAsync")!, typeof(LearnStack.Modules.Customization.Application.Abstractions.ISeedStateReader).GetMethod("ReadContentTypeAsync")!, typeof(LearnStack.Modules.Customization.Application.Abstractions.ISeedStateReader).GetMethod("ReadTaxonomyAsync")!, + typeof(LearnStack.Modules.Identity.Application.Abstractions.IRoleReadStore).GetMethod("ReadAsync")!, + typeof(LearnStack.Modules.Identity.Application.Abstractions.ISeedStateReader).GetMethod("ReadRoleAsync")!, + typeof(LearnStack.Modules.Identity.Application.Abstractions.ISeedStateReader).GetMethod("ReadMembershipAsync")!, ]; private interface IIdOnlyWriteProbe { Task DeleteAsync(CourseId id); } diff --git a/backend/tests/LearnStack.Tests.Architecture/AsyncStoreInventoryDocument.cs b/backend/tests/LearnStack.Tests.Architecture/AsyncStoreInventoryDocument.cs index c8435ca87..5b3317fe4 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AsyncStoreInventoryDocument.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AsyncStoreInventoryDocument.cs @@ -46,7 +46,7 @@ internal static string[] Check(string document, IReadOnlyList rows, int expected, string label) diff --git a/backend/tests/LearnStack.Tests.Architecture/AsyncStoreInventoryTests.cs b/backend/tests/LearnStack.Tests.Architecture/AsyncStoreInventoryTests.cs index 8def17c36..3310f8547 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AsyncStoreInventoryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AsyncStoreInventoryTests.cs @@ -80,7 +80,7 @@ public void Inventory_coverage_rejects_every_removed_row_and_blank_vendor_classi { var removed = subject.Document.Replace(row + "\n", "", StringComparison.Ordinal); removed.Should().NotBe(subject.Document, "the planted control must actually remove its row"); - var reason = section == "custody" ? "audit/provider/external/volatile custody" : "complete five-chain migration census"; + var reason = section == "custody" ? "audit/provider/external/volatile custody" : "complete migration census"; Check(removed, subject.Platform, subject.Audit, subject.Modules) .Should().Contain(failure => failure.Contains(reason, StringComparison.Ordinal)); @@ -283,18 +283,12 @@ private static (string Document, MigrationOperation[] Platform, MigrationOperati .UseNpgsql("Host=unused").Options); using var audit = new AuditDbContext(new DbContextOptionsBuilder() .UseNpgsql("Host=unused").Options, new StaticTenantContextAccessor(null)); - using var tenancy = new TenancyDbContext(new DbContextOptionsBuilder() - .UseNpgsql("Host=unused").Options, StaticTenantContextAccessor.Unresolved); - using var customization = new CustomizationDbContext(new DbContextOptionsBuilder() - .UseNpgsql("Host=unused").Options, StaticTenantContextAccessor.Unresolved); - using var education = new EducationDbContext(new DbContextOptionsBuilder() - .UseNpgsql("Host=unused").Options, StaticTenantContextAccessor.Unresolved); - var modules = new Dictionary + var modules = new Dictionary(StringComparer.Ordinal); + foreach (var module in Modules.Mapped.Where(module => module.Domain != typeof(LearnStack.Modules.Audit.Domain.AuditEntry).Assembly)) { - ["Tenancy"] = AsyncStoreInventoryCensus.Operations(tenancy), - ["Customization"] = AsyncStoreInventoryCensus.Operations(customization), - ["Education"] = AsyncStoreInventoryCensus.Operations(education), - }; + using var context = module.Context(); + modules.Add(module.Domain.GetName().Name!, AsyncStoreInventoryCensus.Operations(context)); + } modules.Values.Should().OnlyContain(operations => operations.Length > 0); var platformOperations = AsyncStoreInventoryCensus.Operations(platform); var auditOperations = AsyncStoreInventoryCensus.Operations(audit); diff --git a/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs index 3cdbc5a05..b3c730f81 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuditConventionTests.cs @@ -164,7 +164,7 @@ public void Every_Module_Has_An_AuditCoverage_Matrix() // another appearing without a matrix is what this rule is for, and a bare count // would let one be swapped for another. modules.Select(Path.GetFileName).Should().BeEquivalentTo( - ["tenancy", "customization", "audit", "education"]); + ["tenancy", "customization", "audit", "education", "identity"]); WithoutMatrix(modules).Should().BeEmpty( "a module spec without a coverage matrix is a module whose audit obligations " @@ -305,7 +305,7 @@ public void Modules_Do_Not_Write_AuditLog_Directly() inserting.Should().Equal( ["LearnStack.Infrastructure.Audit/PostgresAuditStore.cs"], - "PostgresAuditStore's six writes are the only SQL that adds an audit row"); + "PostgresAuditStore's eight writes are the only SQL that adds an audit row"); // The context's exemption is for the MAPPING: a change-tracker write placed inside // AuditDbContext would be invisible to the leg above, because its caller names only the @@ -515,13 +515,14 @@ public void The_AppendOnly_Sweep_Can_Actually_Fail() public void IAuditStore_Exposes_No_Update_Method() { // The other half of the same claim, and the one a reader checks first. ADR-0033 - // ADR-0046 and ADR-0047 authorize six writes and no update; another method would + // ADR-0046, ADR-0047 and ADR-0072 authorize eight writes and no update; another method would // make the port contradict its closed write contract. typeof(IAuditStore).GetMethods() .Select(method => method.Name) .Should().BeEquivalentTo( "WritePendingAsync", "WriteStandaloneAsync", "WriteBestEffortAsync", - "WritePlatformScopeAsync", "WriteEventTerminalAsync", "WriteJobTerminalAsync"); + "WritePlatformScopeAsync", "WriteEventTerminalAsync", "WriteJobTerminalAsync", + "WriteGlobalIdentityPendingAsync", "ReconcileGlobalIdentityAsync"); } /// diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Controls.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Controls.cs index ac776d146..364f6448f 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Controls.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Controls.cs @@ -37,6 +37,7 @@ public void Authority_census_rejects_compiled_claim_role_and_projection_bypasses blinded.Should().Throw("a weakened raw-reader predicate must fail its dirty control: " + name); } foreach (var name in new[] { nameof(AuthorityProbe.Forge), nameof(AuthorityProbe.ForgeFeature), + nameof(AuthorityProbe.ForgeVerified), nameof(AuthorityProbe.CloneVerified), nameof(AuthorityProbe.VerifiedText), nameof(AuthorityProbe.Clone), nameof(AuthorityProbe.SubjectPermission), nameof(AuthorityProbe.SubjectDeconstruct), nameof(AuthorityProbe.SubjectText), nameof(AuthorityProbe.SubjectInterpolation), nameof(AuthorityProbe.FeatureFormatting) }) Offenders(modules, [methods.Single(method => method.Name == name)]).Should().NotBeEmpty(name); @@ -66,7 +67,7 @@ public void Authority_census_detects_missing_subjects_mutability_and_extra_trust var profile = api.GetType(Profile); var factory = profile.Methods.Single(method => method.Name == "TryReadValidated"); var construction = factory.Body.Instructions.Single(instruction => instruction.OpCode == OpCodes.Newobj - && instruction.Operand is MethodReference target && Is(target.DeclaringType, Identity)); + && instruction.Operand is MethodReference target && Is(target.DeclaringType, Verified)); var original = construction.Operand; construction.Operand = api.ImportReference(typeof(object).GetConstructor(Type.EmptyTypes)!); Offenders(modules).Should().NotBeEmpty("the actual factory call is a required nonempty subject"); @@ -75,6 +76,14 @@ public void Authority_census_detects_missing_subjects_mutability_and_extra_trust identity.IsSealed = false; Offenders(modules).Should().NotBeEmpty("the projection cannot gain a mutable/subclass authority channel"); identity.IsSealed = true; + var verified = api.GetType(Verified); + verified.IsSealed = false; + Offenders(modules).Should().NotBeEmpty("the verified subject cannot gain a subclass authority channel"); + verified.IsSealed = true; + var verifiedField = verified.Fields.First(); + verifiedField.IsInitOnly = false; + Offenders(modules).Should().NotBeEmpty("verified evidence must remain immutable for cached quota provenance"); + verifiedField.IsInitOnly = true; var actor = identity.Properties.Single(property => property.Name == "ActorUserId").SetMethod; var init = actor.ReturnType; actor.ReturnType = api.TypeSystem.Void; @@ -89,7 +98,7 @@ public void Authority_census_detects_missing_subjects_mutability_and_extra_trust var validated = events.Methods.Single(method => method.Name == "TokenValidated"); var setter = validated.Body.Instructions.Single(instruction => instruction.Operand is MethodReference target - && Is(target.DeclaringType, Feature) && target.Name == "set_Identity"); + && Is(target.DeclaringType, Feature) && target.Name == "set_VerifiedSubject"); var duplicate = Instruction.Create(OpCodes.Callvirt, (MethodReference)setter.Operand); validated.Body.Instructions.Add(duplicate); Offenders(modules).Should().NotBeEmpty("an extra write inside the approved owner is still a changed capability multiset"); @@ -157,6 +166,10 @@ public void Authority_census_detects_missing_subjects_mutability_and_extra_trust /// ADR-0064: approved owners do not authorize extra members, overloads or opaque exports. [Theory] + [InlineData("verified-method")] + [InlineData("verified-property")] + [InlineData("verified-field")] + [InlineData("verified-constructor")] [InlineData("identity-method")] [InlineData("identity-property")] [InlineData("identity-field")] @@ -173,7 +186,8 @@ public void Authority_census_closes_shape_and_approved_owner_exports(string muta { Offenders(modules).Should().BeEmpty(); var api = modules.Single(module => module.Assembly.Name.Name == "LearnStack.Api"); - var owner = api.GetType(mutation.StartsWith("feature-", StringComparison.Ordinal) ? Feature : Identity); + var owner = api.GetType(mutation.StartsWith("feature-", StringComparison.Ordinal) ? Feature + : mutation.StartsWith("verified-", StringComparison.Ordinal) ? Verified : Identity); var factory = api.GetType(Profile).Methods.Single(method => method.Name == "TryReadValidated"); if (mutation.EndsWith("-property", StringComparison.Ordinal)) owner.Properties.Add(new PropertyDefinition("Extra", PropertyAttributes.None, api.TypeSystem.String)); @@ -185,7 +199,7 @@ public void Authority_census_closes_shape_and_approved_owner_exports(string muta { var constructor = new MethodDefinition(".ctor", MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, api.TypeSystem.Void); // Same arity, different signature, and actually called by the approved factory. - foreach (var _ in Enumerable.Range(0, owner.FullName == Identity ? 5 : 0)) + foreach (var _ in Enumerable.Range(0, owner.FullName is Identity or Verified ? 5 : 0)) constructor.Parameters.Add(new ParameterDefinition(api.TypeSystem.Object)); owner.Methods.Add(constructor); factory.Body.Instructions.Add(Instruction.Create(OpCodes.Newobj, constructor)); @@ -257,8 +271,8 @@ public void Authority_census_rejects_actual_identity_forwarding_to_opaque_helper var validated = api.GetType(Events).Methods.Single(method => method.Name == "TokenValidated"); var setter = validated.Body.Instructions.Single(instruction => instruction.Operand is MethodReference target - && Is(target.DeclaringType, Feature) && target.Name == "set_Identity"); - var identity = validated.Body.Variables.Single(variable => Is(variable.VariableType, Identity)); + && Is(target.DeclaringType, Feature) && target.Name == "set_VerifiedSubject"); + var identity = validated.Body.Variables.Single(variable => Is(variable.VariableType, Verified)); var forwarding = new List(); if (array) forwarding.AddRange([Instruction.Create(OpCodes.Ldc_I4_1), Instruction.Create(OpCodes.Newarr, api.TypeSystem.Object), @@ -323,8 +337,8 @@ public void Authority_census_rejects_actual_identity_forwarding_through_opaque_s var validated = api.GetType(Events).Methods.Single(method => method.Name == "TokenValidated"); var setter = validated.Body.Instructions.Single(instruction => instruction.Operand is MethodReference target - && Is(target.DeclaringType, Feature) && target.Name == "set_Identity"); - var identity = validated.Body.Variables.Single(variable => Is(variable.VariableType, Identity)); + && Is(target.DeclaringType, Feature) && target.Name == "set_VerifiedSubject"); + var identity = validated.Body.Variables.Single(variable => Is(variable.VariableType, Verified)); var forwarding = new List(); if (storage == "instance") forwarding.AddRange([Instruction.Create(OpCodes.Newobj, constructor), Instruction.Create(OpCodes.Dup)]); if (storage == "array") forwarding.AddRange([Instruction.Create(OpCodes.Ldsfld, field), Instruction.Create(OpCodes.Ldc_I4_0)]); @@ -377,6 +391,9 @@ internal static IAuthorizeData InterfaceRoleMetadata(IAuthorizeData metadata) internal static bool RawHeaderReparse(HttpContext context) => new Microsoft.IdentityModel.JsonWebTokens.JsonWebToken( context.Request.Headers.Authorization.ToString()["Bearer ".Length..]).GetPayloadValue("permission") == "write"; internal static ValidatedTenantIdentity Forge() => new("issuer", "subject", UserId.From(Guid.Parse("a2999254-8355-43da-86ea-5cbebf105d29")), null, null); + internal static VerifiedProviderSubject ForgeVerified() => new("issuer", "subject", null, null, null); + internal static VerifiedProviderSubject CloneVerified(VerifiedProviderSubject subject) => subject with { Subject = "substitution" }; + internal static string VerifiedText(VerifiedProviderSubject subject) => subject.ToString(); internal static TenantCredentialFeature ForgeFeature(ValidatedTenantIdentity identity) => new() { Identity = identity }; internal static ValidatedTenantIdentity Clone(ValidatedTenantIdentity identity) => identity with { Subject = "tenant-admin" }; internal static bool SubjectPermission(ValidatedTenantIdentity identity) => identity.Subject == "tenant-admin"; diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs index 52f6c553a..aae24b9c2 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.Shapes.cs @@ -5,6 +5,7 @@ namespace LearnStack.Tests.Architecture; public sealed partial class AuthenticationAuthorityTests { + private const string OptionalUser = "System.Nullable`1"; private const string User = "LearnStack.SharedKernel.Identifiers.UserId"; private const string Tenant = "System.Nullable`1"; private const string Organization = "System.Nullable`1"; @@ -19,14 +20,22 @@ public sealed partial class AuthenticationAuthorityTests private const string Init = "System.Void modreq(System.Runtime.CompilerServices.IsExternalInit)"; private static readonly string[] IdentityArguments = ["System.String", "System.String", User, Tenant, Organization]; private static readonly string IdentityConstructor = Signature(Identity, ".ctor", "System.Void", IdentityArguments); + private static readonly string[] VerifiedArguments = ["System.String", "System.String", OptionalUser, Tenant, Organization]; + private static readonly string VerifiedConstructor = Signature(Verified, ".ctor", "System.Void", VerifiedArguments); + private static readonly string VerifiedCopyConstructor = Signature(Verified, ".ctor", "System.Void", Verified); private static readonly string IdentityCopyConstructor = Signature(Identity, ".ctor", "System.Void", Identity); private static readonly Dictionary ApprovedSites = new(StringComparer.Ordinal) { - [Profile + ".TryReadValidated"] = Signature(Profile, "TryReadValidated", "System.Boolean", "System.String", Authentication + "TenantAuthenticationOptions", "System.DateTimeOffset", Identity + "&", Authentication + "TenantTokenFailure&"), + [Profile + ".TryReadValidated"] = Signature(Profile, "TryReadValidated", "System.Boolean", "System.String", Authentication + "TenantAuthenticationOptions", "System.DateTimeOffset", Verified + "&", Authentication + "TenantTokenFailure&"), [Events + ".MessageReceived"] = Signature(Events, "MessageReceived", TaskType, "Microsoft.AspNetCore.Authentication.JwtBearer.MessageReceivedContext"), [Events + ".AuthenticationFailed"] = Signature(Events, "AuthenticationFailed", TaskType, "Microsoft.AspNetCore.Authentication.JwtBearer.AuthenticationFailedContext"), [Events + ".TokenValidated"] = Signature(Events, "TokenValidated", TaskType, "Microsoft.AspNetCore.Authentication.JwtBearer.TokenValidatedContext"), - [Limiter + ".AttemptAcquire"] = Signature(Limiter, "AttemptAcquire", Authentication + "SubjectAdmissionDecision", Identity), + [Limiter + ".AttemptAcquire"] = Signature(Limiter, "AttemptAcquire", Authentication + "SubjectAdmissionDecision", Verified), + [BindingAdmission + ".InvokeAsync"] = Signature(BindingAdmission, "InvokeAsync", TaskType, Http, Authentication + "ITenantIdentityBindingResolver"), + [BindingAdmission + ".Refuse"] = Signature(BindingAdmission, "Refuse", "System.Void", Http), + [BindingResolver + ".ResolveExistingAsync"] = Signature(BindingResolver, "ResolveExistingAsync", TaskType + "`1", Verified, "System.Threading.CancellationToken"), + [Provenance + "..ctor"] = Signature(Provenance, ".ctor", "System.Void", Verified), + [Provenance + ".Matches"] = Signature(Provenance, "Matches", "System.Boolean", Verified), [Resolver + ".BuildAttemptAsync"] = Signature(Resolver, "BuildAttemptAsync", TaskType + "`1<" + Attempt + ">", Http, Host, ScopeValidator, Membership, Identity), [Resolver + ".RecordRefusalAsync"] = Signature(Resolver, "RecordRefusalAsync", TaskType, Attempt, Host, Identity, Recorder), [Resolver + ".InvokeAsync"] = Signature(Resolver, "InvokeAsync", TaskType, Http, ScopeValidator, Membership, Recorder), @@ -44,63 +53,96 @@ private static string Signature(string owner, string name, string result, params private static string ExpectedSite(string site) => site switch { Feature + ".set_Identity" => Signature(Feature, "set_Identity", "System.Void", Identity), + Feature + ".set_VerifiedSubject" => Signature(Feature, "set_VerifiedSubject", "System.Void", Verified), Feature + "..ctor" => Signature(Feature, ".ctor", "System.Void"), Identity + ".$" => Signature(Identity, "$", Identity), + Verified + ".$" => Signature(Verified, "$", Verified), _ => ApprovedSites[site] }; - private static bool HasClosedIdentityShape(TypeDefinition identity) - { - var expected = new List - { - IdentityConstructor, IdentityCopyConstructor, - Signature(Identity, "get_EqualityContract", "System.Type"), - Signature(Identity, "ToString", "System.String"), - Signature(Identity, "PrintMembers", "System.Boolean", "System.Text.StringBuilder"), - Signature(Identity, "op_Inequality", "System.Boolean", Identity, Identity), - Signature(Identity, "op_Equality", "System.Boolean", Identity, Identity), - Signature(Identity, "GetHashCode", "System.Int32"), - Signature(Identity, "Equals", "System.Boolean", "System.Object"), - Signature(Identity, "Equals", "System.Boolean", Identity), - Signature(Identity, "$", Identity), - Signature(Identity, "Deconstruct", "System.Void", IdentityArguments.Select(argument => argument + "&").ToArray()) - }; - var types = new Dictionary(StringComparer.Ordinal) + private static bool HasClosedIdentityShape(TypeDefinition identity) => HasClosedRecordShape(identity, Identity, + IdentityArguments, new Dictionary(StringComparer.Ordinal) { ["Issuer"] = "System.String", ["Subject"] = "System.String", ["ActorUserId"] = User, ["TenantId"] = Tenant, ["OrganizationId"] = Organization + }); + + private static bool HasClosedVerifiedShape(TypeDefinition identity) => HasClosedRecordShape(identity, Verified, + VerifiedArguments, new Dictionary(StringComparer.Ordinal) + { + ["Issuer"] = "System.String", + ["Subject"] = "System.String", + ["ClaimedActor"] = OptionalUser, + ["TenantId"] = Tenant, + ["OrganizationId"] = Organization + }); + + private static bool HasClosedRecordShape(TypeDefinition identity, string name, string[] arguments, + Dictionary types) + { + var expected = new List + { + Signature(name, ".ctor", "System.Void", arguments), Signature(name, ".ctor", "System.Void", name), + Signature(name, "get_EqualityContract", "System.Type"), + Signature(name, "ToString", "System.String"), + Signature(name, "PrintMembers", "System.Boolean", "System.Text.StringBuilder"), + Signature(name, "op_Inequality", "System.Boolean", name, name), + Signature(name, "op_Equality", "System.Boolean", name, name), + Signature(name, "GetHashCode", "System.Int32"), + Signature(name, "Equals", "System.Boolean", "System.Object"), + Signature(name, "Equals", "System.Boolean", name), + Signature(name, "$", name), + Signature(name, "Deconstruct", "System.Void", arguments.Select(argument => argument + "&").ToArray()) }; foreach (var (property, type) in types) { - expected.Add(Signature(Identity, "get_" + property, type)); - expected.Add(Signature(Identity, "set_" + property, Init, type)); + expected.Add(Signature(name, "get_" + property, type)); + expected.Add(Signature(name, "set_" + property, Init, type)); } - return Same(identity.Methods.Select(method => method.FullName), expected) - && Same(identity.Properties.Select(property => property.Name), IdentityProperties.Append("EqualityContract")) + return identity.IsSealed && !identity.IsPublic + && Same(identity.Methods.Select(method => method.FullName), expected) + && Same(identity.Properties.Select(property => property.Name), types.Keys.Append("EqualityContract")) && identity.Properties.Single(property => property.Name == "EqualityContract") is { SetMethod: null, PropertyType.FullName: "System.Type" } + && identity.Properties.Where(property => property.Name != "EqualityContract").All(property => + property.PropertyType.FullName == types[property.Name] + && property.GetMethod.ReturnType.FullName == types[property.Name] + && property.SetMethod.ReturnType.FullName == Init + && property.SetMethod.Parameters.Single().ParameterType.FullName == types[property.Name]) && Same(identity.Fields.Select(field => field.Name + ":" + field.FieldType.FullName), types.Select(property => "<" + property.Key + ">k__BackingField:" + property.Value)) && identity.Fields.All(field => field.IsPrivate && field.IsInitOnly && !field.IsStatic) && identity.BaseType.FullName == "System.Object" - && Same(identity.Interfaces.Select(contract => contract.InterfaceType.FullName), ["System.IEquatable`1<" + Identity + ">"]) + && Same(identity.Interfaces.Select(contract => contract.InterfaceType.FullName), ["System.IEquatable`1<" + name + ">"]) && !identity.HasEvents && !identity.HasNestedTypes && !identity.HasGenericParameters; } private static bool HasClosedFeatureShape(TypeDefinition feature) => Same(feature.Methods.Select(method => method.FullName), - [Signature(Feature, ".ctor", "System.Void"), Signature(Feature, "get_Identity", Identity), Signature(Feature, "set_Identity", "System.Void", Identity)]) - && feature.Properties.Count == 1 && feature.Properties[0].Name == "Identity" - && feature.Fields.Count == 1 && feature.Fields[0] is { Name: "k__BackingField", IsPrivate: true, IsStatic: false } - && Is(feature.Fields[0].FieldType, Identity) + [Signature(Feature, ".ctor", "System.Void"), Signature(Feature, "get_Identity", Identity), Signature(Feature, "set_Identity", "System.Void", Identity), + Signature(Feature, "get_VerifiedSubject", Verified), Signature(Feature, "set_VerifiedSubject", "System.Void", Verified)]) + && Same(feature.Properties.Select(property => property.Name), ["Identity", "VerifiedSubject"]) + && feature.Properties.All(property => Is(property.PropertyType, + property.Name == "Identity" ? Identity : Verified)) + && Same(feature.Fields.Select(field => field.Name + ":" + field.FieldType.FullName), + ["k__BackingField:" + Identity, "k__BackingField:" + Verified]) + && feature.Fields.All(field => field.IsPrivate && !field.IsStatic) && feature.BaseType.FullName == "System.Object" && !feature.HasInterfaces && !feature.HasEvents && !feature.HasNestedTypes && !feature.HasGenericParameters; private static bool Same(IEnumerable actual, IEnumerable expected) => actual.Order(StringComparer.Ordinal).SequenceEqual(expected.Order(StringComparer.Ordinal), StringComparer.Ordinal); + private static bool HasClosedProvenanceShape(TypeDefinition provenance) => provenance.IsSealed && !provenance.IsPublic + && Same(provenance.Methods.Select(method => method.FullName), + [Signature(Provenance, ".ctor", "System.Void", Verified), Signature(Provenance, "Matches", "System.Boolean", Verified)]) + && provenance.Fields.Count == 1 && provenance.Fields[0] is { Name: "_subject", IsPrivate: true, IsInitOnly: true, IsStatic: false } + && Is(provenance.Fields[0].FieldType, Verified) + && !provenance.HasProperties && !provenance.HasEvents && !provenance.HasInterfaces + && !provenance.HasNestedTypes && !provenance.HasGenericParameters; + private static bool IsOpaqueProjectionArgument(TypeReference type, MethodReference? method = null, TypeReference? owner = null) { if (type is GenericParameter parameter) @@ -120,7 +162,8 @@ private static bool IsOpaqueProjectionArgument(TypeReference type, MethodReferen { "System.Runtime" => target.FullName is "System.Void System.ArgumentNullException::ThrowIfNull(System.Object,System.String)" - or "System.Void System.ObjectDisposedException::ThrowIf(System.Boolean,System.Object)", + or "System.Void System.ObjectDisposedException::ThrowIf(System.Boolean,System.Object)" + or "System.Boolean System.Object::ReferenceEquals(System.Object,System.Object)", "System.Threading" => target.FullName is "System.Void System.Threading.Monitor::Enter(System.Object,System.Boolean&)" or "System.Void System.Threading.Monitor::Exit(System.Object)", diff --git a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.cs b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.cs index 663b0cc9f..a918e63e8 100644 --- a/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.cs @@ -12,10 +12,14 @@ public sealed partial class AuthenticationAuthorityTests { private const string Authentication = "LearnStack.Api.Authentication."; private const string Identity = Authentication + nameof(ValidatedTenantIdentity); + private const string Verified = Authentication + nameof(VerifiedProviderSubject); private const string Feature = Authentication + nameof(TenantCredentialFeature); private const string Events = Authentication + nameof(TenantAuthenticationEvents); private const string Profile = Authentication + nameof(TenantTokenProfile); private const string Limiter = Authentication + nameof(TenantSubjectRateLimiter); + private const string BindingAdmission = Authentication + nameof(TenantIdentityBindingAdmissionMiddleware); + private const string BindingResolver = Authentication + nameof(TenantIdentityBindingResolver); + private const string Provenance = Authentication + nameof(TenantSubjectAdmissionProvenance); private const string Resolver = "LearnStack.Api.Tenancy.TenantResolverMiddleware"; private static readonly string[] IdentityProperties = ["ActorUserId", "Issuer", "OrganizationId", "Subject", "TenantId"]; private static readonly Dictionary IdentityTypes = new(StringComparer.Ordinal) @@ -68,9 +72,9 @@ private static SortedSet Offenders(ModuleDefinition[] modules, // record without an identity-declared call. Close acquisition, holders // and forwarding too, rather than treating getters as the only readers. foreach (var method in methods.Where(projectionUse ?? TouchesProjection)) - if (method.Owner.FullName != Identity && method.Owner.FullName != Feature && !ApprovedSites.Values.Contains(method.Site, StringComparer.Ordinal)) + if (method.Owner.FullName != Identity && method.Owner.FullName != Verified && method.Owner.FullName != Feature && !ApprovedSites.Values.Contains(method.Site, StringComparer.Ordinal)) errors.Add("Unapproved typed identity/feature consumer: " + method.Site); - foreach (var method in methods.Where(method => method.Owner.FullName != Identity && method.Owner.FullName != Feature + foreach (var method in methods.Where(method => method.Owner.FullName != Identity && method.Owner.FullName != Verified && method.Owner.FullName != Feature && TouchesProjection(method) && ExportsProjection(method))) errors.Add("Opaque typed identity/feature export: " + method.Site); foreach (var type in types) @@ -87,22 +91,33 @@ private static SortedSet Offenders(ModuleDefinition[] modules, errors.Add("Realm-role authorization metadata: " + type.FullName); } - Require(method => method.FullName == IdentityConstructor, Profile + ".TryReadValidated"); + Require(method => method.FullName == IdentityConstructor, BindingAdmission + ".InvokeAsync"); Require(method => method.FullName == IdentityCopyConstructor, Identity + ".$"); + Require(method => method.FullName == VerifiedConstructor, Profile + ".TryReadValidated"); + Require(method => method.FullName == VerifiedCopyConstructor, Verified + ".$"); Require(Target(Feature, ".ctor"), Events + ".MessageReceived"); - Require(Target(Feature, "set_Identity"), Events + ".AuthenticationFailed", Events + ".TokenValidated"); + Require(Target(Feature, "set_Identity"), Events + ".AuthenticationFailed", + Authentication + "TenantCredentialAdmissionMiddleware.InvokeAsync", + Authentication + "TenantSubjectAdmissionMiddleware.InvokeAsync", BindingAdmission + ".InvokeAsync", + BindingAdmission + ".InvokeAsync", BindingAdmission + ".Refuse"); + Require(Target(Feature, "set_VerifiedSubject"), Events + ".AuthenticationFailed", Events + ".TokenValidated"); Require(Target(Profile, "TryReadValidated"), Events + ".TokenValidated"); Require(method => method.Name == "Set" && method is GenericInstanceMethod generic && generic.GenericArguments.Any(argument => Is(argument, Feature)), Events + ".MessageReceived"); - foreach (var call in calls.Where(call => Is(call.Target.DeclaringType, Identity) + foreach (var call in calls.Where(call => (Is(call.Target.DeclaringType, Identity) || Is(call.Target.DeclaringType, Verified)) && (call.Target.Name.StartsWith("set_", StringComparison.Ordinal) || call.Target.Name is "$" or "Deconstruct") || Is(call.Target.DeclaringType, Events) && call.Target.Name == "TokenValidated")) errors.Add("Cannot forge, clone, mutate, deconstruct or directly invoke validated identity: " + call.Source.Site); // Issuer/sub may select a private accounting partition, never permission. // Scope/actor consumption remains explicit even inside the API assembly. - Consumers("Issuer", Limiter + ".AttemptAcquire"); - Consumers("Subject", Limiter + ".AttemptAcquire"); + Consumers("Issuer"); + Consumers("Subject"); + VerifiedConsumers("Issuer", Limiter + ".AttemptAcquire", BindingResolver + ".ResolveExistingAsync", BindingAdmission + ".InvokeAsync"); + VerifiedConsumers("Subject", Limiter + ".AttemptAcquire", BindingResolver + ".ResolveExistingAsync", BindingAdmission + ".InvokeAsync"); + VerifiedConsumers("ClaimedActor", BindingResolver + ".ResolveExistingAsync"); + VerifiedConsumers("TenantId", BindingAdmission + ".InvokeAsync"); + VerifiedConsumers("OrganizationId", BindingAdmission + ".InvokeAsync"); Consumers("ActorUserId", Resolver + ".BuildAttemptAsync", Resolver + ".RecordRefusalAsync", "LearnStack.Api.Tenancy.TenantAssertionMiddleware.InvokeAsync", Authentication + "TenantSurfaceAdmissionMiddleware.HasHostAuthority"); @@ -113,8 +128,8 @@ private static SortedSet Offenders(ModuleDefinition[] modules, foreach (var method in methods) foreach (var instruction in method.Definition.Body.Instructions) if (instruction.OpCode == OpCodes.Stfld && instruction.Operand is FieldReference field - && Is(field.DeclaringType, Feature) && Is(field.FieldType, Identity) - && method.Site != ExpectedSite(Feature + ".set_Identity")) + && Is(field.DeclaringType, Feature) && (Is(field.FieldType, Identity) || Is(field.FieldType, Verified)) + && method.Site != ExpectedSite(Feature + (Is(field.FieldType, Identity) ? ".set_Identity" : ".set_VerifiedSubject"))) errors.Add("Direct identity backing-field write: " + method.Site); var identities = types.Where(type => Is(type, Identity)).ToArray(); @@ -147,6 +162,12 @@ private static SortedSet Offenders(ModuleDefinition[] modules, errors.Add("Validated identity has an unexpected member or constructor signature."); if (features.Length == 1 && !HasClosedFeatureShape(features[0])) errors.Add("Credential feature has an unexpected member or constructor signature."); + var verified = types.Where(type => Is(type, Verified)).ToArray(); + if (verified.Length != 1 || !HasClosedVerifiedShape(verified[0])) + errors.Add("Verified provider subject must retain its closed immutable typed shape."); + var provenance = types.Where(type => Is(type, Provenance)).ToArray(); + if (provenance.Length != 1 || !HasClosedProvenanceShape(provenance[0])) + errors.Add("Subject admission provenance must retain its closed immutable request-local shape."); return errors; void Require(Func target, params string[] owners) @@ -157,9 +178,15 @@ void Require(Func target, params string[] owners) } void Consumers(string property, params string[] owners) + => ProjectionConsumers(Identity, property, owners); + + void VerifiedConsumers(string property, params string[] owners) + => ProjectionConsumers(Verified, property, owners); + + void ProjectionConsumers(string projection, string property, params string[] owners) { - var actual = calls.Where(call => Is(call.Target.DeclaringType, Identity) && call.Target.Name == "get_" + property - && call.Source.Owner.FullName != Identity) + var actual = calls.Where(call => Is(call.Target.DeclaringType, projection) && call.Target.Name == "get_" + property + && call.Source.Owner.FullName != projection) .Select(call => call.Source.Site).Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal); if (!actual.SequenceEqual(owners.Select(ExpectedSite).Order(StringComparer.Ordinal), StringComparer.Ordinal)) errors.Add("Changed/missing validated " + property + " consumers: " + string.Join(", ", actual)); @@ -200,7 +227,7 @@ private static bool Matches(TypeReference actual, Type expected) => Nullable.Get : actual.FullName == expected.FullName && (expected == typeof(string) || actual.Scope.Name.Replace(".dll", "", StringComparison.Ordinal) == expected.Assembly.GetName().Name); - private static bool CarriesProjection(TypeReference type) => Is(type, Identity) || Is(type, Feature) + private static bool CarriesProjection(TypeReference type) => Is(type, Identity) || Is(type, Verified) || Is(type, Feature) || type is GenericInstanceType generic && generic.GenericArguments.Any(CarriesProjection) || type is TypeSpecification specification && CarriesProjection(specification.ElementType); diff --git a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobApplicationSourceBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobApplicationSourceBoundaryTests.cs index ea9e2eeec..c82f6851f 100644 --- a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobApplicationSourceBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobApplicationSourceBoundaryTests.cs @@ -110,8 +110,8 @@ private static SortedSet JobApplicationSourceOffenders(ProductionCensus Exact(resources, "DisposeReaderAsync", [cores[0], cores[2], (AppJobResources, "CleanupAsync")]); Exact(resources, "CleanupAsync", cores); Exact(owner, "BindMainUnit", [(AppJobUnit, "BindJobMainUnit")]); - Exact(owner, "HoldMainConnection", [(AppJobUnit, "get_Connection"), (AppJobUnit, "BeginTransactionAsync")]); - Exact(owner, "HoldMainTransaction", [(AppJobUnit, "BeginTransactionAsync")]); + Exact(owner, "HoldMainConnection", [(AppJobUnit, "get_Connection"), (AppJobUnit, "BeginTransactionCoreAsync")]); + Exact(owner, "HoldMainTransaction", [(AppJobUnit, "BeginTransactionCoreAsync")]); Exact(owner, "ReportMainTransactionCleanup", [(AppJobUnit, "CommitFrameAsync"), (AppJobUnit, "CommitFrameAsync"), (AppJobUnit, "DisposeCompletedTransactionAsync"), (AppJobUnit, "DisposeCompletedTransactionAsync"), (AppJobUnit, "RollbackCoreAsync"), (AppJobUnit, "RollbackCoreAsync")]); @@ -140,9 +140,9 @@ void Exact(TypeDefinition subject, string name, (string Type, string Method)[] e foreach (var (typeName, methodName) in expected) { var callers = types[typeName].Methods.Where(method => method.Name == methodName - && (typeName != AppJobUnit || methodName != "BeginTransactionAsync" + && (typeName != AppJobUnit || methodName != "BeginTransactionCoreAsync" || method.Parameters.Select(parameter => parameter.ParameterType.FullName).SequenceEqual( - ["LearnStack.SharedKernel.Persistence.TransactionMode", "System.Threading.CancellationToken"]))).ToArray(); + ["LearnStack.SharedKernel.Persistence.TransactionMode", "System.Boolean", "System.Threading.CancellationToken"]))).ToArray(); if (callers.Length != 1) { offenders.Add("Missing or overloaded job source caller: " + typeName + "::" + methodName); continue; } allowed.Add(MethodId(callers[0])); } diff --git a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobAuthorityBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobAuthorityBoundaryTests.cs index a46cceac2..baef89a06 100644 --- a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobAuthorityBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobAuthorityBoundaryTests.cs @@ -25,7 +25,7 @@ public void BackgroundJob_Ordinary_Execution_Has_No_Platform_Authority() CheckJobFrameworkMetadata(); } - public sealed partial class JobAuthorityMutationTests + public sealed class JobAuthorityCensusMutationTests { /// ADR-0047: prove the same production predicate detects removal and additional activation. @@ -180,7 +180,9 @@ private static SortedSet JobAuthorityOffenders(ProductionCensus census) RequireBoundaryMethod(offenders, types[(InfrastructureAssembly, JobBridgeStore)], "UpdateAsync", BoundaryBooleanTask, MethodAttributes.Private, "LearnStack.Infrastructure.Jobs.BackgroundJobBridgeClaim", "System.String", "System.Nullable`1", BoundaryCancellation), - Owner(DeliveryApplication, DeliveryCoordinator, "PrepareDeliveryOwnerAsync"), Owner(DeliveryApplication, DeliveryCoordinator, "ExecutePreparedDeliveryAsync")]); + Owner(DeliveryApplication, DeliveryCoordinator, "PrepareDeliveryOwnerAsync"), Owner(DeliveryApplication, DeliveryCoordinator, "ExecutePreparedDeliveryAsync"), + Owner(DeliveryApplication, DeliveryCoordinator, "PrepareGlobalIdentityOwnerAsync"), + Owner(DeliveryApplication, DeliveryCoordinator, "ExecutePreparedGlobalIdentityAsync")]); return offenders; string Identity(MethodDefinition method) diff --git a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobCapacityMutationTests.cs b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobCapacityMutationTests.cs index a47514734..a5c08cf88 100644 --- a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobCapacityMutationTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobCapacityMutationTests.cs @@ -8,7 +8,7 @@ namespace LearnStack.Tests.Architecture; public sealed partial class OutboxDispatchConventionTests { - public sealed partial class JobLifecycleMutationTests + public sealed class JobCapacityMutationTests { /// ADR-0047 capacity boundaries: planted escapes must fail the same production capability detector. [Fact] diff --git a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobMetricBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobMetricBoundaryTests.cs index 23493f2ef..5c8ae5a78 100644 --- a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobMetricBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobMetricBoundaryTests.cs @@ -301,227 +301,230 @@ private static bool MetricPathAvoids(MethodDefinition constructor, IEnumerable(StringComparer.Ordinal); - var roots = JobMetricRoots(census, ignored); - ignored.Should().BeEmpty(); - roots.Should().HaveCount(18, "five actual collectors and thirteen fixed-memory control/execution/recurrence recorders or predicates are independently reached"); - foreach (var recorder in roots.Where(method => method.Name == "ObserveLeaseLoss")) - { - var asynchronous = new CustomAttribute(recorder.Module.ImportReference( - typeof(System.Runtime.CompilerServices.AsyncStateMachineAttribute).GetConstructor([typeof(Type)])!)); - asynchronous.ConstructorArguments.Add(new(recorder.Module.ImportReference(typeof(Type)), recorder.DeclaringType)); - recorder.CustomAttributes.Add(asynchronous); - try + [Fact] + public void Background_job_metric_callbacks_follow_the_actual_transitive_memory_graph_and_refuse_persistence_helpers() + { + using var census = ProductionCensus.Read(); + var baselineOffenders = EvaluateDetector(census, RuntimeLifetimeOffenders); + baselineOffenders.Should().BeEmpty("complete baseline offenders: {0}", string.Join("\n", baselineOffenders)); + var ignored = new SortedSet(StringComparer.Ordinal); + var roots = JobMetricRoots(census, ignored); + ignored.Should().BeEmpty(); + roots.Should().HaveCount(18, "five actual collectors and thirteen fixed-memory control/execution/recurrence recorders or predicates are independently reached"); + foreach (var recorder in roots.Where(method => method.Name == "ObserveLeaseLoss")) { - EvaluateDetector(census, RuntimeLifetimeOffenders).Should().Contain(value => - value.Contains("two concrete synchronous instance helpers", StringComparison.Ordinal), - "an async-void recorder cannot retain its synchronous fixed-memory claim"); + var asynchronous = new CustomAttribute(recorder.Module.ImportReference( + typeof(System.Runtime.CompilerServices.AsyncStateMachineAttribute).GetConstructor([typeof(Type)])!)); + asynchronous.ConstructorArguments.Add(new(recorder.Module.ImportReference(typeof(Type)), recorder.DeclaringType)); + recorder.CustomAttributes.Add(asynchronous); + try + { + EvaluateDetector(census, RuntimeLifetimeOffenders).Should().Contain(value => + value.Contains("two concrete synchronous instance helpers", StringComparison.Ordinal), + "an async-void recorder cannot retain its synchronous fixed-memory claim"); + } + finally { recorder.CustomAttributes.Remove(asynchronous); } + EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); } - finally { recorder.CustomAttributes.Remove(asynchronous); } - EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); - } - foreach (var recorder in roots.Where(method => method.Name is "ObserveLateSettlement" or "HasSettledStage" or "CaptureLateSettlements")) - { - var asynchronous = new CustomAttribute(recorder.Module.ImportReference( - typeof(System.Runtime.CompilerServices.AsyncStateMachineAttribute).GetConstructor([typeof(Type)])!)); - asynchronous.ConstructorArguments.Add(new(recorder.Module.ImportReference(typeof(Type)), recorder.DeclaringType)); - recorder.CustomAttributes.Add(asynchronous); - try + foreach (var recorder in roots.Where(method => method.Name is "ObserveLateSettlement" or "HasSettledStage" or "CaptureLateSettlements")) { - EvaluateDetector(census, RuntimeLifetimeOffenders).Should().Contain(value => - value.Contains("concrete synchronous helper", StringComparison.Ordinal), - "every late classifier/forwarder/recorder remains synchronous memory observation"); + var asynchronous = new CustomAttribute(recorder.Module.ImportReference( + typeof(System.Runtime.CompilerServices.AsyncStateMachineAttribute).GetConstructor([typeof(Type)])!)); + asynchronous.ConstructorArguments.Add(new(recorder.Module.ImportReference(typeof(Type)), recorder.DeclaringType)); + recorder.CustomAttributes.Add(asynchronous); + try + { + EvaluateDetector(census, RuntimeLifetimeOffenders).Should().Contain(value => + value.Contains("concrete synchronous helper", StringComparison.Ordinal), + "every late classifier/forwarder/recorder remains synchronous memory observation"); + } + finally { recorder.CustomAttributes.Remove(asynchronous); } + EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); } - finally { recorder.CustomAttributes.Remove(asynchronous); } - EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); - } - var root = roots.Single(method => method.Name == "CollectCounts"); - var application = census.Modules.Single(module => module.Assembly.Name.Name == DeliveryApplication); - var helper = AddProbe(application, "MetricMemoryHelper"); - var memory = new MethodDefinition("ReadMemory", MethodAttributes.Public | MethodAttributes.Static, application.TypeSystem.Void); - memory.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); - helper.Methods.Add(memory); - var sql = AddCall(helper, "ReadSql", application.ImportReference(typeof(Npgsql.NpgsqlCommand).GetConstructor(Type.EmptyTypes)!), OpCodes.Newobj); - sql.Body.Instructions.Insert(1, Instruction.Create(OpCodes.Pop)); - var call = Instruction.Create(OpCodes.Call, root.Module.ImportReference(memory)); - root.Body.Instructions.Insert(0, call); - try - { - EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty( - "an unreached SQL sibling does not make a pure memory helper activate persistence"); - var indirect = Instruction.Create(OpCodes.Call, application.ImportReference(sql)); - memory.Body.Instructions.Insert(0, indirect); + var root = roots.Single(method => method.Name == "CollectCounts"); + var application = census.Modules.Single(module => module.Assembly.Name.Name == DeliveryApplication); + var helper = AddProbe(application, "MetricMemoryHelper"); + var memory = new MethodDefinition("ReadMemory", MethodAttributes.Public | MethodAttributes.Static, application.TypeSystem.Void); + memory.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + helper.Methods.Add(memory); + var sql = AddCall(helper, "ReadSql", application.ImportReference(typeof(Npgsql.NpgsqlCommand).GetConstructor(Type.EmptyTypes)!), OpCodes.Newobj); + sql.Body.Instructions.Insert(1, Instruction.Create(OpCodes.Pop)); + var call = Instruction.Create(OpCodes.Call, root.Module.ImportReference(memory)); + root.Body.Instructions.Insert(0, call); try { - EvaluateDetector(census, RuntimeLifetimeOffenders).Should().Contain(value => - value.Contains("jobs metrics observation reaches persistence/provider activation", StringComparison.Ordinal), - "the actual callback reaches SQL only through the foreign helper's second method"); - } - finally { memory.Body.Instructions.Remove(indirect); } - EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); - foreach (var recorder in roots.Where(method => method.DeclaringType.FullName != JobObservation)) - { - var recorderCall = Instruction.Create(OpCodes.Call, recorder.Module.ImportReference(sql)); - recorder.Body.Instructions.Insert(0, recorderCall); + EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty( + "an unreached SQL sibling does not make a pure memory helper activate persistence"); + var indirect = Instruction.Create(OpCodes.Call, application.ImportReference(sql)); + memory.Body.Instructions.Insert(0, indirect); try { EvaluateDetector(census, RuntimeLifetimeOffenders).Should().Contain(value => value.Contains("jobs metrics observation reaches persistence/provider activation", StringComparison.Ordinal), - "each permitted counter helper must reject transitive SQL independently: {0}", recorder.Name); + "the actual callback reaches SQL only through the foreign helper's second method"); } - finally { recorder.Body.Instructions.Remove(recorderCall); } + finally { memory.Body.Instructions.Remove(indirect); } EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); + foreach (var recorder in roots.Where(method => method.DeclaringType.FullName != JobObservation)) + { + var recorderCall = Instruction.Create(OpCodes.Call, recorder.Module.ImportReference(sql)); + recorder.Body.Instructions.Insert(0, recorderCall); + try + { + EvaluateDetector(census, RuntimeLifetimeOffenders).Should().Contain(value => + value.Contains("jobs metrics observation reaches persistence/provider activation", StringComparison.Ordinal), + "each permitted counter helper must reject transitive SQL independently: {0}", recorder.Name); + } + finally { recorder.Body.Instructions.Remove(recorderCall); } + EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); + } } - } - finally { root.Body.Instructions.Remove(call); application.Types.Remove(helper); } - EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); - AssertMutation(census, "an indirect discarded Task.Delay in a first-loss recorder", () => - { - var recorder = roots.Single(method => method.DeclaringType.FullName == OrchestrationExecution && method.Name == "ObserveLeaseLoss"); - var delayOwner = AddProbe(application, "MetricDelayHelper"); - var delay = AddCall(delayOwner, "Delay", application.ImportReference(typeof(Task).GetMethod("Delay", [typeof(int)])!), OpCodes.Call); - delay.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Ldc_I4_1)); - delay.Body.Instructions.Insert(2, Instruction.Create(OpCodes.Pop)); - var invokeDelay = Instruction.Create(OpCodes.Call, recorder.Module.ImportReference(delay)); - recorder.Body.Instructions.Insert(0, invokeDelay); - return () => { recorder.Body.Instructions.Remove(invokeDelay); application.Types.Remove(delayOwner); }; - }, RuntimeLifetimeOffenders); - AssertMutation(census, "an extra persistent late-settlement recorder caller", () => - { - var owner = census.Types[(InfrastructureAssembly, OrchestrationControl)]; - var extra = new MethodDefinition("InventLateSettlement", MethodAttributes.Private, owner.Module.TypeSystem.Void); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4_0)); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Call, owner.Methods.Single(method => method.Name == "ObserveLateSettlement"))); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); - owner.Methods.Add(extra); - return () => owner.Methods.Remove(extra); - }, RuntimeLifetimeOffenders); - AssertMutation(census, "an extra writer that could manufacture framework cleanup", () => - { - var owner = census.Types[(InfrastructureAssembly, OrchestrationBound)]; - var extra = new MethodDefinition("InventFrameworkCleanup", MethodAttributes.Private, owner.Module.TypeSystem.Void); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4_1)); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Stfld, owner.Fields.Single(field => field.Name == "_cleanupConfirmed"))); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); - owner.Methods.Add(extra); - return () => owner.Methods.Remove(extra); - }, RuntimeLifetimeOffenders); - AssertMutation(census, "an extra elapsed-stage writer that could turn stop into clock provenance", () => - { - var owner = census.Types[(InfrastructureAssembly, OrchestrationInvocation)]; - var extra = new MethodDefinition("InventElapsedStage", MethodAttributes.Private, owner.Module.TypeSystem.Void); - var marker = owner.Fields.Single(field => field.Name == "_elapsedStage"); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldflda, marker)); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Initobj, marker.FieldType)); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); - owner.Methods.Add(extra); - return () => owner.Methods.Remove(extra); - }, RuntimeLifetimeOffenders); - AssertMutation(census, "an unlisted recurrence progress caller outside the actual awaited SQL observation", () => - { - var owner = census.Types[(InfrastructureAssembly, RcControl)]; - var extra = new MethodDefinition("InventRecurrenceProgress", MethodAttributes.Private, owner.Module.TypeSystem.Void); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4_1)); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldnull)); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Call, owner.Methods.Single(method => method.Name == "ObserveProgress"))); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); - owner.Methods.Add(extra); - return () => owner.Methods.Remove(extra); - }, RuntimeLifetimeOffenders); + finally { root.Body.Instructions.Remove(call); application.Types.Remove(helper); } + EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); + AssertMutation(census, "an indirect discarded Task.Delay in a first-loss recorder", () => + { + var recorder = roots.Single(method => method.DeclaringType.FullName == OrchestrationExecution && method.Name == "ObserveLeaseLoss"); + var delayOwner = AddProbe(application, "MetricDelayHelper"); + var delay = AddCall(delayOwner, "Delay", application.ImportReference(typeof(Task).GetMethod("Delay", [typeof(int)])!), OpCodes.Call); + delay.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Ldc_I4_1)); + delay.Body.Instructions.Insert(2, Instruction.Create(OpCodes.Pop)); + var invokeDelay = Instruction.Create(OpCodes.Call, recorder.Module.ImportReference(delay)); + recorder.Body.Instructions.Insert(0, invokeDelay); + return () => { recorder.Body.Instructions.Remove(invokeDelay); application.Types.Remove(delayOwner); }; + }, RuntimeLifetimeOffenders); + AssertMutation(census, "an extra persistent late-settlement recorder caller", () => + { + var owner = census.Types[(InfrastructureAssembly, OrchestrationControl)]; + var extra = new MethodDefinition("InventLateSettlement", MethodAttributes.Private, owner.Module.TypeSystem.Void); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4_0)); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Call, owner.Methods.Single(method => method.Name == "ObserveLateSettlement"))); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + owner.Methods.Add(extra); + return () => owner.Methods.Remove(extra); + }, RuntimeLifetimeOffenders); + AssertMutation(census, "an extra writer that could manufacture framework cleanup", () => + { + var owner = census.Types[(InfrastructureAssembly, OrchestrationBound)]; + var extra = new MethodDefinition("InventFrameworkCleanup", MethodAttributes.Private, owner.Module.TypeSystem.Void); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4_1)); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Stfld, owner.Fields.Single(field => field.Name == "_cleanupConfirmed"))); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + owner.Methods.Add(extra); + return () => owner.Methods.Remove(extra); + }, RuntimeLifetimeOffenders); + AssertMutation(census, "an extra elapsed-stage writer that could turn stop into clock provenance", () => + { + var owner = census.Types[(InfrastructureAssembly, OrchestrationInvocation)]; + var extra = new MethodDefinition("InventElapsedStage", MethodAttributes.Private, owner.Module.TypeSystem.Void); + var marker = owner.Fields.Single(field => field.Name == "_elapsedStage"); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldflda, marker)); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Initobj, marker.FieldType)); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + owner.Methods.Add(extra); + return () => owner.Methods.Remove(extra); + }, RuntimeLifetimeOffenders); + AssertMutation(census, "an unlisted recurrence progress caller outside the actual awaited SQL observation", () => + { + var owner = census.Types[(InfrastructureAssembly, RcControl)]; + var extra = new MethodDefinition("InventRecurrenceProgress", MethodAttributes.Private, owner.Module.TypeSystem.Void); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4_1)); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldnull)); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Call, owner.Methods.Single(method => method.Name == "ObserveProgress"))); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + owner.Methods.Add(extra); + return () => owner.Methods.Remove(extra); + }, RuntimeLifetimeOffenders); - var callback = AddProbe(application, "CustomMetricCallback"); - callback.BaseType = application.ImportReference(typeof(MulticastDelegate)); - callback.IsSealed = true; - var invoke = new MethodDefinition("Invoke", MethodAttributes.Public | MethodAttributes.Virtual, - application.TypeSystem.Void) - { ImplAttributes = MethodImplAttributes.Runtime | MethodImplAttributes.Managed }; - callback.Methods.Add(invoke); - var delegateConstructor = new MethodDefinition(".ctor", MethodAttributes.Public | MethodAttributes.HideBySig - | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, application.TypeSystem.Void) - { ImplAttributes = MethodImplAttributes.Runtime | MethodImplAttributes.Managed }; - delegateConstructor.Parameters.Add(new(application.TypeSystem.Object)); - delegateConstructor.Parameters.Add(new(application.TypeSystem.IntPtr)); - callback.Methods.Add(delegateConstructor); - var field = new FieldDefinition("Callback", FieldAttributes.Public | FieldAttributes.Static, callback); - helper = AddProbe(application, "MetricDelegateHolder"); - helper.Fields.Add(field); - var load = Instruction.Create(OpCodes.Ldsfld, root.Module.ImportReference(field)); - var dispatch = Instruction.Create(OpCodes.Callvirt, root.Module.ImportReference(invoke)); - root.Body.Instructions.Insert(0, dispatch); - root.Body.Instructions.Insert(0, load); - try - { - EvaluateDetector(census, RuntimeLifetimeOffenders).Should().Contain(value => - value.Contains("jobs metrics observation invokes an arbitrary delegate", StringComparison.Ordinal), - "a runtime-implemented custom Invoke has no body whose absence can hide an unknown callback"); - } - finally - { - root.Body.Instructions.Remove(load); - root.Body.Instructions.Remove(dispatch); - application.Types.Remove(helper); - application.Types.Remove(callback); - } - EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); - AssertMutation(census, "an external Predicate Invoke that has no in-census delegate declaration", () => - { - var instructions = new[] - { - Instruction.Create(OpCodes.Ldnull), Instruction.Create(OpCodes.Ldnull), - Instruction.Create(OpCodes.Callvirt, root.Module.ImportReference(typeof(Predicate).GetMethod("Invoke")!)), - Instruction.Create(OpCodes.Pop), - }; - for (var index = 0; index < instructions.Length; index++) root.Body.Instructions.Insert(index, instructions[index]); - return () => { foreach (var instruction in instructions) root.Body.Instructions.Remove(instruction); }; - }, RuntimeLifetimeOffenders); + var callback = AddProbe(application, "CustomMetricCallback"); + callback.BaseType = application.ImportReference(typeof(MulticastDelegate)); + callback.IsSealed = true; + var invoke = new MethodDefinition("Invoke", MethodAttributes.Public | MethodAttributes.Virtual, + application.TypeSystem.Void) + { ImplAttributes = MethodImplAttributes.Runtime | MethodImplAttributes.Managed }; + callback.Methods.Add(invoke); + var delegateConstructor = new MethodDefinition(".ctor", MethodAttributes.Public | MethodAttributes.HideBySig + | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, application.TypeSystem.Void) + { ImplAttributes = MethodImplAttributes.Runtime | MethodImplAttributes.Managed }; + delegateConstructor.Parameters.Add(new(application.TypeSystem.Object)); + delegateConstructor.Parameters.Add(new(application.TypeSystem.IntPtr)); + callback.Methods.Add(delegateConstructor); + var field = new FieldDefinition("Callback", FieldAttributes.Public | FieldAttributes.Static, callback); + helper = AddProbe(application, "MetricDelegateHolder"); + helper.Fields.Add(field); + var load = Instruction.Create(OpCodes.Ldsfld, root.Module.ImportReference(field)); + var dispatch = Instruction.Create(OpCodes.Callvirt, root.Module.ImportReference(invoke)); + root.Body.Instructions.Insert(0, dispatch); + root.Body.Instructions.Insert(0, load); + try + { + EvaluateDetector(census, RuntimeLifetimeOffenders).Should().Contain(value => + value.Contains("jobs metrics observation invokes an arbitrary delegate", StringComparison.Ordinal), + "a runtime-implemented custom Invoke has no body whose absence can hide an unknown callback"); + } + finally + { + root.Body.Instructions.Remove(load); + root.Body.Instructions.Remove(dispatch); + application.Types.Remove(helper); + application.Types.Remove(callback); + } + EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); + AssertMutation(census, "an external Predicate Invoke that has no in-census delegate declaration", () => + { + var instructions = new[] + { + Instruction.Create(OpCodes.Ldnull), Instruction.Create(OpCodes.Ldnull), + Instruction.Create(OpCodes.Callvirt, root.Module.ImportReference(typeof(Predicate).GetMethod("Invoke")!)), + Instruction.Create(OpCodes.Pop), + }; + for (var index = 0; index < instructions.Length; index++) root.Body.Instructions.Insert(index, instructions[index]); + return () => { foreach (var instruction in instructions) root.Body.Instructions.Remove(instruction); }; + }, RuntimeLifetimeOffenders); - helper = AddProbe(application, "MetricStaticHolder"); - var marker = new FieldDefinition("Marker", FieldAttributes.Public | FieldAttributes.Static, application.TypeSystem.Int64); - helper.Fields.Add(marker); - var initializer = new MethodDefinition(".cctor", MethodAttributes.Private | MethodAttributes.Static - | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, application.TypeSystem.Void); - initializer.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); - helper.Methods.Add(initializer); - try - { - foreach (var code in new[] { OpCodes.Ldsfld, OpCodes.Ldsflda, OpCodes.Stsfld }) + helper = AddProbe(application, "MetricStaticHolder"); + var marker = new FieldDefinition("Marker", FieldAttributes.Public | FieldAttributes.Static, application.TypeSystem.Int64); + helper.Fields.Add(marker); + var initializer = new MethodDefinition(".cctor", MethodAttributes.Private | MethodAttributes.Static + | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, application.TypeSystem.Void); + initializer.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + helper.Methods.Add(initializer); + try { - var access = Instruction.Create(code, root.Module.ImportReference(marker)); - var value = code == OpCodes.Stsfld ? Instruction.Create(OpCodes.Ldc_I8, 0L) : Instruction.Create(OpCodes.Pop); - root.Body.Instructions.Insert(0, code == OpCodes.Stsfld ? access : value); - root.Body.Instructions.Insert(0, code == OpCodes.Stsfld ? value : access); - try + foreach (var code in new[] { OpCodes.Ldsfld, OpCodes.Ldsflda, OpCodes.Stsfld }) { - EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty("a reached memory-only initializer is safe"); - var create = Instruction.Create(OpCodes.Newobj, - application.ImportReference(typeof(Npgsql.NpgsqlCommand).GetConstructor(Type.EmptyTypes)!)); - var pop = Instruction.Create(OpCodes.Pop); - initializer.Body.Instructions.Insert(0, pop); - initializer.Body.Instructions.Insert(0, create); + var access = Instruction.Create(code, root.Module.ImportReference(marker)); + var value = code == OpCodes.Stsfld ? Instruction.Create(OpCodes.Ldc_I8, 0L) : Instruction.Create(OpCodes.Pop); + root.Body.Instructions.Insert(0, code == OpCodes.Stsfld ? access : value); + root.Body.Instructions.Insert(0, code == OpCodes.Stsfld ? value : access); try { - EvaluateDetector(census, RuntimeLifetimeOffenders).Should().Contain(value => - value.Contains("jobs metrics observation reaches persistence/provider activation", StringComparison.Ordinal), - "the static field access implicitly executes its owner's initializer"); + EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty("a reached memory-only initializer is safe"); + var create = Instruction.Create(OpCodes.Newobj, + application.ImportReference(typeof(Npgsql.NpgsqlCommand).GetConstructor(Type.EmptyTypes)!)); + var pop = Instruction.Create(OpCodes.Pop); + initializer.Body.Instructions.Insert(0, pop); + initializer.Body.Instructions.Insert(0, create); + try + { + EvaluateDetector(census, RuntimeLifetimeOffenders).Should().Contain(value => + value.Contains("jobs metrics observation reaches persistence/provider activation", StringComparison.Ordinal), + "the static field access implicitly executes its owner's initializer"); + } + finally { initializer.Body.Instructions.Remove(create); initializer.Body.Instructions.Remove(pop); } + EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); } - finally { initializer.Body.Instructions.Remove(create); initializer.Body.Instructions.Remove(pop); } - EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); + finally { root.Body.Instructions.Remove(access); root.Body.Instructions.Remove(value); } } - finally { root.Body.Instructions.Remove(access); root.Body.Instructions.Remove(value); } } + finally { application.Types.Remove(helper); } + EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); } - finally { application.Types.Remove(helper); } - EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); } [Fact] @@ -555,310 +558,313 @@ public void Background_job_metric_registration_requires_the_actual_singleton_des JobMetricRegistrationOffenders(services).Should().BeEmpty(); } - [Fact] - public void Background_job_metric_census_rejects_bait_callbacks_hidden_registration_and_skipped_binding() + public sealed partial class JobMetricMutationTests { - using var census = ProductionCensus.Read(); - var baselineOffenders = EvaluateDetector(census, RuntimeLifetimeOffenders); - baselineOffenders.Should().BeEmpty("complete baseline offenders: {0}", string.Join("\n", baselineOffenders)); - var observation = census.Types[(InfrastructureAssembly, JobObservation)]; - var ctor = observation.Methods.Single(method => method.IsConstructor && !method.IsStatic); - var gauge = ctor.Body.Instructions.First(instruction => instruction.Operand is MethodReference method - && method.DeclaringType.FullName == "System.Diagnostics.Metrics.Meter" && method.Name == "CreateObservableGauge"); - var original = ctor.Body.Instructions.Skip(ctor.Body.Instructions.IndexOf(gauge) - 8).Take(9).ToArray(); - AssertMutation(census, "an extra UpDownCounter outside the approved observable inventory", () => - { - var upDown = typeof(System.Diagnostics.Metrics.Meter).GetMethods().Single(method => method.Name == "CreateObservableUpDownCounter" - && method.IsGenericMethodDefinition && method.GetParameters().Length == 4 - && method.GetParameters()[1].ParameterType.GetGenericArguments()[0] is { IsGenericType: true } result - && result.GetGenericTypeDefinition() == typeof(IEnumerable<>)).MakeGenericMethod(typeof(long)); - var extra = original.Select(instruction => + [Fact] + public void Background_job_metric_census_rejects_bait_callbacks_hidden_registration_and_skipped_binding() + { + using var census = ProductionCensus.Read(); + var baselineOffenders = EvaluateDetector(census, RuntimeLifetimeOffenders); + baselineOffenders.Should().BeEmpty("complete baseline offenders: {0}", string.Join("\n", baselineOffenders)); + var observation = census.Types[(InfrastructureAssembly, JobObservation)]; + var ctor = observation.Methods.Single(method => method.IsConstructor && !method.IsStatic); + var gauge = ctor.Body.Instructions.First(instruction => instruction.Operand is MethodReference method + && method.DeclaringType.FullName == "System.Diagnostics.Metrics.Meter" && method.Name == "CreateObservableGauge"); + var original = ctor.Body.Instructions.Skip(ctor.Body.Instructions.IndexOf(gauge) - 8).Take(9).ToArray(); + AssertMutation(census, "an extra UpDownCounter outside the approved observable inventory", () => { - var clone = Instruction.Create(OpCodes.Nop); - clone.OpCode = instruction.OpCode; - clone.Operand = instruction.Operand; - return clone; - }).Append(Instruction.Create(OpCodes.Pop)).ToArray(); - extra[2].Operand = "learnstack_job_unapproved"; - extra[8].Operand = ctor.Module.ImportReference(upDown); - foreach (var instruction in extra) ctor.Body.Instructions.Insert(ctor.Body.Instructions.Count - 1, instruction); - return () => { foreach (var instruction in extra) ctor.Body.Instructions.Remove(instruction); }; - }, RuntimeLifetimeOffenders); - var actualName = original[2]; - AssertMutation(census, "an unused correct instrument name followed by the actual foreign name", () => - { - var bait = Instruction.Create(OpCodes.Ldstr, (string)actualName.Operand); - var pop = Instruction.Create(OpCodes.Pop); - ctor.Body.Instructions.Insert(ctor.Body.Instructions.IndexOf(actualName), bait); - ctor.Body.Instructions.Insert(ctor.Body.Instructions.IndexOf(actualName), pop); - var old = actualName.Operand; - actualName.Operand = "learnstack_job_unapproved"; - return () => { actualName.Operand = old; ctor.Body.Instructions.Remove(bait); ctor.Body.Instructions.Remove(pop); }; - }, RuntimeLifetimeOffenders); - AssertMutation(census, "an unused correct delegate followed by an actual factory-supplied callback", () => - { - var factory = new MethodDefinition("CreateCallback", MethodAttributes.Private | MethodAttributes.Static, - ((MethodReference)original[5].Operand).DeclaringType); - factory.Parameters.Add(new(observation)); - factory.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); - factory.Body.Instructions.Add(Instruction.Create(OpCodes.Ldftn, (MethodReference)original[4].Operand)); - factory.Body.Instructions.Add(Instruction.Create(OpCodes.Newobj, (MethodReference)original[5].Operand)); - factory.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); - observation.Methods.Add(factory); - var bait = new[] - { - Instruction.Create(OpCodes.Ldarg_0), Instruction.Create(OpCodes.Ldftn, (MethodReference)original[4].Operand), - Instruction.Create(OpCodes.Newobj, (MethodReference)original[5].Operand), Instruction.Create(OpCodes.Pop), - }; - foreach (var instruction in bait) ctor.Body.Instructions.Insert(ctor.Body.Instructions.IndexOf(original[0]), instruction); - var pointer = original[4].Operand; - var delegateConstructor = original[5].Operand; - original[4].OpCode = OpCodes.Call; - original[4].Operand = factory; - original[5].OpCode = OpCodes.Nop; - original[5].Operand = null; - return () => - { - original[4].OpCode = OpCodes.Ldftn; original[4].Operand = pointer; - original[5].OpCode = OpCodes.Newobj; original[5].Operand = delegateConstructor; - foreach (var instruction in bait) ctor.Body.Instructions.Remove(instruction); - observation.Methods.Remove(factory); - }; - }, RuntimeLifetimeOffenders); - AssertMutation(census, "an observer helper that creates its own named Meter without reading the owned field", () => - { - var registrar = new MethodDefinition("RegisterOwnMeter", MethodAttributes.Private | MethodAttributes.Static, ctor.Module.TypeSystem.Void); - registrar.Body.Instructions.Add(Instruction.Create(OpCodes.Ldstr, "learnstack.jobs")); - registrar.Body.Instructions.Add(Instruction.Create(OpCodes.Ldnull)); - registrar.Body.Instructions.Add(Instruction.Create(OpCodes.Newobj, ctor.Module.ImportReference( - typeof(System.Diagnostics.Metrics.Meter).GetConstructor([typeof(string), typeof(string)])!))); - registrar.Body.Instructions.Add(Instruction.Create(OpCodes.Pop)); - registrar.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); - observation.Methods.Add(registrar); - var call = Instruction.Create(OpCodes.Call, registrar); - ctor.Body.Instructions.Insert(ctor.Body.Instructions.Count - 1, call); - return () => { ctor.Body.Instructions.Remove(call); observation.Methods.Remove(registrar); }; - }, RuntimeLifetimeOffenders); - var application = census.Modules.Single(module => module.Assembly.Name.Name == DeliveryApplication); - var holder = AddProbe(application, "MetricRegistrationStaticHolder"); - var marker = new FieldDefinition("Marker", FieldAttributes.Public | FieldAttributes.Static, application.TypeSystem.Int64); - holder.Fields.Add(marker); - var initializer = new MethodDefinition(".cctor", MethodAttributes.Private | MethodAttributes.Static - | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, application.TypeSystem.Void); - initializer.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); - holder.Methods.Add(initializer); - var markerRead = Instruction.Create(OpCodes.Ldsfld, ctor.Module.ImportReference(marker)); - var markerPop = Instruction.Create(OpCodes.Pop); - ctor.Body.Instructions.Insert(0, markerPop); - ctor.Body.Instructions.Insert(0, markerRead); - try - { - EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); - AssertMutation(census, "an observer constructor whose static marker initializes a second Meter", () => + var upDown = typeof(System.Diagnostics.Metrics.Meter).GetMethods().Single(method => method.Name == "CreateObservableUpDownCounter" + && method.IsGenericMethodDefinition && method.GetParameters().Length == 4 + && method.GetParameters()[1].ParameterType.GetGenericArguments()[0] is { IsGenericType: true } result + && result.GetGenericTypeDefinition() == typeof(IEnumerable<>)).MakeGenericMethod(typeof(long)); + var extra = original.Select(instruction => + { + var clone = Instruction.Create(OpCodes.Nop); + clone.OpCode = instruction.OpCode; + clone.Operand = instruction.Operand; + return clone; + }).Append(Instruction.Create(OpCodes.Pop)).ToArray(); + extra[2].Operand = "learnstack_job_unapproved"; + extra[8].Operand = ctor.Module.ImportReference(upDown); + foreach (var instruction in extra) ctor.Body.Instructions.Insert(ctor.Body.Instructions.Count - 1, instruction); + return () => { foreach (var instruction in extra) ctor.Body.Instructions.Remove(instruction); }; + }, RuntimeLifetimeOffenders); + var actualName = original[2]; + AssertMutation(census, "an unused correct instrument name followed by the actual foreign name", () => + { + var bait = Instruction.Create(OpCodes.Ldstr, (string)actualName.Operand); + var pop = Instruction.Create(OpCodes.Pop); + ctor.Body.Instructions.Insert(ctor.Body.Instructions.IndexOf(actualName), bait); + ctor.Body.Instructions.Insert(ctor.Body.Instructions.IndexOf(actualName), pop); + var old = actualName.Operand; + actualName.Operand = "learnstack_job_unapproved"; + return () => { actualName.Operand = old; ctor.Body.Instructions.Remove(bait); ctor.Body.Instructions.Remove(pop); }; + }, RuntimeLifetimeOffenders); + AssertMutation(census, "an unused correct delegate followed by an actual factory-supplied callback", () => + { + var factory = new MethodDefinition("CreateCallback", MethodAttributes.Private | MethodAttributes.Static, + ((MethodReference)original[5].Operand).DeclaringType); + factory.Parameters.Add(new(observation)); + factory.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); + factory.Body.Instructions.Add(Instruction.Create(OpCodes.Ldftn, (MethodReference)original[4].Operand)); + factory.Body.Instructions.Add(Instruction.Create(OpCodes.Newobj, (MethodReference)original[5].Operand)); + factory.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + observation.Methods.Add(factory); + var bait = new[] + { + Instruction.Create(OpCodes.Ldarg_0), Instruction.Create(OpCodes.Ldftn, (MethodReference)original[4].Operand), + Instruction.Create(OpCodes.Newobj, (MethodReference)original[5].Operand), Instruction.Create(OpCodes.Pop), + }; + foreach (var instruction in bait) ctor.Body.Instructions.Insert(ctor.Body.Instructions.IndexOf(original[0]), instruction); + var pointer = original[4].Operand; + var delegateConstructor = original[5].Operand; + original[4].OpCode = OpCodes.Call; + original[4].Operand = factory; + original[5].OpCode = OpCodes.Nop; + original[5].Operand = null; + return () => + { + original[4].OpCode = OpCodes.Ldftn; original[4].Operand = pointer; + original[5].OpCode = OpCodes.Newobj; original[5].Operand = delegateConstructor; + foreach (var instruction in bait) ctor.Body.Instructions.Remove(instruction); + observation.Methods.Remove(factory); + }; + }, RuntimeLifetimeOffenders); + AssertMutation(census, "an observer helper that creates its own named Meter without reading the owned field", () => + { + var registrar = new MethodDefinition("RegisterOwnMeter", MethodAttributes.Private | MethodAttributes.Static, ctor.Module.TypeSystem.Void); + registrar.Body.Instructions.Add(Instruction.Create(OpCodes.Ldstr, "learnstack.jobs")); + registrar.Body.Instructions.Add(Instruction.Create(OpCodes.Ldnull)); + registrar.Body.Instructions.Add(Instruction.Create(OpCodes.Newobj, ctor.Module.ImportReference( + typeof(System.Diagnostics.Metrics.Meter).GetConstructor([typeof(string), typeof(string)])!))); + registrar.Body.Instructions.Add(Instruction.Create(OpCodes.Pop)); + registrar.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + observation.Methods.Add(registrar); + var call = Instruction.Create(OpCodes.Call, registrar); + ctor.Body.Instructions.Insert(ctor.Body.Instructions.Count - 1, call); + return () => { ctor.Body.Instructions.Remove(call); observation.Methods.Remove(registrar); }; + }, RuntimeLifetimeOffenders); + var application = census.Modules.Single(module => module.Assembly.Name.Name == DeliveryApplication); + var holder = AddProbe(application, "MetricRegistrationStaticHolder"); + var marker = new FieldDefinition("Marker", FieldAttributes.Public | FieldAttributes.Static, application.TypeSystem.Int64); + holder.Fields.Add(marker); + var initializer = new MethodDefinition(".cctor", MethodAttributes.Private | MethodAttributes.Static + | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, application.TypeSystem.Void); + initializer.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + holder.Methods.Add(initializer); + var markerRead = Instruction.Create(OpCodes.Ldsfld, ctor.Module.ImportReference(marker)); + var markerPop = Instruction.Create(OpCodes.Pop); + ctor.Body.Instructions.Insert(0, markerPop); + ctor.Body.Instructions.Insert(0, markerRead); + try + { + EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); + AssertMutation(census, "an observer constructor whose static marker initializes a second Meter", () => + { + var instructions = new[] + { + Instruction.Create(OpCodes.Ldstr, "learnstack.jobs"), Instruction.Create(OpCodes.Ldnull), + Instruction.Create(OpCodes.Newobj, application.ImportReference( + typeof(System.Diagnostics.Metrics.Meter).GetConstructor([typeof(string), typeof(string)])!)), + Instruction.Create(OpCodes.Pop), + }; + for (var index = 0; index < instructions.Length; index++) initializer.Body.Instructions.Insert(index, instructions[index]); + return () => { foreach (var instruction in instructions) initializer.Body.Instructions.Remove(instruction); }; + }, RuntimeLifetimeOffenders); + EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); + } + finally { ctor.Body.Instructions.Remove(markerRead); ctor.Body.Instructions.Remove(markerPop); application.Types.Remove(holder); } + var actualInitializer = observation.Methods.Single(method => method.IsConstructor && method.IsStatic); + AssertMutation(census, "a hidden Meter registered in the actual observer static constructor", () => { var instructions = new[] { Instruction.Create(OpCodes.Ldstr, "learnstack.jobs"), Instruction.Create(OpCodes.Ldnull), - Instruction.Create(OpCodes.Newobj, application.ImportReference( + Instruction.Create(OpCodes.Newobj, actualInitializer.Module.ImportReference( typeof(System.Diagnostics.Metrics.Meter).GetConstructor([typeof(string), typeof(string)])!)), Instruction.Create(OpCodes.Pop), }; - for (var index = 0; index < instructions.Length; index++) initializer.Body.Instructions.Insert(index, instructions[index]); - return () => { foreach (var instruction in instructions) initializer.Body.Instructions.Remove(instruction); }; + for (var index = 0; index < instructions.Length; index++) actualInitializer.Body.Instructions.Insert(index, instructions[index]); + return () => { foreach (var instruction in instructions) actualInitializer.Body.Instructions.Remove(instruction); }; + }, RuntimeLifetimeOffenders); + var hidden = new MethodDefinition("RegisterHidden", MethodAttributes.Private, ctor.Module.TypeSystem.Void); + foreach (var instruction in original) + { + var clone = Instruction.Create(OpCodes.Nop); + clone.OpCode = instruction.OpCode; + clone.Operand = instruction.Operand; + hidden.Body.Instructions.Add(clone); + } + hidden.Body.Instructions.Add(Instruction.Create(OpCodes.Pop)); + hidden.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + AssertMutation(census, "a second observable registration moved behind an owner helper", () => + { + observation.Methods.Add(hidden); + var receiver = Instruction.Create(OpCodes.Ldarg_0); + var call = Instruction.Create(OpCodes.Call, hidden); + ctor.Body.Instructions.Insert(ctor.Body.Instructions.Count - 1, receiver); + ctor.Body.Instructions.Insert(ctor.Body.Instructions.Count - 1, call); + return () => { ctor.Body.Instructions.Remove(receiver); ctor.Body.Instructions.Remove(call); observation.Methods.Remove(hidden); }; + }, RuntimeLifetimeOffenders); + var executor = census.Types[(InfrastructureAssembly, JobExecutorType)]; + var execution = census.Types[(InfrastructureAssembly, OrchestrationExecution)]; + var leaseRecorder = execution.Methods.Single(method => method.Name == "ObserveLeaseLoss"); + AssertMutation(census, "a balanced removal of the first-loss CompareExchange gate", () => + { + var compare = leaseRecorder.Body.Instructions.Single(instruction => instruction.Operand is MethodReference target + && target.Name == "CompareExchange" && target.DeclaringType.FullName == "System.Threading.Interlocked"); + var original = compare.Operand; + compare.OpCode = OpCodes.Pop; + compare.Operand = null; + var replacements = new[] { Instruction.Create(OpCodes.Pop), Instruction.Create(OpCodes.Pop), Instruction.Create(OpCodes.Ldc_I4_0) }; + for (var index = 0; index < replacements.Length; index++) + leaseRecorder.Body.Instructions.Insert(leaseRecorder.Body.Instructions.IndexOf(compare) + 1 + index, replacements[index]); + return () => + { + compare.OpCode = OpCodes.Call; compare.Operand = original; + foreach (var instruction in replacements) leaseRecorder.Body.Instructions.Remove(instruction); + }; + }, RuntimeLifetimeOffenders); + AssertMutation(census, "a constructor-unrelated acknowledged lease eligibility writer", () => + { + var extra = new MethodDefinition("InventLeaseEligibility", MethodAttributes.Private, execution.Module.TypeSystem.Void); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4_1)); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Stfld, execution.Fields.Single(field => field.Name == "_leaseObservationEligible"))); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + execution.Methods.Add(extra); + return () => execution.Methods.Remove(extra); + }, RuntimeLifetimeOffenders); + AssertMutation(census, "an unlisted direct persistent lease-loss recorder caller", () => + { + var parent = census.Types[(InfrastructureAssembly, OrchestrationControl)]; + var extra = new MethodDefinition("InventPersistentLeaseLoss", MethodAttributes.Private, parent.Module.TypeSystem.Void); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4_2)); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Call, parent.Methods.Single(method => method.Name == "ObserveLeaseLoss"))); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + parent.Methods.Add(extra); + return () => parent.Methods.Remove(extra); + }, RuntimeLifetimeOffenders); + var bridge = census.Types[(InfrastructureAssembly, JobBridge)]; + foreach (var fieldName in new[] { "_priorHintRepairs", "_expiredTokenRepairs" }) + AssertMutation(census, "an unlisted bridge repair field reader " + fieldName, + () => AddBoundaryFieldGetter(bridge, "ReadRepairOutsideSnapshot", fieldName), RuntimeLifetimeOffenders); + var bridgeClaim = census.Types[(InfrastructureAssembly, JobBridgeClaim)]; + AssertMutation(census, "a mutable original bridge claim classification", () => + { + var classification = bridgeClaim.Fields.Single(field => field.Name == "k__BackingField"); + classification.IsInitOnly = false; + return () => classification.IsInitOnly = true; + }, RuntimeLifetimeOffenders); + var field = executor.Fields.Single(candidate => candidate.Name == "k__BackingField"); + AssertMutation(census, "removing required observer readonly metadata", () => + { + field.IsInitOnly = false; + return () => field.IsInitOnly = true; + }, RuntimeLifetimeOffenders); + var runtimeCtor = census.Types[(InfrastructureAssembly, JobRuntime)].Methods.Single(method => MethodId(method) == RuntimeConstructorId); + var bind = runtimeCtor.Body.Instructions.Single(instruction => instruction.Operand is MethodReference method + && method.DeclaringType.FullName == JobObservation && method.Name == "Bind"); + AssertMutation(census, "a captured Bind method group without invoking the required binding", () => + { + var arguments = runtimeCtor.Body.Instructions.Skip(runtimeCtor.Body.Instructions.IndexOf(bind) - 3).Take(3).ToArray(); + var oldArguments = arguments.Select(instruction => (instruction.OpCode, instruction.Operand)).ToArray(); + foreach (var argument in arguments) { argument.OpCode = OpCodes.Nop; argument.Operand = null; } + var target = bind.Operand; + bind.OpCode = OpCodes.Ldftn; + var create = Instruction.Create(OpCodes.Newobj, runtimeCtor.Module.ImportReference( + typeof(Action).GetConstructor([typeof(object), typeof(IntPtr)])!)); + var pop = Instruction.Create(OpCodes.Pop); + runtimeCtor.Body.Instructions.Insert(runtimeCtor.Body.Instructions.IndexOf(bind) + 1, create); + runtimeCtor.Body.Instructions.Insert(runtimeCtor.Body.Instructions.IndexOf(create) + 1, pop); + return () => + { + for (var index = 0; index < arguments.Length; index++) + { arguments[index].OpCode = oldArguments[index].OpCode; arguments[index].Operand = oldArguments[index].Operand; } + bind.OpCode = OpCodes.Callvirt; bind.Operand = target; + runtimeCtor.Body.Instructions.Remove(create); runtimeCtor.Body.Instructions.Remove(pop); + }; + }, RuntimeLifetimeOffenders); + AssertMutation(census, "an initial-state false branch that skips binding but still pins both sources", () => + { + var entry = runtimeCtor.Body.Instructions[runtimeCtor.Body.Instructions.IndexOf(bind) - 6]; + var old = (entry.OpCode, entry.Operand); + // Both suppression-flow paths branch to this original instruction. + // Inserting a prefix before it would leave the dirty branch unreachable. + entry.OpCode = OpCodes.Ldc_I4_0; + entry.Operand = null; + var skip = Instruction.Create(OpCodes.Brfalse, bind.Next!); + var receiver = Instruction.Create(OpCodes.Ldarg_0); + runtimeCtor.Body.Instructions.Insert(runtimeCtor.Body.Instructions.IndexOf(entry) + 1, skip); + runtimeCtor.Body.Instructions.Insert(runtimeCtor.Body.Instructions.IndexOf(skip) + 1, receiver); + return () => + { + entry.OpCode = old.OpCode; entry.Operand = old.Operand; + runtimeCtor.Body.Instructions.Remove(skip); runtimeCtor.Body.Instructions.Remove(receiver); + }; + }, RuntimeLifetimeOffenders); + var histogram = ctor.Body.Instructions.Single(instruction => instruction.Operand is MethodReference method + && method.DeclaringType.FullName == "System.Diagnostics.Metrics.Meter" && method.Name == "CreateHistogram"); + AssertMutation(census, "a duration histogram whose emitted unit silently changes to milliseconds", () => + { + var unit = ctor.Body.Instructions[ctor.Body.Instructions.IndexOf(histogram) - 4]; + unit.OpCode.Should().Be(OpCodes.Ldstr); + unit.Operand.Should().Be("s"); + unit.Operand = "ms"; + return () => unit.Operand = "s"; }, RuntimeLifetimeOffenders); - EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); - } - finally { ctor.Body.Instructions.Remove(markerRead); ctor.Body.Instructions.Remove(markerPop); application.Types.Remove(holder); } - var actualInitializer = observation.Methods.Single(method => method.IsConstructor && method.IsStatic); - AssertMutation(census, "a hidden Meter registered in the actual observer static constructor", () => - { - var instructions = new[] - { - Instruction.Create(OpCodes.Ldstr, "learnstack.jobs"), Instruction.Create(OpCodes.Ldnull), - Instruction.Create(OpCodes.Newobj, actualInitializer.Module.ImportReference( - typeof(System.Diagnostics.Metrics.Meter).GetConstructor([typeof(string), typeof(string)])!)), - Instruction.Create(OpCodes.Pop), - }; - for (var index = 0; index < instructions.Length; index++) actualInitializer.Body.Instructions.Insert(index, instructions[index]); - return () => { foreach (var instruction in instructions) actualInitializer.Body.Instructions.Remove(instruction); }; - }, RuntimeLifetimeOffenders); - var hidden = new MethodDefinition("RegisterHidden", MethodAttributes.Private, ctor.Module.TypeSystem.Void); - foreach (var instruction in original) - { - var clone = Instruction.Create(OpCodes.Nop); - clone.OpCode = instruction.OpCode; - clone.Operand = instruction.Operand; - hidden.Body.Instructions.Add(clone); - } - hidden.Body.Instructions.Add(Instruction.Create(OpCodes.Pop)); - hidden.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); - AssertMutation(census, "a second observable registration moved behind an owner helper", () => - { - observation.Methods.Add(hidden); - var receiver = Instruction.Create(OpCodes.Ldarg_0); - var call = Instruction.Create(OpCodes.Call, hidden); - ctor.Body.Instructions.Insert(ctor.Body.Instructions.Count - 1, receiver); - ctor.Body.Instructions.Insert(ctor.Body.Instructions.Count - 1, call); - return () => { ctor.Body.Instructions.Remove(receiver); ctor.Body.Instructions.Remove(call); observation.Methods.Remove(hidden); }; - }, RuntimeLifetimeOffenders); - var executor = census.Types[(InfrastructureAssembly, JobExecutorType)]; - var execution = census.Types[(InfrastructureAssembly, OrchestrationExecution)]; - var leaseRecorder = execution.Methods.Single(method => method.Name == "ObserveLeaseLoss"); - AssertMutation(census, "a balanced removal of the first-loss CompareExchange gate", () => - { - var compare = leaseRecorder.Body.Instructions.Single(instruction => instruction.Operand is MethodReference target - && target.Name == "CompareExchange" && target.DeclaringType.FullName == "System.Threading.Interlocked"); - var original = compare.Operand; - compare.OpCode = OpCodes.Pop; - compare.Operand = null; - var replacements = new[] { Instruction.Create(OpCodes.Pop), Instruction.Create(OpCodes.Pop), Instruction.Create(OpCodes.Ldc_I4_0) }; - for (var index = 0; index < replacements.Length; index++) - leaseRecorder.Body.Instructions.Insert(leaseRecorder.Body.Instructions.IndexOf(compare) + 1 + index, replacements[index]); - return () => - { - compare.OpCode = OpCodes.Call; compare.Operand = original; - foreach (var instruction in replacements) leaseRecorder.Body.Instructions.Remove(instruction); - }; - }, RuntimeLifetimeOffenders); - AssertMutation(census, "a constructor-unrelated acknowledged lease eligibility writer", () => - { - var extra = new MethodDefinition("InventLeaseEligibility", MethodAttributes.Private, execution.Module.TypeSystem.Void); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4_1)); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Stfld, execution.Fields.Single(field => field.Name == "_leaseObservationEligible"))); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); - execution.Methods.Add(extra); - return () => execution.Methods.Remove(extra); - }, RuntimeLifetimeOffenders); - AssertMutation(census, "an unlisted direct persistent lease-loss recorder caller", () => - { - var parent = census.Types[(InfrastructureAssembly, OrchestrationControl)]; - var extra = new MethodDefinition("InventPersistentLeaseLoss", MethodAttributes.Private, parent.Module.TypeSystem.Void); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0)); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4_2)); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Call, parent.Methods.Single(method => method.Name == "ObserveLeaseLoss"))); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); - parent.Methods.Add(extra); - return () => parent.Methods.Remove(extra); - }, RuntimeLifetimeOffenders); - var bridge = census.Types[(InfrastructureAssembly, JobBridge)]; - foreach (var fieldName in new[] { "_priorHintRepairs", "_expiredTokenRepairs" }) - AssertMutation(census, "an unlisted bridge repair field reader " + fieldName, - () => AddBoundaryFieldGetter(bridge, "ReadRepairOutsideSnapshot", fieldName), RuntimeLifetimeOffenders); - var bridgeClaim = census.Types[(InfrastructureAssembly, JobBridgeClaim)]; - AssertMutation(census, "a mutable original bridge claim classification", () => - { - var classification = bridgeClaim.Fields.Single(field => field.Name == "k__BackingField"); - classification.IsInitOnly = false; - return () => classification.IsInitOnly = true; - }, RuntimeLifetimeOffenders); - var field = executor.Fields.Single(candidate => candidate.Name == "k__BackingField"); - AssertMutation(census, "removing required observer readonly metadata", () => - { - field.IsInitOnly = false; - return () => field.IsInitOnly = true; - }, RuntimeLifetimeOffenders); - var runtimeCtor = census.Types[(InfrastructureAssembly, JobRuntime)].Methods.Single(method => MethodId(method) == RuntimeConstructorId); - var bind = runtimeCtor.Body.Instructions.Single(instruction => instruction.Operand is MethodReference method - && method.DeclaringType.FullName == JobObservation && method.Name == "Bind"); - AssertMutation(census, "a captured Bind method group without invoking the required binding", () => - { - var arguments = runtimeCtor.Body.Instructions.Skip(runtimeCtor.Body.Instructions.IndexOf(bind) - 3).Take(3).ToArray(); - var oldArguments = arguments.Select(instruction => (instruction.OpCode, instruction.Operand)).ToArray(); - foreach (var argument in arguments) { argument.OpCode = OpCodes.Nop; argument.Operand = null; } - var target = bind.Operand; - bind.OpCode = OpCodes.Ldftn; - var create = Instruction.Create(OpCodes.Newobj, runtimeCtor.Module.ImportReference( - typeof(Action).GetConstructor([typeof(object), typeof(IntPtr)])!)); - var pop = Instruction.Create(OpCodes.Pop); - runtimeCtor.Body.Instructions.Insert(runtimeCtor.Body.Instructions.IndexOf(bind) + 1, create); - runtimeCtor.Body.Instructions.Insert(runtimeCtor.Body.Instructions.IndexOf(create) + 1, pop); - return () => - { - for (var index = 0; index < arguments.Length; index++) - { arguments[index].OpCode = oldArguments[index].OpCode; arguments[index].Operand = oldArguments[index].Operand; } - bind.OpCode = OpCodes.Callvirt; bind.Operand = target; - runtimeCtor.Body.Instructions.Remove(create); runtimeCtor.Body.Instructions.Remove(pop); - }; - }, RuntimeLifetimeOffenders); - AssertMutation(census, "an initial-state false branch that skips binding but still pins both sources", () => - { - var entry = runtimeCtor.Body.Instructions[runtimeCtor.Body.Instructions.IndexOf(bind) - 6]; - var old = (entry.OpCode, entry.Operand); - // Both suppression-flow paths branch to this original instruction. - // Inserting a prefix before it would leave the dirty branch unreachable. - entry.OpCode = OpCodes.Ldc_I4_0; - entry.Operand = null; - var skip = Instruction.Create(OpCodes.Brfalse, bind.Next!); - var receiver = Instruction.Create(OpCodes.Ldarg_0); - runtimeCtor.Body.Instructions.Insert(runtimeCtor.Body.Instructions.IndexOf(entry) + 1, skip); - runtimeCtor.Body.Instructions.Insert(runtimeCtor.Body.Instructions.IndexOf(skip) + 1, receiver); - return () => - { - entry.OpCode = old.OpCode; entry.Operand = old.Operand; - runtimeCtor.Body.Instructions.Remove(skip); runtimeCtor.Body.Instructions.Remove(receiver); - }; - }, RuntimeLifetimeOffenders); - var histogram = ctor.Body.Instructions.Single(instruction => instruction.Operand is MethodReference method - && method.DeclaringType.FullName == "System.Diagnostics.Metrics.Meter" && method.Name == "CreateHistogram"); - AssertMutation(census, "a duration histogram whose emitted unit silently changes to milliseconds", () => - { - var unit = ctor.Body.Instructions[ctor.Body.Instructions.IndexOf(histogram) - 4]; - unit.OpCode.Should().Be(OpCodes.Ldstr); - unit.Operand.Should().Be("s"); - unit.Operand = "ms"; - return () => unit.Operand = "s"; - }, RuntimeLifetimeOffenders); - - var executorBody = OwnedBodies(census).Single(item => item.Owner.DeclaringType == executor - && item.Owner.Name == "ExecutePublishedAsync" && item.Body.Body.Instructions.Any(instruction => - instruction.Operand is MethodReference method && method.DeclaringType.FullName == JobObservation && method.Name == "StartStage")).Body; - var start = executorBody.Body.Instructions.Single(instruction => instruction.Operand is MethodReference method - && method.DeclaringType.FullName == JobObservation && method.Name == "StartStage"); - AssertMutation(census, "an unused StartStage method group replacing the actual timing call", () => - { - var local = new VariableDefinition(executorBody.Module.ImportReference(typeof(long?))); - var initialized = executorBody.Body.InitLocals; - executorBody.Body.InitLocals = true; - executorBody.Body.Variables.Add(local); - start.OpCode = OpCodes.Ldftn; - var replacements = new[] - { - Instruction.Create(OpCodes.Newobj, executorBody.Module.ImportReference( - typeof(Func).GetConstructor([typeof(object), typeof(IntPtr)])!)), - Instruction.Create(OpCodes.Pop), Instruction.Create(OpCodes.Ldloca, local), - Instruction.Create(OpCodes.Initobj, local.VariableType), Instruction.Create(OpCodes.Ldloc, local), - }; - for (var index = 0; index < replacements.Length; index++) - executorBody.Body.Instructions.Insert(executorBody.Body.Instructions.IndexOf(start) + 1 + index, replacements[index]); - return () => - { - start.OpCode = OpCodes.Callvirt; - foreach (var instruction in replacements) executorBody.Body.Instructions.Remove(instruction); - executorBody.Body.Variables.Remove(local); - executorBody.Body.InitLocals = initialized; - }; - }, RuntimeLifetimeOffenders); - foreach (var method in observation.Methods.Where(method => method.Name is "StartStage" or "RecordStage")) - { - EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); - var instructions = new[] + var executorBody = OwnedBodies(census).Single(item => item.Owner.DeclaringType == executor + && item.Owner.Name == "ExecutePublishedAsync" && item.Body.Body.Instructions.Any(instruction => + instruction.Operand is MethodReference method && method.DeclaringType.FullName == JobObservation && method.Name == "StartStage")).Body; + var start = executorBody.Body.Instructions.Single(instruction => instruction.Operand is MethodReference method + && method.DeclaringType.FullName == JobObservation && method.Name == "StartStage"); + AssertMutation(census, "an unused StartStage method group replacing the actual timing call", () => { - Instruction.Create(OpCodes.Newobj, method.Module.ImportReference(typeof(Npgsql.NpgsqlCommand).GetConstructor(Type.EmptyTypes)!)), - Instruction.Create(OpCodes.Pop), - }; - method.Body.Instructions.Insert(0, instructions[1]); - method.Body.Instructions.Insert(0, instructions[0]); - try + var local = new VariableDefinition(executorBody.Module.ImportReference(typeof(long?))); + var initialized = executorBody.Body.InitLocals; + executorBody.Body.InitLocals = true; + executorBody.Body.Variables.Add(local); + start.OpCode = OpCodes.Ldftn; + var replacements = new[] + { + Instruction.Create(OpCodes.Newobj, executorBody.Module.ImportReference( + typeof(Func).GetConstructor([typeof(object), typeof(IntPtr)])!)), + Instruction.Create(OpCodes.Pop), Instruction.Create(OpCodes.Ldloca, local), + Instruction.Create(OpCodes.Initobj, local.VariableType), Instruction.Create(OpCodes.Ldloc, local), + }; + for (var index = 0; index < replacements.Length; index++) + executorBody.Body.Instructions.Insert(executorBody.Body.Instructions.IndexOf(start) + 1 + index, replacements[index]); + return () => + { + start.OpCode = OpCodes.Callvirt; + foreach (var instruction in replacements) executorBody.Body.Instructions.Remove(instruction); + executorBody.Body.Variables.Remove(local); + executorBody.Body.InitLocals = initialized; + }; + }, RuntimeLifetimeOffenders); + + foreach (var method in observation.Methods.Where(method => method.Name is "StartStage" or "RecordStage")) { - EvaluateDetector(census, RuntimeLifetimeOffenders).Should().Contain(value => - value.Contains("job stage metrics observation reaches persistence/provider activation", StringComparison.Ordinal), - "each actual synchronous stage root must be independently selected by the memory walk"); + EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); + var instructions = new[] + { + Instruction.Create(OpCodes.Newobj, method.Module.ImportReference(typeof(Npgsql.NpgsqlCommand).GetConstructor(Type.EmptyTypes)!)), + Instruction.Create(OpCodes.Pop), + }; + method.Body.Instructions.Insert(0, instructions[1]); + method.Body.Instructions.Insert(0, instructions[0]); + try + { + EvaluateDetector(census, RuntimeLifetimeOffenders).Should().Contain(value => + value.Contains("job stage metrics observation reaches persistence/provider activation", StringComparison.Ordinal), + "each actual synchronous stage root must be independently selected by the memory walk"); + } + finally { foreach (var instruction in instructions) method.Body.Instructions.Remove(instruction); } + EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); } - finally { foreach (var instruction in instructions) method.Body.Instructions.Remove(instruction); } EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); } - EvaluateDetector(census, RuntimeLifetimeOffenders).Should().BeEmpty(); } } diff --git a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobOrchestrationBoundaryTests.Retention.cs b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobOrchestrationBoundaryTests.Retention.cs index f48740137..57971f200 100644 --- a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobOrchestrationBoundaryTests.Retention.cs +++ b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobOrchestrationBoundaryTests.Retention.cs @@ -135,7 +135,7 @@ private static void CheckTerminalPrivilegedAwaits(ProductionCensus census, Sorte && census.Types.TryGetValue(Key(state), out var owner) ? owner : null; } - public sealed partial class JobExecutionMutationTests + public sealed class JobOrchestrationMutationTests { [Fact] diff --git a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobOrchestrationBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobOrchestrationBoundaryTests.cs index 161aad09f..e5d16d801 100644 --- a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobOrchestrationBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobOrchestrationBoundaryTests.cs @@ -508,71 +508,74 @@ private static string OrchestrationFieldType(string type, string name) _ => null, }; - [Fact] - public void Background_job_orchestration_has_closed_finite_owners_and_rejects_extra_callers_and_lost_retention() + public sealed class JobOrchestrationDeclarationMutationTests { - using var census = ProductionCensus.Read(); - var baseline = EvaluateDetector(census, JobOrchestrationOffenders); - baseline.Should().BeEmpty("the exact orchestration manifest must match; offenders: {0}", - string.Join(Environment.NewLine, baseline)); - var application = census.Modules.Single(module => module.Assembly.Name.Name == DeliveryApplication); - var guarded = new Dictionary + [Fact] + public void Background_job_orchestration_has_closed_finite_owners_and_rejects_extra_callers_and_lost_retention() { - [OrchestrationControl] = [".ctor", "TryBegin", "Release", "Start", "RequestStop", "FinishAdmissionAsync", "FinishBusinessAsync", "RunRenewalAsync", "RunControlAsync", "RunTerminalAsync", "ObserveExternalRetry", "ObserveRequestRetry", "ObserveRequestHistory", "IsRetryTransition"], - [OrchestrationExecution] = [".ctor", "HoldAdmission", "HoldBusiness", "HoldCapacityCheckpoint", "JoinAsync", "JoinBusinessObserversAsync", "JoinBusinessObserversCoreAsync", "ReleaseAfterPrivateCleanup", "ObservePublicationAsync", "ObserveDeadlineAsync", "RecordRenewal", "RefuseRenewal", "CloseExecution", "LeaseElapsed"], - [OrchestrationRenewal] = [".ctor", "Start", "Schedule", "ObserveWaitAsync"], - [OrchestrationIdentity] = [".ctor", "FromReceipt"], - [OrchestrationCheckpoint] = [".ctor", "Start", "Schedule", "RequestStop", "RelayStopAsync", "ObserveActualAsync", "ObserveWaitAsync"], - }; - foreach (var (typeName, methods) in guarded) - { - var type = census.Types[(InfrastructureAssembly, typeName)]; - foreach (var method in type.Methods.Where(method => methods.Contains(method.Name, StringComparer.Ordinal)).ToArray()) + using var census = ProductionCensus.Read(); + var baseline = EvaluateDetector(census, JobOrchestrationOffenders); + baseline.Should().BeEmpty("the exact orchestration manifest must match; offenders: {0}", + string.Join(Environment.NewLine, baseline)); + var application = census.Modules.Single(module => module.Assembly.Name.Name == DeliveryApplication); + var guarded = new Dictionary + { + [OrchestrationControl] = [".ctor", "TryBegin", "Release", "Start", "RequestStop", "FinishAdmissionAsync", "FinishBusinessAsync", "RunRenewalAsync", "RunControlAsync", "RunTerminalAsync", "ObserveExternalRetry", "ObserveRequestRetry", "ObserveRequestHistory", "IsRetryTransition"], + [OrchestrationExecution] = [".ctor", "HoldAdmission", "HoldBusiness", "HoldCapacityCheckpoint", "JoinAsync", "JoinBusinessObserversAsync", "JoinBusinessObserversCoreAsync", "ReleaseAfterPrivateCleanup", "ObservePublicationAsync", "ObserveDeadlineAsync", "RecordRenewal", "RefuseRenewal", "CloseExecution", "LeaseElapsed"], + [OrchestrationRenewal] = [".ctor", "Start", "Schedule", "ObserveWaitAsync"], + [OrchestrationIdentity] = [".ctor", "FromReceipt"], + [OrchestrationCheckpoint] = [".ctor", "Start", "Schedule", "RequestStop", "RelayStopAsync", "ObserveActualAsync", "ObserveWaitAsync"], + }; + foreach (var (typeName, methods) in guarded) + { + var type = census.Types[(InfrastructureAssembly, typeName)]; + foreach (var method in type.Methods.Where(method => methods.Contains(method.Name, StringComparer.Ordinal)).ToArray()) + { + foreach (var opcode in new[] { OpCodes.Call, OpCodes.Callvirt, OpCodes.Ldftn, OpCodes.Ldvirtftn }) + AssertMutation(census, "an additional finite orchestration capability through " + opcode, + () => AddCallProbe(application, "OrchestrationEscape", method, opcode), JobOrchestrationOffenders); + AssertMutation(census, "an async orchestration capability escape", + () => AddAsyncCallProbe(application, "AsyncOrchestrationEscape", method), JobOrchestrationOffenders); + } + AssertMutation(census, "a missing concrete orchestration subject", () => + { + var module = type.Module; + module.Types.Remove(type); + return () => module.Types.Add(type); + }, JobOrchestrationOffenders); + } + foreach (var (typeName, field) in new[] { (OrchestrationControl, "_renewalFlight"), (OrchestrationControl, "_controlOperation"), + (OrchestrationControl, "_terminalOperation"), (OrchestrationExecution, "_admission"), + (OrchestrationExecution, "_business"), (OrchestrationExecution, "_leaseTimer"), (OrchestrationExecution, "_capacityCheckpoint"), + (OrchestrationExecution, "_observersPublished"), (OrchestrationRenewal, "_actual"), (OrchestrationCheckpoint, "_actual"), + (OrchestrationCheckpoint, "_private"), (OrchestrationCheckpoint, "_cancellation"), + (OrchestrationInvocation, "_cleanupPublished"), (OrchestrationInvocation, "_cancellationObservation"), + (OrchestrationInvocation, "_admission"), (OrchestrationInvocation, "_business") }) + AssertMutation(census, "an approved owner forwarding a retained orchestration resource", + () => AddBoundaryFieldGetter(census.Types[(InfrastructureAssembly, typeName)], "ForwardOrchestrationResource", field), JobOrchestrationOffenders); + var control = census.Types[(InfrastructureAssembly, OrchestrationControl)]; + foreach (var (methodName, bound) in new[] { ("TryBegin", 64), ("TryBeginRecovery", 64), ("Enqueue", 128) }) { - foreach (var opcode in new[] { OpCodes.Call, OpCodes.Callvirt, OpCodes.Ldftn, OpCodes.Ldvirtftn }) - AssertMutation(census, "an additional finite orchestration capability through " + opcode, - () => AddCallProbe(application, "OrchestrationEscape", method, opcode), JobOrchestrationOffenders); - AssertMutation(census, "an async orchestration capability escape", - () => AddAsyncCallProbe(application, "AsyncOrchestrationEscape", method), JobOrchestrationOffenders); + var instruction = control.Methods.Single(method => method.Name == methodName).Body.Instructions + .Single(instruction => OrchestrationConstant(instruction) == bound); + AssertMutation(census, "an enlarged finite orchestration bound", + () => ReplaceInstruction(instruction, OpCodes.Ldc_I4, bound + 1), JobOrchestrationOffenders); } - AssertMutation(census, "a missing concrete orchestration subject", () => + var renewal = census.Types[(InfrastructureAssembly, OrchestrationRenewal)]; + var start = renewal.Methods.Single(method => method.Name == "Start"); + AssertMutation(census, "an added renewal-start overload", () => { - var module = type.Module; - module.Types.Remove(type); - return () => module.Types.Add(type); + var overload = new MethodDefinition("Start", MethodAttributes.Assembly, renewal.Module.TypeSystem.Void); + overload.Parameters.Add(new ParameterDefinition(renewal.Module.TypeSystem.String)); + overload.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + renewal.Methods.Add(overload); + return () => renewal.Methods.Remove(overload); + }, JobOrchestrationOffenders); + AssertMutation(census, "a missing actual renewal-start seam", () => + { + renewal.Methods.Remove(start); + return () => renewal.Methods.Add(start); }, JobOrchestrationOffenders); } - foreach (var (typeName, field) in new[] { (OrchestrationControl, "_renewalFlight"), (OrchestrationControl, "_controlOperation"), - (OrchestrationControl, "_terminalOperation"), (OrchestrationExecution, "_admission"), - (OrchestrationExecution, "_business"), (OrchestrationExecution, "_leaseTimer"), (OrchestrationExecution, "_capacityCheckpoint"), - (OrchestrationExecution, "_observersPublished"), (OrchestrationRenewal, "_actual"), (OrchestrationCheckpoint, "_actual"), - (OrchestrationCheckpoint, "_private"), (OrchestrationCheckpoint, "_cancellation"), - (OrchestrationInvocation, "_cleanupPublished"), (OrchestrationInvocation, "_cancellationObservation"), - (OrchestrationInvocation, "_admission"), (OrchestrationInvocation, "_business") }) - AssertMutation(census, "an approved owner forwarding a retained orchestration resource", - () => AddBoundaryFieldGetter(census.Types[(InfrastructureAssembly, typeName)], "ForwardOrchestrationResource", field), JobOrchestrationOffenders); - var control = census.Types[(InfrastructureAssembly, OrchestrationControl)]; - foreach (var (methodName, bound) in new[] { ("TryBegin", 64), ("TryBeginRecovery", 64), ("Enqueue", 128) }) - { - var instruction = control.Methods.Single(method => method.Name == methodName).Body.Instructions - .Single(instruction => OrchestrationConstant(instruction) == bound); - AssertMutation(census, "an enlarged finite orchestration bound", - () => ReplaceInstruction(instruction, OpCodes.Ldc_I4, bound + 1), JobOrchestrationOffenders); - } - var renewal = census.Types[(InfrastructureAssembly, OrchestrationRenewal)]; - var start = renewal.Methods.Single(method => method.Name == "Start"); - AssertMutation(census, "an added renewal-start overload", () => - { - var overload = new MethodDefinition("Start", MethodAttributes.Assembly, renewal.Module.TypeSystem.Void); - overload.Parameters.Add(new ParameterDefinition(renewal.Module.TypeSystem.String)); - overload.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); - renewal.Methods.Add(overload); - return () => renewal.Methods.Remove(overload); - }, JobOrchestrationOffenders); - AssertMutation(census, "a missing actual renewal-start seam", () => - { - renewal.Methods.Remove(start); - return () => renewal.Methods.Add(start); - }, JobOrchestrationOffenders); } } diff --git a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobOwnerBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobOwnerBoundaryTests.cs index 495eda9db..8aed086e3 100644 --- a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobOwnerBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobOwnerBoundaryTests.cs @@ -31,7 +31,7 @@ public void BackgroundJob_Completion_Is_Owner_Atomic_And_Fenced() "Fix: retain one exact receipt/unit/root participant and the existing owner-only Complete boundary"); } - public sealed partial class JobExecutionMutationTests + public sealed class JobOwnerMutationTests { [Fact] diff --git a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobRecipientBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobRecipientBoundaryTests.cs index 59598c30b..4c52d1d10 100644 --- a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobRecipientBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobRecipientBoundaryTests.cs @@ -185,7 +185,7 @@ public void Background_job_recipient_history_controls_reject_detached_cleanup_an }, RecipientOffenders); } - public sealed partial class JobLifecycleMutationTests + public sealed class JobRecipientMutationTests { /// ADR-0047: the production detector rejects added, removed, delegated and overloaded authority. diff --git a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobRecurrenceRuntimeBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobRecurrenceRuntimeBoundaryTests.cs index 307aadfc6..6bf083971 100644 --- a/backend/tests/LearnStack.Tests.Architecture/BackgroundJobRecurrenceRuntimeBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/BackgroundJobRecurrenceRuntimeBoundaryTests.cs @@ -25,151 +25,154 @@ public void Background_job_recurrence_runtime_keeps_exact_concrete_capability_ow + string.Join(Environment.NewLine, offenders)); } - /// ADR-0047: nonempty clean/dirty/restored subjects pin actual opcodes and positive joins. - [Theory] - [InlineData("constructor_visibility")] - [InlineData("callback_signature")] - [InlineData("extra_caller")] - [InlineData("foreign_target")] - [InlineData("foreign_cleanup")] - [InlineData("foreign_await")] - [InlineData("delegate_escape")] - [InlineData("parent_join")] - [InlineData("native_stop")] - [InlineData("recipient_cancel_join")] - [InlineData("thread_exit")] - [InlineData("sdk_queue")] - [InlineData("sdk_cron")] - [InlineData("sdk_tick_type")] - [InlineData("sdk_manager")] - [InlineData("sdk_payload")] - [InlineData("sdk_misfire")] - [InlineData("sdk_arity")] - [InlineData("sdk_key_slot")] - [InlineData("sdk_extra_caller")] - [InlineData("sdk_interface_caller")] - [InlineData("sdk_swapped_literals")] - [InlineData("ownership_extra_holder")] - [InlineData("ownership_public_field")] - [InlineData("ownership_published_type")] - [InlineData("ownership_forwarded_field")] - [InlineData("ownership_completion_state")] - [InlineData("ownership_foreign_resource")] - [InlineData("ownership_foreign_generic")] - [InlineData("ownership_forwarded_stop")] - [InlineData("ownership_forwarded_manager")] - [InlineData("memory_wake")] - [InlineData("memory_field")] - [InlineData("memory_helper")] - [InlineData("memory_indirect")] - [InlineData("memory_scheduling")] - [InlineData("memory_tick_type")] - [InlineData("memory_vendor_identity")] - [InlineData("memory_readiness_wait")] - [InlineData("memory_extra_caller")] - [InlineData("exclusion_sql")] - [InlineData("exclusion_typed_array")] - [InlineData("exclusion_clone")] - [InlineData("exclusion_limit")] - [InlineData("exclusion_delegated_binding")] - [InlineData("exclusion_foreign_binding")] - [InlineData("publication_before_start")] - [InlineData("publication_dispose_before_join_ack")] - public void Background_job_recurrence_runtime_controls_reject_changed_authority_and_cleanup(string mutation) + public sealed class JobRecurrenceMutationTests { - using var census = ProductionCensus.Read(); - var types = census.Types; - AssertMutation(census, mutation, () => + /// ADR-0047: nonempty clean/dirty/restored subjects pin actual opcodes and positive joins. + [Theory] + [InlineData("constructor_visibility")] + [InlineData("callback_signature")] + [InlineData("extra_caller")] + [InlineData("foreign_target")] + [InlineData("foreign_cleanup")] + [InlineData("foreign_await")] + [InlineData("delegate_escape")] + [InlineData("parent_join")] + [InlineData("native_stop")] + [InlineData("recipient_cancel_join")] + [InlineData("thread_exit")] + [InlineData("sdk_queue")] + [InlineData("sdk_cron")] + [InlineData("sdk_tick_type")] + [InlineData("sdk_manager")] + [InlineData("sdk_payload")] + [InlineData("sdk_misfire")] + [InlineData("sdk_arity")] + [InlineData("sdk_key_slot")] + [InlineData("sdk_extra_caller")] + [InlineData("sdk_interface_caller")] + [InlineData("sdk_swapped_literals")] + [InlineData("ownership_extra_holder")] + [InlineData("ownership_public_field")] + [InlineData("ownership_published_type")] + [InlineData("ownership_forwarded_field")] + [InlineData("ownership_completion_state")] + [InlineData("ownership_foreign_resource")] + [InlineData("ownership_foreign_generic")] + [InlineData("ownership_forwarded_stop")] + [InlineData("ownership_forwarded_manager")] + [InlineData("memory_wake")] + [InlineData("memory_field")] + [InlineData("memory_helper")] + [InlineData("memory_indirect")] + [InlineData("memory_scheduling")] + [InlineData("memory_tick_type")] + [InlineData("memory_vendor_identity")] + [InlineData("memory_readiness_wait")] + [InlineData("memory_extra_caller")] + [InlineData("exclusion_sql")] + [InlineData("exclusion_typed_array")] + [InlineData("exclusion_clone")] + [InlineData("exclusion_limit")] + [InlineData("exclusion_delegated_binding")] + [InlineData("exclusion_foreign_binding")] + [InlineData("publication_before_start")] + [InlineData("publication_dispose_before_join_ack")] + public void Background_job_recurrence_runtime_controls_reject_changed_authority_and_cleanup(string mutation) { - if (mutation.StartsWith("sdk_", StringComparison.Ordinal)) return MutateRecurrenceSdk(census, mutation); - if (mutation.StartsWith("ownership_", StringComparison.Ordinal)) return MutateRecurrenceOwnership(census, mutation); - if (mutation.StartsWith("memory_", StringComparison.Ordinal)) return MutateRecurrenceMemory(census, mutation); - if (mutation.StartsWith("exclusion_", StringComparison.Ordinal) || mutation.StartsWith("publication_", StringComparison.Ordinal)) - return MutateRecurrencePublication(census, mutation); - var recipient = types[(InfrastructureAssembly, RcRecipient)]; - if (mutation == "constructor_visibility") - { - var constructor = recipient.Methods.Single(method => method.IsConstructor); - return ChangeAttributes(() => constructor.Attributes, value => constructor.Attributes = value, - (constructor.Attributes & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Public); - } - if (mutation == "callback_signature") - { - var callback = types[(InfrastructureAssembly, RcNative)].Methods.Single(method => method.Name == "StartThread"); - var original = callback.ReturnType; - callback.ReturnType = callback.Module.TypeSystem.Int32; - return () => callback.ReturnType = original; - } - if (mutation == "extra_caller") + using var census = ProductionCensus.Read(); + var types = census.Types; + AssertMutation(census, mutation, () => { - var owner = types[(InfrastructureAssembly, RcControl)]; - var extra = new MethodDefinition("UnlistedRecurrenceStart", MethodAttributes.Private, - owner.Module.TypeSystem.Void); - owner.Methods.Add(extra); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Call, - types[(InfrastructureAssembly, RcNative)].Methods.Single(method => method.Name == "Start"))); - extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); - return () => owner.Methods.Remove(extra); - } - if (mutation == "foreign_await") - { - var module = types[(DeliveryApplication, RecipientClaim)].Module; - var outer = new TypeDefinition("System.Runtime.CompilerServices", "ConfiguredTaskAwaitable", - TypeAttributes.NotPublic | TypeAttributes.Sealed | TypeAttributes.Class, module.TypeSystem.Object); - var nested = new TypeDefinition("", "ConfiguredTaskAwaiter", - TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.Class, module.TypeSystem.Object); - outer.NestedTypes.Add(nested); - module.Types.Add(outer); - var method = new MethodDefinition("GetResult", MethodAttributes.Public, module.TypeSystem.Void); - nested.Methods.Add(method); - method.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); - var calls = OwnedBodies(census).Where(item => item.Owner.DeclaringType.FullName == RcNative - && item.Owner.Name == "ObserveAsync").SelectMany(item => item.Body.Body.Instructions) - .Where(item => item.Operand is MethodReference target - && target.DeclaringType.FullName == "System.Runtime.CompilerServices.ConfiguredTaskAwaitable/ConfiguredTaskAwaiter" - && target.Name == "GetResult").ToArray(); - calls.Should().HaveCount(2, "both non-generic awaits are real subjects before substituting one"); - var original = calls[0].Operand; - calls[0].Operand = method; - return () => { calls[0].Operand = original; module.Types.Remove(outer); }; - } - if (mutation is "foreign_target" or "foreign_cleanup") - { - var module = types[(DeliveryApplication, RecipientClaim)].Module; - var cleanup = mutation == "foreign_cleanup"; - var foreign = new TypeDefinition(cleanup ? "System.Threading" : "LearnStack.Infrastructure.Jobs", - cleanup ? "Thread" : "BackgroundJobNativeRecurrenceOperation", - TypeAttributes.NotPublic | TypeAttributes.Sealed | TypeAttributes.Class, module.TypeSystem.Object); - module.Types.Add(foreign); - var method = new MethodDefinition(cleanup ? "get_IsAlive" : "Start", MethodAttributes.Assembly, - cleanup ? module.TypeSystem.Boolean : module.TypeSystem.Void); - foreign.Methods.Add(method); - method.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); - var call = OwnedBodies(census).Where(item => item.Owner.DeclaringType.FullName == (cleanup ? RcNative : RcControl) - && item.Owner.Name == (cleanup ? "ObserveAsync" : "RegisterAsync")).SelectMany(item => item.Body.Body.Instructions) + if (mutation.StartsWith("sdk_", StringComparison.Ordinal)) return MutateRecurrenceSdk(census, mutation); + if (mutation.StartsWith("ownership_", StringComparison.Ordinal)) return MutateRecurrenceOwnership(census, mutation); + if (mutation.StartsWith("memory_", StringComparison.Ordinal)) return MutateRecurrenceMemory(census, mutation); + if (mutation.StartsWith("exclusion_", StringComparison.Ordinal) || mutation.StartsWith("publication_", StringComparison.Ordinal)) + return MutateRecurrencePublication(census, mutation); + var recipient = types[(InfrastructureAssembly, RcRecipient)]; + if (mutation == "constructor_visibility") + { + var constructor = recipient.Methods.Single(method => method.IsConstructor); + return ChangeAttributes(() => constructor.Attributes, value => constructor.Attributes = value, + (constructor.Attributes & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Public); + } + if (mutation == "callback_signature") + { + var callback = types[(InfrastructureAssembly, RcNative)].Methods.Single(method => method.Name == "StartThread"); + var original = callback.ReturnType; + callback.ReturnType = callback.Module.TypeSystem.Int32; + return () => callback.ReturnType = original; + } + if (mutation == "extra_caller") + { + var owner = types[(InfrastructureAssembly, RcControl)]; + var extra = new MethodDefinition("UnlistedRecurrenceStart", MethodAttributes.Private, + owner.Module.TypeSystem.Void); + owner.Methods.Add(extra); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Call, + types[(InfrastructureAssembly, RcNative)].Methods.Single(method => method.Name == "Start"))); + extra.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + return () => owner.Methods.Remove(extra); + } + if (mutation == "foreign_await") + { + var module = types[(DeliveryApplication, RecipientClaim)].Module; + var outer = new TypeDefinition("System.Runtime.CompilerServices", "ConfiguredTaskAwaitable", + TypeAttributes.NotPublic | TypeAttributes.Sealed | TypeAttributes.Class, module.TypeSystem.Object); + var nested = new TypeDefinition("", "ConfiguredTaskAwaiter", + TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.Class, module.TypeSystem.Object); + outer.NestedTypes.Add(nested); + module.Types.Add(outer); + var method = new MethodDefinition("GetResult", MethodAttributes.Public, module.TypeSystem.Void); + nested.Methods.Add(method); + method.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + var calls = OwnedBodies(census).Where(item => item.Owner.DeclaringType.FullName == RcNative + && item.Owner.Name == "ObserveAsync").SelectMany(item => item.Body.Body.Instructions) + .Where(item => item.Operand is MethodReference target + && target.DeclaringType.FullName == "System.Runtime.CompilerServices.ConfiguredTaskAwaitable/ConfiguredTaskAwaiter" + && target.Name == "GetResult").ToArray(); + calls.Should().HaveCount(2, "both non-generic awaits are real subjects before substituting one"); + var original = calls[0].Operand; + calls[0].Operand = method; + return () => { calls[0].Operand = original; module.Types.Remove(outer); }; + } + if (mutation is "foreign_target" or "foreign_cleanup") + { + var module = types[(DeliveryApplication, RecipientClaim)].Module; + var cleanup = mutation == "foreign_cleanup"; + var foreign = new TypeDefinition(cleanup ? "System.Threading" : "LearnStack.Infrastructure.Jobs", + cleanup ? "Thread" : "BackgroundJobNativeRecurrenceOperation", + TypeAttributes.NotPublic | TypeAttributes.Sealed | TypeAttributes.Class, module.TypeSystem.Object); + module.Types.Add(foreign); + var method = new MethodDefinition(cleanup ? "get_IsAlive" : "Start", MethodAttributes.Assembly, + cleanup ? module.TypeSystem.Boolean : module.TypeSystem.Void); + foreign.Methods.Add(method); + method.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + var call = OwnedBodies(census).Where(item => item.Owner.DeclaringType.FullName == (cleanup ? RcNative : RcControl) + && item.Owner.Name == (cleanup ? "ObserveAsync" : "RegisterAsync")).SelectMany(item => item.Body.Body.Instructions) + .Single(item => item.Operand is MethodReference target + && target.DeclaringType.FullName == (cleanup ? "System.Threading.Thread" : RcNative) + && target.Name == (cleanup ? "get_IsAlive" : "Start")); + var original = call.Operand; + call.Operand = method; + return () => { call.Operand = original; module.Types.Remove(foreign); }; + } + var (ownerType, ownerMethod, targetType, targetMethod) = mutation switch + { + "delegate_escape" => (RcControl, "RegisterAsync", RcNative, "Start"), + "parent_join" => (OrchestrationControl, "ObserveCompletionAsync", RcControl, "get_Completion"), + "native_stop" => (RcControl, "RequestStop", RcNative, "RequestStop"), + "recipient_cancel_join" => (RcRecipient, "ObserveAsync", "System.Threading.Tasks.Task", "WhenAll"), + "thread_exit" => (RcNative, "ObserveAsync", "System.Threading.Thread", "get_IsAlive"), + _ => throw new ArgumentOutOfRangeException(nameof(mutation)), + }; + var instruction = OwnedBodies(census).Where(item => item.Owner.DeclaringType.FullName == ownerType + && item.Owner.Name == ownerMethod).SelectMany(item => item.Body.Body.Instructions) .Single(item => item.Operand is MethodReference target - && target.DeclaringType.FullName == (cleanup ? "System.Threading.Thread" : RcNative) - && target.Name == (cleanup ? "get_IsAlive" : "Start")); - var original = call.Operand; - call.Operand = method; - return () => { call.Operand = original; module.Types.Remove(foreign); }; - } - var (ownerType, ownerMethod, targetType, targetMethod) = mutation switch - { - "delegate_escape" => (RcControl, "RegisterAsync", RcNative, "Start"), - "parent_join" => (OrchestrationControl, "ObserveCompletionAsync", RcControl, "get_Completion"), - "native_stop" => (RcControl, "RequestStop", RcNative, "RequestStop"), - "recipient_cancel_join" => (RcRecipient, "ObserveAsync", "System.Threading.Tasks.Task", "WhenAll"), - "thread_exit" => (RcNative, "ObserveAsync", "System.Threading.Thread", "get_IsAlive"), - _ => throw new ArgumentOutOfRangeException(nameof(mutation)), - }; - var instruction = OwnedBodies(census).Where(item => item.Owner.DeclaringType.FullName == ownerType - && item.Owner.Name == ownerMethod).SelectMany(item => item.Body.Body.Instructions) - .Single(item => item.Operand is MethodReference target - && target.DeclaringType.FullName == targetType && target.Name == targetMethod); - return mutation == "delegate_escape" ? ReplaceInstruction(instruction, OpCodes.Ldftn, instruction.Operand) - : ReplaceInstruction(instruction, OpCodes.Nop, null!); - }, RecurrenceRuntimeOffenders); + && target.DeclaringType.FullName == targetType && target.Name == targetMethod); + return mutation == "delegate_escape" ? ReplaceInstruction(instruction, OpCodes.Ldftn, instruction.Operand) + : ReplaceInstruction(instruction, OpCodes.Nop, null!); + }, RecurrenceRuntimeOffenders); + } } private static SortedSet RecurrenceRuntimeOffenders(ProductionCensus census) diff --git a/backend/tests/LearnStack.Tests.Architecture/DataProtectionConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/DataProtectionConventionTests.cs new file mode 100644 index 000000000..169b81c44 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Architecture/DataProtectionConventionTests.cs @@ -0,0 +1,206 @@ +using FluentAssertions; +using LearnStack.Infrastructure.DataProtection; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Tenancy.Domain; +using LearnStack.Modules.Tenancy.Infrastructure.Persistence; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Xunit; +using Xunit.Abstractions; + +namespace LearnStack.Tests.Architecture; + +public sealed class DataProtectionConventionTests(ITestOutputHelper output) +{ + private const string ModelConnection = "Host=model-only;Database=model-only;Username=model-only"; + + /// ADR-0073: the complete actual production-model population requires explicit classification. + [Fact] + public void Mapped_Properties_Have_Explicit_Personal_Data_Classification() + { + var discovered = ProductionAssemblies.All().SelectMany(assembly => assembly.GetTypes()) + .Where(type => !type.IsAbstract && !type.ContainsGenericParameters && typeof(DbContext).IsAssignableFrom(type)) + .ToArray(); + var covered = new List(); + var properties = new List(); + foreach (var create in ModelFactories()) + { + using var context = create(); + covered.Add(context.GetType()); + var model = context.GetService().Model; + if (context is PlatformDbContext) + { + model.GetEntityTypes().Should().BeEmpty( + "Platform is deliberately migration-only; SQL-only stores retain their separate inventory"); + continue; + } + + var mapped = model.GetEntityTypes().SelectMany(entity => entity.GetProperties()).ToArray(); + mapped.Should().NotBeEmpty("an empty module model cannot qualify the classification census"); + output.WriteLine("{0}: {1} entities, {2} scalar properties.", + context.GetType().Name, model.GetEntityTypes().Count(), mapped.Length); + properties.AddRange(mapped); + model.FindAnnotation(PersonalDataClassificationExtensions.ValidatedModelAnnotation)?.Value.Should().Be(true, + "Fix: opt every production mapped context into the finalizing convention"); + PersonalDataModelCensus.Inspect(model).Should().BeEmpty( + "Fix: explicitly declare each mapped property, including inherited and shadow properties"); + } + + covered.Should().BeEquivalentTo(discovered, + "Fix: add every new production DbContext to the census; no module or non-module context may disappear"); + covered.Count.Should().BeGreaterThan(4, "the sweep includes every mapped module and the empty Platform context"); + properties.Should().Contain(property => property.Name == "CreatedBy", + "inherited actor references are part of the real mapped population"); + properties.Should().Contain(property => property.Name == "DeletedBy"); + output.WriteLine("Complete census: {0} contexts, {1} mapped scalar properties.", covered.Count, properties.Count); + } + + [Fact] + public void Production_model_refuses_a_neutral_property_added_after_normal_customization() + { + using var context = ModifiedTenancy(); + var build = () => context.Model; + build.Should().Throw().WithMessage(PersonalDataModelCensus.FailureMessage); + } + + [Fact] + public void Production_model_accepts_the_same_neutral_property_with_an_explicit_declaration() + { + using var context = ModifiedTenancy(); + var model = context.GetService().Model; + var property = model.FindEntityType(typeof(Tenant))!.FindProperty("NeutralPayload")!; + property.IsShadowProperty().Should().BeTrue("the control reaches a real added mapping rather than a CLR-name scan"); + property.FindAnnotation(PersonalDataClassificationExtensions.CategoryAnnotation)!.Value + .Should().Be(PersonalDataCategory.Identity); + PersonalDataModelCensus.Inspect(model).Should().BeEmpty(); + } + + [Theory] + [InlineData(0, "A purpose does not make the default category valid.")] + [InlineData(7, "Unknown category.")] + [InlineData(1, "")] + [InlineData(1, " ")] + public void Invalid_category_or_blank_purpose_is_refused(int category, string purpose) + { + var entity = ProbeModel().Entity(); + var declare = () => entity.Property(probe => probe.NeutralPayload) + .HasPersonalData((PersonalDataCategory)category, purpose); + declare.Should().Throw().WithMessage(PersonalDataModelCensus.FailureMessage); + } + + [Fact] + public void Purpose_is_bounded_and_conflicting_declarations_cannot_overwrite_a_review() + { + var property = ProbeModel().Entity().Property(probe => probe.NeutralPayload); + var purpose = new string('a', PersonalDataClassificationExtensions.MaximumPurposeLength); + property.HasPersonalData(PersonalDataCategory.Identity, purpose); + property.HasPersonalData(PersonalDataCategory.Identity, purpose); + + var conflictingCategory = () => property.HasPersonalData(PersonalDataCategory.None, purpose); + var conflictingPurpose = () => property.HasPersonalData(PersonalDataCategory.Identity, "Different purpose."); + var excessivePurpose = () => property.HasPersonalData(PersonalDataCategory.Identity, purpose + "a"); + conflictingCategory.Should().Throw().WithMessage(PersonalDataModelCensus.FailureMessage); + conflictingPurpose.Should().Throw().WithMessage(PersonalDataModelCensus.FailureMessage); + excessivePurpose.Should().Throw().WithMessage(PersonalDataModelCensus.FailureMessage); + property.Metadata.FindAnnotation(PersonalDataClassificationExtensions.PurposeAnnotation)!.Value.Should().Be(purpose); + } + + [Fact] + public void Declaration_of_an_unmapped_name_does_not_create_a_property_or_partially_classify() + { + var entity = ProbeModel().Entity(); + var declare = () => entity.DeclarePersonalData(PersonalDataCategory.None, "Fixture structural fields.", + nameof(Probe.NeutralPayload), "UnmappedPayload"); + declare.Should().Throw().WithMessage(PersonalDataModelCensus.FailureMessage); + entity.Metadata.FindProperty("UnmappedPayload").Should().BeNull(); + entity.Metadata.FindProperty(nameof(Probe.NeutralPayload))! + .FindAnnotation(PersonalDataClassificationExtensions.CategoryAnnotation).Should().BeNull(); + } + + [Fact] + public void Census_is_deterministic_and_reports_no_annotation_or_property_values() + { + const string canary = "private-person-value-canary"; + var builder = ProbeModel(); + var property = builder.Entity().Property(probe => probe.NeutralPayload); + property.HasDefaultValue(canary); + property.Metadata.SetAnnotation(PersonalDataClassificationExtensions.CategoryAnnotation, new UnprintableValue()); + property.Metadata.SetAnnotation(PersonalDataClassificationExtensions.PurposeAnnotation, + canary + new string('x', PersonalDataClassificationExtensions.MaximumPurposeLength)); + + var issues = PersonalDataModelCensus.Inspect(builder.Model); + issues.Select(issue => issue.Code).Should().Equal("invalid_category", "invalid_purpose"); + PersonalDataModelCensus.Inspect(builder.Model).Should().Equal(issues); + string.Join("|", issues).Should().NotContain(canary); + var declare = () => property.HasPersonalData(PersonalDataCategory.Identity, canary + new string('x', 256)); + declare.Should().Throw().WithMessage(PersonalDataModelCensus.FailureMessage) + .Which.ToString().Should().NotContain(canary); + } + + [Fact] + public void Classification_annotations_introduce_no_relational_schema_changes() + { + foreach (var create in Modules.Mapped.Select(module => module.Context)) + { + using var context = create(); + var snapshot = context.GetService().ModelSnapshot; + snapshot.Should().NotBeNull("each scoped module has its existing migration baseline"); + var previous = context.GetService().Initialize(snapshot!.Model, designTime: true); + var current = context.GetService().Model; + context.GetService() + .GetDifferences(previous.GetRelationalModel(), current.GetRelationalModel()) + .Should().BeEmpty("classification is metadata only, and must not change the existing schema"); + } + } + + private static IEnumerable> ModelFactories() => + Modules.Mapped.Select(module => module.Context).Append(() => new PlatformDbContext( + new DbContextOptionsBuilder().UseNpgsql(ModelConnection).Options)); + + private static TenancyDbContext ModifiedTenancy() where TCustomizer : class, IModelCustomizer => + new(new DbContextOptionsBuilder().UseNpgsql(ModelConnection) + .ReplaceService().Options, StaticTenantContextAccessor.Unresolved); + + private static ModelBuilder ProbeModel() + { + var builder = new ModelBuilder(); + builder.Entity().Property(probe => probe.Id) + .HasPersonalData(PersonalDataCategory.None, "Fixture structural key."); + builder.Entity().Property(probe => probe.NeutralPayload); + return builder; + } + + public sealed class MissingPropertyCustomizer(ModelCustomizerDependencies dependencies) : ModelCustomizer(dependencies) + { + public override void Customize(ModelBuilder modelBuilder, DbContext context) + { + base.Customize(modelBuilder, context); + modelBuilder.Entity().Property("NeutralPayload"); + } + } + + public sealed class DeclaredPropertyCustomizer(ModelCustomizerDependencies dependencies) : ModelCustomizer(dependencies) + { + public override void Customize(ModelBuilder modelBuilder, DbContext context) + { + base.Customize(modelBuilder, context); + modelBuilder.Entity().Property("NeutralPayload") + .HasPersonalData(PersonalDataCategory.Identity, "Fixture demonstrates explicit classification of a neutral name."); + } + } + + private sealed class Probe + { + public int Id { get; set; } + public string? NeutralPayload { get; set; } + } + + private sealed class UnprintableValue + { + public override string ToString() => throw new InvalidOperationException("Metadata values must never be rendered."); + } +} diff --git a/backend/tests/LearnStack.Tests.Architecture/DeliveryDispatchBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/DeliveryDispatchBoundaryTests.cs index 7a09d94cb..a0e8a3f61 100644 --- a/backend/tests/LearnStack.Tests.Architecture/DeliveryDispatchBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/DeliveryDispatchBoundaryTests.cs @@ -134,34 +134,37 @@ public void Delivery_observation_walk_rejects_concrete_interface_inherited_async finally { observation.Fields.Remove(cleanField); module.Types.Remove(clean); } } - [Fact] - public void Delivery_credentials_reject_extra_store_locators_forwarding_overloads_and_wrong_keys() + public sealed class DeliveryCredentialMutationTests { - using var census = ProductionCensus.Read(); - var module = census.Modules.Single(item => item.Assembly.Name.Name == DeliveryApplication); - var store = census.Types[(InfrastructureAssembly, DeliveryStore)]; - foreach (var capability in store.Methods.Where(method => method.Name is ".ctor" or "TryClaimAsync" or "ReplayAsync")) - foreach (var opcode in new[] { OpCodes.Call, OpCodes.Callvirt, OpCodes.Ldftn, OpCodes.Ldvirtftn }) - AssertMutation(census, "a subscriber privileged store escape through " + opcode.Name, - () => AddCallProbe(module, "DeliveryStoreEscape", capability, opcode), CredentialOffenders); - var locator = typeof(ServiceProviderServiceExtensions).GetMethods().Single(method => method.Name == "GetRequiredService" - && method.IsGenericMethodDefinition && method.GetParameters().Length == 1).MakeGenericMethod(typeof(DeliveryDispatchStore)); - AssertMutation(census, "an unkeyed subscriber store locator", () => - AddAsyncCallProbe(module, "DeliveryStoreLocator", module.ImportReference(locator)), CredentialOffenders); - var worker = census.Types[(BoundaryApi, DeliveryWorker)]; - foreach (var (type, name, field) in new[] { (worker, "StartAsync", "_source"), (worker, "DispatchAsync", "_store"), - (worker, "ClaimNextAsync", "_store"), - (store, "ReplayAsync", "_source"), (store, "AcquireAsync", "_source") }) - AssertMutation(census, "an extra privileged forwarding overload", () => AddBoundaryFieldGetter(type, name, field), CredentialOffenders); - var parameter = worker.Methods.Single(method => method.IsConstructor && !method.IsStatic).Parameters - .Single(item => item.CustomAttributes.Any(attribute => attribute.AttributeType.Name == "FromKeyedServicesAttribute")); - var attribute = parameter.CustomAttributes.Single(item => item.AttributeType.Name == "FromKeyedServicesAttribute"); - AssertMutation(census, "subscriber worker crossing to the platform credential", () => + [Fact] + public void Delivery_credentials_reject_extra_store_locators_forwarding_overloads_and_wrong_keys() { - var original = attribute.ConstructorArguments[0]; - attribute.ConstructorArguments[0] = new CustomAttributeArgument(original.Type, BoundaryPlatform); - return () => attribute.ConstructorArguments[0] = original; - }, CredentialOffenders); + using var census = ProductionCensus.Read(); + var module = census.Modules.Single(item => item.Assembly.Name.Name == DeliveryApplication); + var store = census.Types[(InfrastructureAssembly, DeliveryStore)]; + foreach (var capability in store.Methods.Where(method => method.Name is ".ctor" or "TryClaimAsync" or "ReplayAsync")) + foreach (var opcode in new[] { OpCodes.Call, OpCodes.Callvirt, OpCodes.Ldftn, OpCodes.Ldvirtftn }) + AssertMutation(census, "a subscriber privileged store escape through " + opcode.Name, + () => AddCallProbe(module, "DeliveryStoreEscape", capability, opcode), CredentialOffenders); + var locator = typeof(ServiceProviderServiceExtensions).GetMethods().Single(method => method.Name == "GetRequiredService" + && method.IsGenericMethodDefinition && method.GetParameters().Length == 1).MakeGenericMethod(typeof(DeliveryDispatchStore)); + AssertMutation(census, "an unkeyed subscriber store locator", () => + AddAsyncCallProbe(module, "DeliveryStoreLocator", module.ImportReference(locator)), CredentialOffenders); + var worker = census.Types[(BoundaryApi, DeliveryWorker)]; + foreach (var (type, name, field) in new[] { (worker, "StartAsync", "_source"), (worker, "DispatchAsync", "_store"), + (worker, "ClaimNextAsync", "_store"), + (store, "ReplayAsync", "_source"), (store, "AcquireAsync", "_source") }) + AssertMutation(census, "an extra privileged forwarding overload", () => AddBoundaryFieldGetter(type, name, field), CredentialOffenders); + var parameter = worker.Methods.Single(method => method.IsConstructor && !method.IsStatic).Parameters + .Single(item => item.CustomAttributes.Any(attribute => attribute.AttributeType.Name == "FromKeyedServicesAttribute")); + var attribute = parameter.CustomAttributes.Single(item => item.AttributeType.Name == "FromKeyedServicesAttribute"); + AssertMutation(census, "subscriber worker crossing to the platform credential", () => + { + var original = attribute.ConstructorArguments[0]; + attribute.ConstructorArguments[0] = new CustomAttributeArgument(original.Type, BoundaryPlatform); + return () => attribute.ConstructorArguments[0] = original; + }, CredentialOffenders); + } } [Fact] diff --git a/backend/tests/LearnStack.Tests.Architecture/DomainGenericityTests.cs b/backend/tests/LearnStack.Tests.Architecture/DomainGenericityTests.cs index 6ad60b331..2fd622606 100644 --- a/backend/tests/LearnStack.Tests.Architecture/DomainGenericityTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/DomainGenericityTests.cs @@ -173,7 +173,7 @@ sequence_no UUID NOT NULL { yield return ("a backend name", [.. ProductionAssemblies.All().SelectMany(NamesIn)]); yield return ("a backend file", [.. BackendFileNames()]); - yield return ("a mapped table or column", [.. Modules.Scoped.SelectMany(module => + yield return ("a mapped table or column", [.. Modules.Mapped.SelectMany(module => { using var context = module.Context(); return ModelNames(context); diff --git a/backend/tests/LearnStack.Tests.Architecture/EntitlementKeyTests.cs b/backend/tests/LearnStack.Tests.Architecture/EntitlementKeyTests.cs index cdc640d90..23a7dbba3 100644 --- a/backend/tests/LearnStack.Tests.Architecture/EntitlementKeyTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/EntitlementKeyTests.cs @@ -246,7 +246,7 @@ private static TypeDefinition Outermost(TypeDefinition type) /// The entity types every module model maps to one physical table. private static List MappedTo(string table) => - [.. Modules.Scoped.SelectMany(module => + [.. Modules.Mapped.SelectMany(module => { using var context = module.Context(); return context.Model.GetEntityTypes() diff --git a/backend/tests/LearnStack.Tests.Architecture/GlobalIdentityModelTests.cs b/backend/tests/LearnStack.Tests.Architecture/GlobalIdentityModelTests.cs new file mode 100644 index 000000000..82f35237b --- /dev/null +++ b/backend/tests/LearnStack.Tests.Architecture/GlobalIdentityModelTests.cs @@ -0,0 +1,108 @@ +using FluentAssertions; +using System.Reflection; +using System.Security.Cryptography; +using System.Text; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.DataProtection; +using LearnStack.SharedKernel.Persistence; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations.Operations; +using Xunit; + +namespace LearnStack.Tests.Architecture; + +public sealed class GlobalIdentityModelTests +{ + [Fact] + public void Historical_Identity_migrations_retain_their_ordered_SQL_operations() + { + // These already-applied migrations call shared DDL/manifest helpers. + // Pin their emitted SQL independently of the latest database census. + string[] historical = ["20261025201338_create_identity_schema", "20261025232309_add_contextual_identity", + "20261026035353_correct_identity_parent_mirror_sqlstate", "20261026043921_correct_identity_admission_parent_sqlstate"]; + var actual = new Dictionary(StringComparer.Ordinal); + foreach (var type in typeof(IdentityDbContext).Assembly.GetTypes()) + { + var id = type.GetCustomAttribute()?.Id; + if (id is null || !historical.Contains(id, StringComparer.Ordinal)) continue; + var migration = (Migration)Activator.CreateInstance(type)!; + migration.ActiveProvider = "Npgsql.EntityFrameworkCore.PostgreSQL"; + actual.Add(id + "/up", SqlDigest(migration.UpOperations)); + actual.Add(id + "/down", SqlDigest(migration.DownOperations)); + } + actual.Should().BeEquivalentTo(new Dictionary(StringComparer.Ordinal) + { + ["20261025201338_create_identity_schema/up"] = "10934bfcd4e627f53453db73923089ef0091e7bb79ad3903148ad6dc8b77f2f9", + ["20261025201338_create_identity_schema/down"] = "e73bf7c924bd93ff7c5a4b7b280b8662d1c8c92a68322fd08e000bee9b2ea553", + ["20261025232309_add_contextual_identity/up"] = "b2e35b7a50a6bb282a7fe5ea898b075d6b6a1e104a422ac703bbd35b805fc4ea", + ["20261025232309_add_contextual_identity/down"] = "3dcf51c56981f939d7e43ab39dca922ccc51bd51ce6a608f79327b5beac20a77", + ["20261026035353_correct_identity_parent_mirror_sqlstate/up"] = "6d91942839a75e2570f7cc070fe253c8818477525c2af9f86ca51328fd68a39c", + ["20261026035353_correct_identity_parent_mirror_sqlstate/down"] = "6e349e7ba68d3afd76d663d7f7cf4e5fa5a2beea23cf68eb73543a02c050e1d5", + ["20261026043921_correct_identity_admission_parent_sqlstate/up"] = "60fbd523095628a9e2d10fb7385c711f25fb3a7ffb16c1761d93e69fecca8625", + ["20261026043921_correct_identity_admission_parent_sqlstate/down"] = "9ab54f76e69a5638a7295a6cab63c3801c019aaa76cca1e51b29dcd38822edcb", + }); + } + + private static string SqlDigest(IReadOnlyList operations) + { + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + Span length = stackalloc byte[4]; + foreach (var sql in operations.OfType()) + { + var bytes = Encoding.UTF8.GetBytes(sql.Sql); + System.Buffers.Binary.BinaryPrimitives.WriteInt32BigEndian(length, bytes.Length); + hash.AppendData(length); + hash.AppendData(bytes); + } + return Convert.ToHexStringLower(hash.GetHashAndReset()); + } + + [Fact] + public void Generated_snapshot_matches_the_current_Identity_model() + { + using var context = Modules.ModelOnly(); + context.Database.HasPendingModelChanges().Should().BeFalse(); + } + + [Fact] + public void User_Aggregate_Has_No_TenantScoped_Columns() + { + using var context = Modules.ModelOnly(); + context.Model.GetEntityTypes().Select(entity => entity.GetTableName()) + .Should().BeEquivalentTo(["users", "identity_authority", "memberships", "membership_profiles", + "membership_role_assignments", "roles", "role_permission_grants"]); + var user = context.Model.FindEntityType(typeof(User))!; + user.GetProperties().Should().HaveCount(14); + user.FindProperty("TenantId").Should().BeNull(); + user.FindProperty("OrganizationId").Should().BeNull(); + typeof(ITenantOwned).IsAssignableFrom(typeof(User)).Should().BeFalse(); + typeof(User).GetCustomAttributes(typeof(TenantOwnedAttribute), false).Should().BeEmpty(); + user.GetDeclaredQueryFilters().Should().ContainSingle(); + context.Model.FindEntityType(typeof(IdentityAuthority))!.GetDeclaredQueryFilters().Should().BeEmpty(); + Modules.Mapped.Count(module => module.Domain == typeof(User).Assembly).Should().Be(1); + Modules.Scoped.Should().Contain(module => module.Domain == typeof(User).Assembly, + "Identity's contextual roots and contained children require the same tenant/org sweep"); + } + + [Fact] + public void User_binding_has_permanent_unique_key_creation_pair_and_sensitive_raw_subject() + { + using var context = Modules.ModelOnly(); + var user = context.Model.FindEntityType(typeof(User))!; + var binding = user.GetIndexes().Single(index => index.GetDatabaseName() == "ux_users_authority_id_subject_key"); + binding.IsUnique.Should().BeTrue(); + binding.GetFilter().Should().BeNull(); + binding.Properties.Select(property => property.Name).Should().Equal("AuthorityId", "SubjectKey"); + user.FindProperty(nameof(User.CreationAuditId)).Should().NotBeNull(); + user.FindProperty(nameof(User.CreationAuditTimestamp)).Should().NotBeNull(); + user.GetForeignKeys().Should().ContainSingle(key => key.PrincipalEntityType.ClrType == typeof(IdentityAuthority)); + typeof(User).GetProperty(nameof(User.ProviderSubject))! + .GetCustomAttributes(typeof(PiiSensitiveAttribute), true).Should().ContainSingle(); + foreach (var name in new[] { nameof(User.UpdatedAt), nameof(User.UpdatedBy), nameof(User.DeletedAt), nameof(User.DeletedBy) }) + user.FindProperty(name)!.GetBeforeSaveBehavior().Should().Be(PropertySaveBehavior.Ignore, + "the creation-only INSERT grant excludes these four NULL columns"); + } +} diff --git a/backend/tests/LearnStack.Tests.Architecture/HangfireBridgeCredentialBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/HangfireBridgeCredentialBoundaryTests.cs index b41c71521..299aaeb27 100644 --- a/backend/tests/LearnStack.Tests.Architecture/HangfireBridgeCredentialBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/HangfireBridgeCredentialBoundaryTests.cs @@ -93,137 +93,140 @@ private static void CheckBridgeCapturedField(SortedSet offenders, Produc .Select(item => item.OwnerId + ":" + item.Instruction.OpCode.Name), expected); } - [Fact] - public void Bridge_credential_census_rejects_extra_acquisition_forwarding_and_store_consumers() + public sealed class BridgeCredentialMutationTests { - using var census = ProductionCensus.Read(); - EvaluateDetector(census, CredentialOffenders).Should().BeEmpty("the actual bridge store and its bridge owner must be nonempty clean subjects"); - var store = census.Types[(InfrastructureAssembly, JobBridgeStore)]; - var bridge = census.Types[(InfrastructureAssembly, JobBridge)]; - var application = census.Modules.Single(module => module.Assembly.Name.Name == DeliveryApplication); - var reader = store.Methods.Single(method => method.Name == "OpenConnectionAsync"); - var constructor = store.Methods.Single(method => method.IsConstructor); - var claim = store.Methods.Single(method => method.Name == "TryClaimAsync"); - foreach (var target in new[] { reader, constructor, claim }) + [Fact] + public void Bridge_credential_census_rejects_extra_acquisition_forwarding_and_store_consumers() { - foreach (var opcode in new[] { OpCodes.Call, OpCodes.Callvirt, OpCodes.Ldftn, OpCodes.Ldvirtftn }) - AssertMutation(census, "an extra bridge capability consumer through " + opcode, () => - AddCallProbe(application, "ExtraBridgeCapability", target, opcode), CredentialOffenders); - AssertMutation(census, "an async bridge capability consumer", () => - AddAsyncCallProbe(application, "AsyncBridgeCapability", target), CredentialOffenders); - } - AssertMutation(census, "an extra bridge-store constructor call", () => - AddCallProbe(application, "ExtraBridgeConstruction", constructor, OpCodes.Newobj), CredentialOffenders); - AssertMutation(census, "an extra acquisition helper on the sanctioned bridge store", () => - { - var method = AddCall(store, "ExtraBridgeAcquisition", reader, OpCodes.Call); - return () => store.Methods.Remove(method); - }, CredentialOffenders); - AssertMutation(census, "a second acquisition inside an approved bridge caller", () => - { - var body = OwnedBodies(census).Single(item => item.Owner == claim && item.Body.Name == "MoveNext").Body; - var instruction = Instruction.Create(OpCodes.Call, reader); - body.Body.Instructions.Add(instruction); - return () => body.Body.Instructions.Remove(instruction); - }, CredentialOffenders); - foreach (var name in new[] { "ForwardSource", "OpenConnectionAsync", "TryClaimAsync", "UpdateAsync" }) - AssertMutation(census, "a source-forwarding bridge helper or approved-name overload", () => - AddBoundaryFieldGetter(store, name, JobBridgeSourceField), CredentialOffenders); - AssertMutation(census, "a bridge owner forwarding its store capability", () => - AddBoundaryFieldGetter(bridge, "ForwardStore", "P"), CredentialOffenders); - foreach (var opcode in new[] { OpCodes.Ldfld, OpCodes.Ldflda, OpCodes.Stfld }) - AssertMutation(census, "an extra source read, address or write inside the exact reader through " + opcode, () => + using var census = ProductionCensus.Read(); + EvaluateDetector(census, CredentialOffenders).Should().BeEmpty("the actual bridge store and its bridge owner must be nonempty clean subjects"); + var store = census.Types[(InfrastructureAssembly, JobBridgeStore)]; + var bridge = census.Types[(InfrastructureAssembly, JobBridge)]; + var application = census.Modules.Single(module => module.Assembly.Name.Name == DeliveryApplication); + var reader = store.Methods.Single(method => method.Name == "OpenConnectionAsync"); + var constructor = store.Methods.Single(method => method.IsConstructor); + var claim = store.Methods.Single(method => method.Name == "TryClaimAsync"); + foreach (var target in new[] { reader, constructor, claim }) { - var instruction = Instruction.Create(opcode, store.Fields.Single(field => field.Name == JobBridgeSourceField)); - reader.Body.Instructions.Add(instruction); - return () => reader.Body.Instructions.Remove(instruction); - }, CredentialOffenders); - AssertMutation(census, "an unkeyed locator resolving the public bridge store", () => - { - var resolve = typeof(ServiceProviderServiceExtensions).GetMethods().Single(method => method.Name == "GetRequiredService" - && method.IsGenericMethodDefinition && method.GetParameters().Length == 1).MakeGenericMethod(typeof(PostgresBackgroundJobBridgeStore)); - return AddCallProbe(application, "LocatedBridgeStore", application.ImportReference(resolve), OpCodes.Call); - }, CredentialOffenders); - foreach (var wrapped in new[] { false, true }) - AssertMutation(census, "an extra direct or wrapped bridge-store holder", () => + foreach (var opcode in new[] { OpCodes.Call, OpCodes.Callvirt, OpCodes.Ldftn, OpCodes.Ldvirtftn }) + AssertMutation(census, "an extra bridge capability consumer through " + opcode, () => + AddCallProbe(application, "ExtraBridgeCapability", target, opcode), CredentialOffenders); + AssertMutation(census, "an async bridge capability consumer", () => + AddAsyncCallProbe(application, "AsyncBridgeCapability", target), CredentialOffenders); + } + AssertMutation(census, "an extra bridge-store constructor call", () => + AddCallProbe(application, "ExtraBridgeConstruction", constructor, OpCodes.Newobj), CredentialOffenders); + AssertMutation(census, "an extra acquisition helper on the sanctioned bridge store", () => { - var type = AddProbe(application, "ExtraBridgeStoreHolder"); - TypeReference capability = application.ImportReference(store); - if (wrapped) - { - var wrapper = new GenericInstanceType(application.ImportReference(typeof(List<>))); - wrapper.GenericArguments.Add(capability); - capability = wrapper; - } - type.Fields.Add(new FieldDefinition("_store", FieldAttributes.Private, capability)); - return () => application.Types.Remove(type); + var method = AddCall(store, "ExtraBridgeAcquisition", reader, OpCodes.Call); + return () => store.Methods.Remove(method); }, CredentialOffenders); - } - - [Fact] - public void Bridge_credential_census_rejects_changed_signatures_captures_and_missing_subjects() - { - using var census = ProductionCensus.Read(); - var store = census.Types[(InfrastructureAssembly, JobBridgeStore)]; - var bridge = census.Types[(InfrastructureAssembly, JobBridge)]; - foreach (var method in store.Methods.Where(method => method.Name is ".ctor" or "OpenConnectionAsync" or "TryClaimAsync" or "UpdateAsync").ToArray()) - { - AssertMutation(census, "changed visibility on a pinned bridge capability", () => - ChangeAttributes(() => method.Attributes, value => method.Attributes = value, - (method.Attributes & ~MethodAttributes.MemberAccessMask) | (method.IsPublic ? MethodAttributes.Private : MethodAttributes.Public)), CredentialOffenders); - AssertMutation(census, "a static pinned bridge capability", () => - ChangeAttributes(() => method.Attributes, value => method.Attributes = value, method.Attributes | MethodAttributes.Static), CredentialOffenders); - AssertMutation(census, "a changed pinned bridge return type", () => + AssertMutation(census, "a second acquisition inside an approved bridge caller", () => { - var original = method.ReturnType; - method.ReturnType = method.Module.TypeSystem.Object; - return () => method.ReturnType = original; + var body = OwnedBodies(census).Single(item => item.Owner == claim && item.Body.Name == "MoveNext").Body; + var instruction = Instruction.Create(OpCodes.Call, reader); + body.Body.Instructions.Add(instruction); + return () => body.Body.Instructions.Remove(instruction); }, CredentialOffenders); - AssertMutation(census, "a changed pinned bridge parameter type", () => - { - var parameter = method.Parameters[0]; - var original = parameter.ParameterType; - parameter.ParameterType = method.Module.TypeSystem.Int32; - return () => parameter.ParameterType = original; - }, CredentialOffenders); - AssertMutation(census, "a generic pinned bridge capability", () => + foreach (var name in new[] { "ForwardSource", "OpenConnectionAsync", "TryClaimAsync", "UpdateAsync" }) + AssertMutation(census, "a source-forwarding bridge helper or approved-name overload", () => + AddBoundaryFieldGetter(store, name, JobBridgeSourceField), CredentialOffenders); + AssertMutation(census, "a bridge owner forwarding its store capability", () => + AddBoundaryFieldGetter(bridge, "ForwardStore", "P"), CredentialOffenders); + foreach (var opcode in new[] { OpCodes.Ldfld, OpCodes.Ldflda, OpCodes.Stfld }) + AssertMutation(census, "an extra source read, address or write inside the exact reader through " + opcode, () => + { + var instruction = Instruction.Create(opcode, store.Fields.Single(field => field.Name == JobBridgeSourceField)); + reader.Body.Instructions.Add(instruction); + return () => reader.Body.Instructions.Remove(instruction); + }, CredentialOffenders); + AssertMutation(census, "an unkeyed locator resolving the public bridge store", () => { - var parameter = new GenericParameter("Unexpected", method); - method.GenericParameters.Add(parameter); - return () => method.GenericParameters.Remove(parameter); + var resolve = typeof(ServiceProviderServiceExtensions).GetMethods().Single(method => method.Name == "GetRequiredService" + && method.IsGenericMethodDefinition && method.GetParameters().Length == 1).MakeGenericMethod(typeof(PostgresBackgroundJobBridgeStore)); + return AddCallProbe(application, "LocatedBridgeStore", application.ImportReference(resolve), OpCodes.Call); }, CredentialOffenders); + foreach (var wrapped in new[] { false, true }) + AssertMutation(census, "an extra direct or wrapped bridge-store holder", () => + { + var type = AddProbe(application, "ExtraBridgeStoreHolder"); + TypeReference capability = application.ImportReference(store); + if (wrapped) + { + var wrapper = new GenericInstanceType(application.ImportReference(typeof(List<>))); + wrapper.GenericArguments.Add(capability); + capability = wrapper; + } + type.Fields.Add(new FieldDefinition("_store", FieldAttributes.Private, capability)); + return () => application.Types.Remove(type); + }, CredentialOffenders); } - foreach (var (holder, name) in new[] { (store, JobBridgeSourceField), (bridge, "P") }) + + [Fact] + public void Bridge_credential_census_rejects_changed_signatures_captures_and_missing_subjects() { - var field = holder.Fields.Single(item => item.Name == name); - AssertMutation(census, "a public captured bridge capability", () => - ChangeAttributes(() => field.Attributes, value => field.Attributes = value, - (field.Attributes & ~FieldAttributes.FieldAccessMask) | FieldAttributes.Public), CredentialOffenders); - AssertMutation(census, "a static captured bridge capability", () => - ChangeAttributes(() => field.Attributes, value => field.Attributes = value, field.Attributes | FieldAttributes.Static), CredentialOffenders); - AssertMutation(census, "a changed captured bridge capability type", () => + using var census = ProductionCensus.Read(); + var store = census.Types[(InfrastructureAssembly, JobBridgeStore)]; + var bridge = census.Types[(InfrastructureAssembly, JobBridge)]; + foreach (var method in store.Methods.Where(method => method.Name is ".ctor" or "OpenConnectionAsync" or "TryClaimAsync" or "UpdateAsync").ToArray()) { - var original = field.FieldType; - field.FieldType = holder.Module.TypeSystem.Object; - return () => field.FieldType = original; - }, CredentialOffenders); - } - AssertMutation(census, "another guarded-source field on the bridge store", () => - { - var field = new FieldDefinition("_extraSource", FieldAttributes.Private, store.Fields.Single(item => item.Name == JobBridgeSourceField).FieldType); - store.Fields.Add(field); - return () => store.Fields.Remove(field); - }, CredentialOffenders); - foreach (var subject in new[] { store, bridge }) - { - AssertMutation(census, "an unsealed bridge capability subject", () => - ChangeAttributes(() => subject.Attributes, value => subject.Attributes = value, subject.Attributes & ~TypeAttributes.Sealed), CredentialOffenders); - AssertMutation(census, "a missing real bridge capability subject", () => + AssertMutation(census, "changed visibility on a pinned bridge capability", () => + ChangeAttributes(() => method.Attributes, value => method.Attributes = value, + (method.Attributes & ~MethodAttributes.MemberAccessMask) | (method.IsPublic ? MethodAttributes.Private : MethodAttributes.Public)), CredentialOffenders); + AssertMutation(census, "a static pinned bridge capability", () => + ChangeAttributes(() => method.Attributes, value => method.Attributes = value, method.Attributes | MethodAttributes.Static), CredentialOffenders); + AssertMutation(census, "a changed pinned bridge return type", () => + { + var original = method.ReturnType; + method.ReturnType = method.Module.TypeSystem.Object; + return () => method.ReturnType = original; + }, CredentialOffenders); + AssertMutation(census, "a changed pinned bridge parameter type", () => + { + var parameter = method.Parameters[0]; + var original = parameter.ParameterType; + parameter.ParameterType = method.Module.TypeSystem.Int32; + return () => parameter.ParameterType = original; + }, CredentialOffenders); + AssertMutation(census, "a generic pinned bridge capability", () => + { + var parameter = new GenericParameter("Unexpected", method); + method.GenericParameters.Add(parameter); + return () => method.GenericParameters.Remove(parameter); + }, CredentialOffenders); + } + foreach (var (holder, name) in new[] { (store, JobBridgeSourceField), (bridge, "P") }) + { + var field = holder.Fields.Single(item => item.Name == name); + AssertMutation(census, "a public captured bridge capability", () => + ChangeAttributes(() => field.Attributes, value => field.Attributes = value, + (field.Attributes & ~FieldAttributes.FieldAccessMask) | FieldAttributes.Public), CredentialOffenders); + AssertMutation(census, "a static captured bridge capability", () => + ChangeAttributes(() => field.Attributes, value => field.Attributes = value, field.Attributes | FieldAttributes.Static), CredentialOffenders); + AssertMutation(census, "a changed captured bridge capability type", () => + { + var original = field.FieldType; + field.FieldType = holder.Module.TypeSystem.Object; + return () => field.FieldType = original; + }, CredentialOffenders); + } + AssertMutation(census, "another guarded-source field on the bridge store", () => { - var module = subject.Module; - module.Types.Remove(subject); - return () => module.Types.Add(subject); + var field = new FieldDefinition("_extraSource", FieldAttributes.Private, store.Fields.Single(item => item.Name == JobBridgeSourceField).FieldType); + store.Fields.Add(field); + return () => store.Fields.Remove(field); }, CredentialOffenders); + foreach (var subject in new[] { store, bridge }) + { + AssertMutation(census, "an unsealed bridge capability subject", () => + ChangeAttributes(() => subject.Attributes, value => subject.Attributes = value, subject.Attributes & ~TypeAttributes.Sealed), CredentialOffenders); + AssertMutation(census, "a missing real bridge capability subject", () => + { + var module = subject.Module; + module.Types.Remove(subject); + return () => module.Types.Add(subject); + }, CredentialOffenders); + } } } } diff --git a/backend/tests/LearnStack.Tests.Architecture/HangfireRuntimeBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/HangfireRuntimeBoundaryTests.cs index 5a81b9dd9..25ea36da4 100644 --- a/backend/tests/LearnStack.Tests.Architecture/HangfireRuntimeBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/HangfireRuntimeBoundaryTests.cs @@ -204,7 +204,7 @@ private static void CheckHangfireCapabilitySites(SortedSet offenders, callers.Select(caller => caller + ":" + target)); } - public sealed partial class JobLifecycleMutationTests + public sealed class HangfireRuntimeMutationTests { /// ADR-0060: planted controls exercise the same production capability/sink census. diff --git a/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.cs new file mode 100644 index 000000000..9f5049e59 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Architecture/IdentityAuditConventionTests.cs @@ -0,0 +1,133 @@ +using System.Reflection; +using FluentAssertions; +using LearnStack.Application.Audit; +using LearnStack.Application.Persistence; +using LearnStack.Infrastructure.Audit; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identity; +using Mono.Cecil; +using Xunit; + +namespace LearnStack.Tests.Architecture; + +public sealed class IdentityAuditConventionTests +{ + private const string BindingService = "LearnStack.Modules.Identity.Infrastructure.Bindings.GlobalIdentityBindingService"; + private const string InitialMigration = "LearnStack.Modules.Identity.Infrastructure.Persistence.Migrations.create_identity_schema"; + private const string Installer = "LearnStack.Infrastructure.Audit.IdentityCreationWitnessInstaller"; + private const string GlobalSource = "LearnStack.Application.Audit.AuditExecutionCoordinator+GlobalCreationSource"; + + [Fact] + public void Global_Identity_Creation_Uses_The_Common_Audit_Owner() + { + var types = ProductionAssemblies.All().SelectMany(assembly => assembly.GetTypes()).ToArray(); + types.Where(type => type.IsSubclassOf(typeof(GlobalIdentityOwnerDescriptor.MintingSource))) + .Select(type => type.FullName).Should().Equal(BindingService); + types.Where(type => type.IsSubclassOf(typeof(GlobalIdentityCreationReference.MintingSource))) + .Select(type => type.FullName).Should().Equal(GlobalSource); + typeof(GlobalIdentityOwnerDescriptor).GetConstructors().Should().BeEmpty(); + typeof(GlobalIdentityCreationReference).GetConstructors().Should().BeEmpty(); + + Callers(typeof(TransactionExecutionCoordinator).FullName!, "PrepareGlobalIdentityOwnerAsync") + .Should().Equal(BindingService + ".AdoptAsync"); + Callers(typeof(TransactionExecutionCoordinator.PreparedGlobalIdentityOwner).FullName!.Replace('+', '/'), "AdmitSerializedAbsence") + .Should().Equal(BindingService + ".AdoptAsync"); + Callers(typeof(TransactionExecutionCoordinator.PreparedGlobalIdentityOwner).FullName!.Replace('+', '/'), "CompleteExistingAsync") + .Should().Equal(BindingService + ".AdoptAsync"); + Callers(typeof(IAuditStore).FullName!, nameof(IAuditStore.WriteGlobalIdentityPendingAsync)) + .Should().Equal(typeof(TransactionExecutionCoordinator).FullName + ".ExecuteFrameAsync"); + Callers(typeof(IAuditStore).FullName!, nameof(IAuditStore.ReconcileGlobalIdentityAsync)) + .Should().Equal(typeof(AuditExecutionCoordinator).FullName + ".ReconcileAsync"); + + var audit = File.ReadAllText(Path.Combine(SourceScan.SourceRoot, + "LearnStack.Infrastructure.Audit", "PostgresAuditStore.cs")); + audit.Should().Contain("INSERT INTO audit_log"); + var installer = File.ReadAllText(Path.Combine(SourceScan.SourceRoot, + "LearnStack.Infrastructure.Audit", "IdentityCreationWitnessInstaller.cs")); + installer.Should().NotContain("INSERT INTO audit_log", "the installer defines witnesses, never an independent writer"); + } + + [Fact] + public void Identity_infrastructure_core_edges_are_confined_to_exact_types_and_members() + { + using var module = ModuleDefinition.ReadModule(typeof(GlobalIdentityBindingService).Assembly.Location); + var inspected = module.Types.Where(type => type.Name != "").ToArray(); + inspected.Should().NotBeEmpty(); + inspected.SelectMany(CoreEdgeViolations).Should().BeEmpty( + "the Identity-only assembly exceptions do not admit any other common Application or Audit dependency"); + var migration = module.GetType(InitialMigration); + migration.Should().NotBeNull(); + Il.MethodsNaming(migration!, Installer).Should().Equal("Down", "Up"); + Callers(Installer, "Install").Should().Equal(InitialMigration + ".Up"); + Callers(Installer, "Remove").Should().Equal(InitialMigration + ".Down"); + } + + [Fact] + public void A_new_minter_or_a_borrowed_core_edge_is_rejected() + { + var types = new[] { typeof(BorrowedDescriptorSource), typeof(BorrowedCreationSource) }; + types.Count(type => type.IsSubclassOf(typeof(GlobalIdentityOwnerDescriptor.MintingSource)) + && type.FullName != BindingService).Should().Be(1); + types.Count(type => type.IsSubclassOf(typeof(GlobalIdentityCreationReference.MintingSource)) + && type.FullName != GlobalSource).Should().Be(1); + using var module = ModuleDefinition.ReadModule(typeof(IdentityAuditConventionTests).Assembly.Location); + CoreEdgeViolations(module.GetType(typeof(BorrowedCoreEdge).FullName!.Replace('+', '/'))) + .Should().ContainSingle().Which.Should().Contain(nameof(AuditExecutionCoordinator)); + } + + [Fact] + public void The_enrollment_reader_has_no_public_mutator_and_does_not_allocate_a_unit() + { + typeof(IGlobalIdentityEnrollment).GetMembers().Select(member => member.Name) + .Should().BeEquivalentTo("IsActive", "get_IsActive"); + typeof(GlobalIdentityEnrollment).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) + .Select(method => method.Name).Should().Equal("get_IsActive"); + typeof(GlobalIdentityEnrollment).GetConstructors().Should().ContainSingle() + .Which.GetParameters().Should().BeEmpty(); + using var module = ModuleDefinition.ReadModule(typeof(GlobalIdentityEnrollment).Assembly.Location); + var reader = module.GetType(typeof(GlobalIdentityEnrollment).FullName!); + Il.Methods(reader).SelectMany(method => method.Definition.HasBody + ? method.Definition.Body.Instructions.Select(instruction => instruction.Operand).OfType() : []) + .Where(method => method.Name is "GetRequiredService" or "CreateConnection" or "Open" or "OpenAsync") + .Should().BeEmpty(); + Callers(typeof(GlobalIdentityEnrollment).FullName!, "Attach") + .Should().Equal(typeof(NpgsqlUnitOfWork).FullName + ".ctor"); + } + + private static IEnumerable CoreEdgeViolations(TypeDefinition type) + { + foreach (var reference in Il.ReferencedTypeReferences(type) + .Where(reference => reference is not GenericParameter) + .Where(reference => reference.Scope.Name is "LearnStack.Application" or "LearnStack.Infrastructure.Audit") + .DistinctBy(reference => reference.FullName)) + { + var allowed = type.FullName == BindingService && reference.FullName is + "LearnStack.Application.Audit.AuditExecutionCoordinator" + or "LearnStack.Application.Persistence.TransactionExecutionCoordinator" + or "LearnStack.Application.Persistence.TransactionExecutionCoordinator/PreparedGlobalIdentityOwner" + || type.FullName == InitialMigration && reference.FullName == Installer; + if (!allowed) yield return type.FullName + " -> " + reference.FullName; + } + } + + 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(); + + private sealed class BorrowedDescriptorSource : GlobalIdentityOwnerDescriptor.MintingSource; + private sealed class BorrowedCreationSource : GlobalIdentityCreationReference.MintingSource; + private sealed class BorrowedCoreEdge + { + public static Type Named() => typeof(AuditExecutionCoordinator); + } +} diff --git a/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs new file mode 100644 index 000000000..e39335b23 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Architecture/IdentityFoundationConventionTests.cs @@ -0,0 +1,173 @@ +using System.Collections.Immutable; +using System.Text.RegularExpressions; +using FluentAssertions; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; +using Mono.Cecil; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Xunit; + +namespace LearnStack.Tests.Architecture; + +public sealed class IdentityFoundationConventionTests +{ + private static readonly string[] ContextualSaveOwners = + ["LearnStack.Modules.Identity.Infrastructure.Persistence.ContextualIdentityStorageControl.SaveAsync"]; + private static readonly ImmutableHashSet<(PermissionScope Scope, string Key)> Expected = + [ + (PermissionScope.Tenant, "identity.membership.admin"), + (PermissionScope.Organization, "identity.membership.admin"), + (PermissionScope.Tenant, "identity.role.admin"), + (PermissionScope.Tenant, "identity.membership_profile.write"), + (PermissionScope.Organization, "identity.membership_profile.write"), + ]; + + [Fact] + public void Permission_Definitions_DeclareScope() + { + var manifest = IdentityFoundationManifest.Version1; + RegistryViolations(manifest.Definitions).Should().BeEmpty(); + manifest.Definitions.Should().NotBeEmpty(); + manifest.Templates.Should().HaveCount(8); + manifest.Templates.Select(template => template.BuiltInKey).Distinct().Should().HaveCount(7); + foreach (var template in manifest.Templates) + { + template.Scope.Should().NotBe(PermissionScope.Platform); + template.Grants.All(grant => grant.Scope == template.Scope && Expected.Contains((grant.Scope, grant.Key))) + .Should().BeTrue("the finite manifest deliberately includes empty templates"); + } + } + + [Fact] + public void Registry_controls_detect_missing_duplicate_inactive_and_wrong_scope_definitions() + { + var definitions = IdentityFoundationManifest.Version1.Definitions; + RegistryViolations(definitions.RemoveAt(0)).Should().NotBeEmpty(); + RegistryViolations(definitions.Add(definitions[0])).Should().NotBeEmpty(); + RegistryViolations(definitions.SetItem(0, new(definitions[0].Scope, definitions[0].Key, false))) + .Should().NotBeEmpty(); + RegistryViolations(definitions.SetItem(0, new(PermissionScope.Platform, definitions[0].Key))) + .Should().NotBeEmpty(); + } + + [Fact] + public void Identity_Seed_Uses_Finite_Adopted_Manifests() + { + var manifest = IdentityFoundationManifest.Version1; + manifest.Version.Should().Be(1); + manifest.Fingerprint.Should().MatchRegex("^[a-f0-9]{64}$"); + manifest.TenantAdminKernel.Select(pair => (pair.Scope, pair.Key)).Should().BeEquivalentTo( + new[] { (PermissionScope.Tenant, "identity.membership.admin"), (PermissionScope.Tenant, "identity.role.admin") }); + manifest.FindTemplate(BuiltInRoleKey.TenantAdmin, PermissionScope.Tenant)!.Grants.Should().HaveCount(3, + "the initial template includes profile write beyond the two-pair administrator minimum"); + + var actor = UserId.From(Guid.Parse("01930000-0000-7000-8000-00000000a001")); + IIdentityPermissionRequest[] operations = + [ + new InitializeSeedRoleCommand(Guid.Empty, BuiltInRoleKey.TenantAdmin, PermissionScope.Tenant, 1, ""), + new CreateFirstSeedAdminMembershipCommand(Guid.Empty, actor, Guid.Empty, 1, ""), + new CreateSeedMembershipCommand(Guid.Empty, actor, Guid.Empty, PermissionScope.Tenant, 1, ""), + new CreateSeedMembershipCommand(Guid.Empty, actor, Guid.Empty, PermissionScope.Organization, 1, ""), + new SetSeedMembershipProfileCommand(Guid.Empty, actor, Guid.Empty, PermissionScope.Tenant, null, null, 1, ""), + new SetSeedMembershipProfileCommand(Guid.Empty, actor, Guid.Empty, PermissionScope.Organization, null, null, 1, ""), + ]; + operations.Select(operation => operation.RequiredPermission).Distinct().Should().BeEquivalentTo(manifest.Definitions); + var permissions = operations.Select(operation => operation.RequiredPermission).ToArray(); + PermissionMappingViolations(permissions).Should().BeEmpty("each actual command/variant owns its exact scoped identity"); + (permissions[0], permissions[1]) = (permissions[1], permissions[0]); + PermissionMappingViolations(permissions).Should().NotBeEmpty("a swapped mapping preserves the distinct set but violates command ownership"); + var sql = new Microsoft.EntityFrameworkCore.Migrations.MigrationBuilder("Npgsql.EntityFrameworkCore.PostgreSQL"); + LearnStack.Modules.Identity.Infrastructure.Persistence.ContextualIdentityStorageDdl.Install(sql); + var installed = string.Join('\n', sql.Operations.OfType() + .Select(operation => operation.Sql)); + installed.Should().Contain(manifest.RegistrySqlValues).And.Contain(manifest.RolePairsSqlValues) + .And.Contain(manifest.GrantSqlValues).And.Contain(manifest.KernelSqlValues); + } + + [Fact] + public void Identity_Membership_Invariants_Use_Fresh_Ordered_Locks() + { + string[] admitted = + [ + "LearnStack.Modules.Identity.Application.Seeding.InitializeSeedRoleCommandHandler.Handle", + "LearnStack.Modules.Identity.Application.Seeding.SeedMembershipCreation.CreateAsync", + "LearnStack.Modules.Identity.Application.Seeding.SetSeedMembershipProfileCommandHandler.Handle", + ]; + Callers(typeof(IIdentityMutationLocks).FullName!, nameof(IIdentityMutationLocks.AcquireAsync)) + .Should().BeEquivalentTo(admitted); + Callers(typeof(IIdentityMutationLocks).FullName!, nameof(IIdentityMutationLocks.RequireCurrent)) + .Should().BeEquivalentTo(admitted); + Callers(typeof(DatabaseFacade).FullName!, "set_AutoSavepointsEnabled").Should().Equal(ContextualSaveOwners, + "only the closed whole-graph adapter may suspend automatic savepoints, with finally restoration and full rollback on failure"); + var root = SourceScan.SourceRoot; + var files = Directory.EnumerateFiles(root, "*.cs", SearchOption.AllDirectories) + .Where(path => !path.Split(Path.DirectorySeparatorChar).Intersect(["obj", "bin"]).Any()) + .Select(File.ReadAllText); + files.SelectMany(SessionCalls).Should().BeEmpty("production uses transaction-level advisory calls only"); + var helper = File.ReadAllText(Path.Combine(root, "LearnStack.Infrastructure", "Persistence", "IdentityMutationLocks.cs")); + helper.Should().Contain("GetTenantContextAnnouncement").And.Contain("Generation") + .And.Contain("ReferenceEquals(_transaction, unit.Transaction)") + .And.Contain("ReferenceEquals(_connection, unit.Connection)"); + var code = SourceText.WithoutComments(helper); + code.IndexOf("foreach (var user in plan.UserIds)", StringComparison.Ordinal) + .Should().BeLessThan(code.IndexOf("IdentityAdvisoryLockKey.ForTenant", StringComparison.Ordinal)); + var save = File.ReadAllText(Path.Combine(root, "Modules", "Identity", "LearnStack.Modules.Identity.Infrastructure", + "Persistence", "ContextualIdentityStores.cs")); + SourceText.WithoutWhitespace(save).Should().Contain("finally{db.Database.AutoSavepointsEnabled=savepoints;}") + .And.Contain("unit.MarkRollbackOnly()"); + } + + [Theory] + [InlineData("SELECT pg_advisory_lock(1)")] + [InlineData("SELECT pg_try_advisory_lock_shared(1)")] + [InlineData("SELECT pg_advisory_unlock_all()")] + public void Session_api_control_detects_a_planted_borrowed_lifetime(string sql) + { + SessionCalls(sql).Should().ContainSingle(); + SessionCalls("SELECT pg_advisory_xact_lock(1), pg_advisory_xact_lock_shared(2)").Should().BeEmpty(); + SessionCalls("// pg_advisory_lock(1)\nSELECT 1").Should().BeEmpty(); + } + + private static IEnumerable RegistryViolations(IEnumerable definitions) + { + var actual = definitions.ToArray(); + if (actual.Length != Expected.Count || actual.Select(definition => (definition.Scope, definition.Key)).Distinct().Count() != actual.Length) + yield return "missing-or-duplicate"; + if (actual.Any(definition => !definition.IsActive || !Expected.Contains((definition.Scope, definition.Key)))) + yield return "inactive-or-scope"; + } + + private static IEnumerable PermissionMappingViolations(PermissionDefinition[] actual) + { + (PermissionScope Scope, string Key)[] expected = + [ + (PermissionScope.Tenant, "identity.role.admin"), + (PermissionScope.Tenant, "identity.membership.admin"), + (PermissionScope.Tenant, "identity.membership.admin"), + (PermissionScope.Organization, "identity.membership.admin"), + (PermissionScope.Tenant, "identity.membership_profile.write"), + (PermissionScope.Organization, "identity.membership_profile.write"), + ]; + if (actual.Length != expected.Length) yield return "population"; + for (var index = 0; index < Math.Min(actual.Length, expected.Length); index++) + if ((actual[index].Scope, actual[index].Key) != expected[index]) yield return "command-permission"; + } + + private static IEnumerable SessionCalls(string source) => Regex.Matches(SourceText.WithoutComments(source), + @"\bpg_(?:try_)?advisory_(?:lock|unlock)(?:_shared|_all)?\s*\(", RegexOptions.IgnoreCase) + .Select(match => match.Value); + + 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/IntegrationDeliveryBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryBoundaryTests.cs index b20c41dda..786ba5bf8 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryBoundaryTests.cs @@ -95,55 +95,58 @@ public void Integration_handler_discovery_sees_inherited_generic_and_explicit_co "abstract bases and unrelated HandleAsync methods are not concrete subscribers"); } - [Fact] - public void Integration_invocation_census_rejects_all_layer_direct_interface_helper_async_and_delegate_bypasses() + public sealed class IntegrationInvocationMutationTests { - using var census = ProductionCensus.Read(); - var types = census.Types; - var handler = types[(typeof(InitializeContentTypeDefaultHandler).Assembly.GetName().Name!, typeof(InitializeContentTypeDefaultHandler).FullName!)]; - var handle = handler.Methods.Single(method => method.Name == "HandleAsync"); - var constructor = handler.Methods.Single(method => method.IsConstructor && !method.IsStatic); - var contract = typeof(IIntegrationEventHandler).GetMethod("HandleAsync")!; - var subscription = types[(InfrastructureAssembly, IntegrationSubscription)]; - var capability = subscription.Properties.Single(property => property.Name == "Handle").GetMethod; - var invoke = types[(InfrastructureAssembly, DeliveryExecutorType)].Methods.Single(method => method.Name == "InvokeAsync"); - - foreach (var module in census.Modules) + [Fact] + public void Integration_invocation_census_rejects_all_layer_direct_interface_helper_async_and_delegate_bypasses() { - AssertMutation(census, "direct handler invocation in " + module.Name, () => - AddCallProbe(module, "DirectIntegrationInvocation", handle, OpCodes.Call), IntegrationInvocationOffenders); - AssertMutation(census, "interface handler invocation in " + module.Name, () => - AddCallProbe(module, "InterfaceIntegrationInvocation", module.ImportReference(contract), OpCodes.Callvirt), IntegrationInvocationOffenders); - AssertMutation(census, "handler construction in " + module.Name, () => - AddCallProbe(module, "DirectIntegrationConstruction", constructor, OpCodes.Newobj), IntegrationInvocationOffenders); - } + using var census = ProductionCensus.Read(); + var types = census.Types; + var handler = types[(typeof(InitializeContentTypeDefaultHandler).Assembly.GetName().Name!, typeof(InitializeContentTypeDefaultHandler).FullName!)]; + var handle = handler.Methods.Single(method => method.Name == "HandleAsync"); + var constructor = handler.Methods.Single(method => method.IsConstructor && !method.IsStatic); + var contract = typeof(IIntegrationEventHandler).GetMethod("HandleAsync")!; + var subscription = types[(InfrastructureAssembly, IntegrationSubscription)]; + var capability = subscription.Properties.Single(property => property.Name == "Handle").GetMethod; + var invoke = types[(InfrastructureAssembly, DeliveryExecutorType)].Methods.Single(method => method.Name == "InvokeAsync"); + + foreach (var module in census.Modules) + { + AssertMutation(census, "direct handler invocation in " + module.Name, () => + AddCallProbe(module, "DirectIntegrationInvocation", handle, OpCodes.Call), IntegrationInvocationOffenders); + AssertMutation(census, "interface handler invocation in " + module.Name, () => + AddCallProbe(module, "InterfaceIntegrationInvocation", module.ImportReference(contract), OpCodes.Callvirt), IntegrationInvocationOffenders); + AssertMutation(census, "handler construction in " + module.Name, () => + AddCallProbe(module, "DirectIntegrationConstruction", constructor, OpCodes.Newobj), IntegrationInvocationOffenders); + } - var application = census.Modules.Single(module => module.Assembly.Name.Name == DeliveryApplication); - foreach (var target in new[] { handle, capability, invoke }) - { - foreach (var opcode in new[] { OpCodes.Call, OpCodes.Callvirt, OpCodes.Ldftn, OpCodes.Ldvirtftn }) - AssertMutation(census, "an extra invocation capability through " + opcode.Name, () => - AddCallProbe(application, "IntegrationInvocationHelper", target, opcode), IntegrationInvocationOffenders); - AssertMutation(census, "an asynchronous invocation helper", () => - AddAsyncCallProbe(application, "AsyncIntegrationInvocationHelper", target), IntegrationInvocationOffenders); - } + var application = census.Modules.Single(module => module.Assembly.Name.Name == DeliveryApplication); + foreach (var target in new[] { handle, capability, invoke }) + { + foreach (var opcode in new[] { OpCodes.Call, OpCodes.Callvirt, OpCodes.Ldftn, OpCodes.Ldvirtftn }) + AssertMutation(census, "an extra invocation capability through " + opcode.Name, () => + AddCallProbe(application, "IntegrationInvocationHelper", target, opcode), IntegrationInvocationOffenders); + AssertMutation(census, "an asynchronous invocation helper", () => + AddAsyncCallProbe(application, "AsyncIntegrationInvocationHelper", target), IntegrationInvocationOffenders); + } - var executor = types[(InfrastructureAssembly, DeliveryExecutorType)]; - AssertMutation(census, "another helper inside the real executor", () => - { - var method = AddCall(executor, "UnexpectedInvocationHelper", invoke, OpCodes.Call); - return () => executor.Methods.Remove(method); - }, IntegrationInvocationOffenders); - var invokeBody = OwnedBodies(census).Single(item => item.Owner == invoke && item.Body.Name == "MoveNext").Body; - var readHandle = invokeBody.Body.Instructions.Single(instruction => instruction.Operand is MethodReference method - && method.Name == "get_Handle" && SameType(method.DeclaringType, subscription)); - AssertMutation(census, "a missing actual reflective invocation capability", () => - ReplaceInstruction(readHandle, OpCodes.Ldstr, "removed invocation capability"), IntegrationInvocationOffenders); - - var clean = AddProbe(application, "CleanIntegrationMetadataObserver"); - AddCall(clean, "Observe", subscription.Properties.Single(property => property.Name == "EventType").GetMethod, OpCodes.Callvirt); - try { IntegrationInvocationOffenders(census).Should().BeEmpty("reading event identity does not invoke a subscriber"); } - finally { application.Types.Remove(clean); } + var executor = types[(InfrastructureAssembly, DeliveryExecutorType)]; + AssertMutation(census, "another helper inside the real executor", () => + { + var method = AddCall(executor, "UnexpectedInvocationHelper", invoke, OpCodes.Call); + return () => executor.Methods.Remove(method); + }, IntegrationInvocationOffenders); + var invokeBody = OwnedBodies(census).Single(item => item.Owner == invoke && item.Body.Name == "MoveNext").Body; + var readHandle = invokeBody.Body.Instructions.Single(instruction => instruction.Operand is MethodReference method + && method.Name == "get_Handle" && SameType(method.DeclaringType, subscription)); + AssertMutation(census, "a missing actual reflective invocation capability", () => + ReplaceInstruction(readHandle, OpCodes.Ldstr, "removed invocation capability"), IntegrationInvocationOffenders); + + var clean = AddProbe(application, "CleanIntegrationMetadataObserver"); + AddCall(clean, "Observe", subscription.Properties.Single(property => property.Name == "EventType").GetMethod, OpCodes.Callvirt); + try { IntegrationInvocationOffenders(census).Should().BeEmpty("reading event identity does not invoke a subscriber"); } + finally { application.Types.Remove(clean); } + } } [Fact] diff --git a/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs index 72174e388..1f7e11961 100644 --- a/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/IntegrationDeliveryLifecycleBoundaryTests.cs @@ -20,6 +20,9 @@ public sealed partial class OutboxDispatchConventionTests private const string LifecycleScope = "LearnStack.SharedKernel.Persistence.IUnitOfWorkScope"; private const string LifecycleAdapter = "LearnStack.Infrastructure.Persistence.NpgsqlUnitOfWork"; private const string LifecycleFrame = LifecycleAdapter + "/Frame"; + private const string LifecycleGlobalPrepared = DeliveryCoordinator + "/PreparedGlobalIdentityOwner"; + private const string LifecycleIdentityAssembly = "LearnStack.Modules.Identity.Infrastructure"; + private const string LifecycleIdentityBindings = "LearnStack.Modules.Identity.Infrastructure.Bindings."; private const string LifecycleAcceptance = "LearnStack.Infrastructure.Messaging.PostgresDeliveryAcceptance"; private const string LifecyclePlatform = "LearnStack.Infrastructure.MultiTenancy.PlatformAdminScope"; private const string LifecycleTask = "System.Threading.Tasks.Task"; @@ -41,143 +44,154 @@ public void Integration_delivery_lifecycle_stays_with_its_enumerated_owners() "Fix: let the common owner fence and complete business delivery; retain only the named acceptance, persistence and standalone transaction owners"); } - [Fact] - public void Integration_delivery_lifecycle_census_rejects_typed_helper_async_delegate_and_missing_paths() + public sealed class DeliveryLifecycleMutationTests { - using var census = ProductionCensus.Read(); - var types = census.Types; - var unit = types[(KernelAssembly, LifecycleUnit)]; - var scope = types[(KernelAssembly, LifecycleScope)]; - var adapter = types[(InfrastructureAssembly, LifecycleAdapter)]; - var frame = types[(InfrastructureAssembly, LifecycleFrame)]; - var application = census.Modules.Single(module => module.Assembly.Name.Name == DeliveryApplication); - var capabilities = new[] { unit, adapter }.SelectMany(type => type.Methods.Where(method => - method.Name is "BeginTransactionAsync" or "CommitAsync" or "RollbackAsync" or "SetTenantContextAsync")) - .Concat(new[] { scope, frame }.SelectMany(type => type.Methods.Where(method => method.Name is "CompleteAsync" or "FailAsync"))) - .Concat(frame.Methods.Where(method => method.Name == "FailOwnedAsync")) - .Cast().Concat(new[] { typeof(DbTransaction), typeof(IDbTransaction), typeof(NpgsqlTransaction), - typeof(IDbContextTransaction), typeof(RelationalTransaction), typeof(DatabaseFacade) } - .SelectMany(type => type.GetMethods().Where(method => LifecycleTerminalMethods.Contains(method.Name, StringComparer.Ordinal) - || LifecycleFacadeTerminalMethods.Contains(method.Name, StringComparer.Ordinal)) - .Where(method => - method.GetParameters().Length == 0 || method.GetParameters() is [{ ParameterType: var parameter }] && parameter == typeof(CancellationToken))) - .Select(method => application.ImportReference(method))).ToArray(); - foreach (var capability in capabilities) + [Fact] + public void Integration_delivery_lifecycle_census_rejects_typed_helper_async_delegate_and_missing_paths() { - foreach (var opcode in new[] { OpCodes.Call, OpCodes.Callvirt, OpCodes.Ldftn, OpCodes.Ldvirtftn }) - AssertMutation(census, "extra typed lifecycle authority through " + opcode.Name, () => - AddCallProbe(application, "IntegrationLifecycleEscape", capability, opcode), IntegrationLifecycleOffenders); - AssertMutation(census, "an asynchronous lifecycle helper", () => - AddAsyncCallProbe(application, "AsyncIntegrationLifecycleEscape", capability), IntegrationLifecycleOffenders); - } - foreach (var module in census.Modules) - AssertMutation(census, "a lifecycle bypass in " + module.Name, () => - AddCallProbe(module, "IntegrationLifecycleLayerEscape", unit.Methods.Single(method => method.Name == "CommitAsync"), OpCodes.Callvirt), IntegrationLifecycleOffenders); + using var census = ProductionCensus.Read(); + var types = census.Types; + var unit = types[(KernelAssembly, LifecycleUnit)]; + var scope = types[(KernelAssembly, LifecycleScope)]; + var adapter = types[(InfrastructureAssembly, LifecycleAdapter)]; + var frame = types[(InfrastructureAssembly, LifecycleFrame)]; + var application = census.Modules.Single(module => module.Assembly.Name.Name == DeliveryApplication); + var capabilities = new[] { unit, adapter }.SelectMany(type => type.Methods.Where(method => + method.Name is "BeginTransactionAsync" or "CommitAsync" or "RollbackAsync" or "SetTenantContextAsync")) + .Concat(new[] { scope, frame }.SelectMany(type => type.Methods.Where(method => method.Name is "CompleteAsync" or "FailAsync"))) + .Concat(frame.Methods.Where(method => method.Name == "FailOwnedAsync")) + .Cast().Concat(new[] { typeof(DbTransaction), typeof(IDbTransaction), typeof(NpgsqlTransaction), + typeof(IDbContextTransaction), typeof(RelationalTransaction), typeof(DatabaseFacade) } + .SelectMany(type => type.GetMethods().Where(method => LifecycleTerminalMethods.Contains(method.Name, StringComparer.Ordinal) + || LifecycleFacadeTerminalMethods.Contains(method.Name, StringComparer.Ordinal)) + .Where(method => + method.GetParameters().Length == 0 || method.GetParameters() is [{ ParameterType: var parameter }] && parameter == typeof(CancellationToken))) + .Select(method => application.ImportReference(method))).ToArray(); + foreach (var capability in capabilities) + { + foreach (var opcode in new[] { OpCodes.Call, OpCodes.Callvirt, OpCodes.Ldftn, OpCodes.Ldvirtftn }) + AssertMutation(census, "extra typed lifecycle authority through " + opcode.Name, () => + AddCallProbe(application, "IntegrationLifecycleEscape", capability, opcode), IntegrationLifecycleOffenders); + AssertMutation(census, "an asynchronous lifecycle helper", () => + AddAsyncCallProbe(application, "AsyncIntegrationLifecycleEscape", capability), IntegrationLifecycleOffenders); + } + foreach (var module in census.Modules) + AssertMutation(census, "a lifecycle bypass in " + module.Name, () => + AddCallProbe(module, "IntegrationLifecycleLayerEscape", unit.Methods.Single(method => method.Name == "CommitAsync"), OpCodes.Callvirt), IntegrationLifecycleOffenders); - foreach (var subject in new[] { adapter, frame }) - { - var module = subject.Module; - var declaring = subject.DeclaringType; - AssertMutation(census, "a missing real lifecycle implementation", () => + foreach (var subject in new[] { adapter, frame }) { - if (declaring is null) module.Types.Remove(subject); - else declaring.NestedTypes.Remove(subject); - return () => + var module = subject.Module; + var declaring = subject.DeclaringType; + AssertMutation(census, "a missing real lifecycle implementation", () => { - if (declaring is null) module.Types.Add(subject); - else declaring.NestedTypes.Add(subject); - }; + if (declaring is null) module.Types.Remove(subject); + else declaring.NestedTypes.Remove(subject); + return () => + { + if (declaring is null) module.Types.Add(subject); + else declaring.NestedTypes.Add(subject); + }; + }, IntegrationLifecycleOffenders); + } + AssertMutation(census, "an extra unit implementation", () => + { + var probe = AddProbe(application, "AdditionalIntegrationUnit"); + probe.Interfaces.Add(new InterfaceImplementation(application.ImportReference(unit))); + return () => application.Types.Remove(probe); }, IntegrationLifecycleOffenders); - } - AssertMutation(census, "an extra unit implementation", () => - { - var probe = AddProbe(application, "AdditionalIntegrationUnit"); - probe.Interfaces.Add(new InterfaceImplementation(application.ImportReference(unit))); - return () => application.Types.Remove(probe); - }, IntegrationLifecycleOffenders); - var complete = OwnedBodies(census).Where(item => item.Owner.DeclaringType.FullName == DeliveryCoordinator - && item.Owner.Name == "ExecuteFrameAsync").SelectMany(item => item.Body.Body.Instructions) - .Single(instruction => instruction.Operand is MethodReference target && target.Name == "CompleteAsync" - && SameType(target.DeclaringType, scope)); - AssertMutation(census, "a missing real owner completion site", () => - ReplaceInstruction(complete, OpCodes.Ldstr, "missing owner completion"), IntegrationLifecycleOffenders); - var physicalCommit = OwnedBodies(census).Where(item => item.Owner.DeclaringType.FullName == LifecycleAdapter - && item.Owner.Name == "CommitFrameAsync").SelectMany(item => item.Body.Body.Instructions) - .Single(instruction => instruction.Operand is MethodReference target - && IntegrationLifecycleCapability(target, types) == "database.CommitAsync"); - AssertMutation(census, "a missing real physical completion site", () => - ReplaceInstruction(physicalCommit, OpCodes.Ldstr, "missing physical completion"), IntegrationLifecycleOffenders); - var ownedFailure = frame.Methods.Single(method => method.Name == "FailOwnedAsync"); - AssertMutation(census, "an exposed private frame cleanup capability", () => - ChangeAttributes(() => ownedFailure.Attributes, value => ownedFailure.Attributes = value, - (ownedFailure.Attributes & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Public), IntegrationLifecycleOffenders); - var cleanupCalls = OwnedBodies(census).Where(item => item.Owner.DeclaringType == frame) - .SelectMany(item => item.Body.Body.Instructions).Where(instruction => instruction.Operand is MethodReference target - && IntegrationLifecycleCapability(target, types) == "owned-frame.fail").ToArray(); - cleanupCalls.Should().HaveCount(2, "only explicit frame failure and disposal share the private rollback cleanup"); - foreach (var call in cleanupCalls) - AssertMutation(census, "a missing real private frame cleanup path", () => - ReplaceInstruction(call, OpCodes.Nop, null!), IntegrationLifecycleOffenders); - foreach (var (assembly, type, name, parameters, terminalCapability) in new[] - { - (AuditAssembly, AuditStore, "WriteOwnTransactionCoreAsync", - new[] { "LearnStack.SharedKernel.Audit.AuditEntryDraft", "LearnStack.SharedKernel.Jobs.JobApplicationAuxiliaryResources", BoundaryCancellation }, "database.CommitAsync"), - (InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobControlStore", "CommitAsync", - new[] { "LearnStack.Infrastructure.Jobs.BackgroundJobControlResources", BoundaryCancellation }, "database.CommitAsync"), - (InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobTerminalStore", "CommitAsync", - new[] { "LearnStack.Infrastructure.Jobs.BackgroundJobControlResources", BoundaryCancellation }, "database.CommitAsync"), - (InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobControlStore", "ProbeCommitAsync", - new[] { "LearnStack.Infrastructure.Jobs.BackgroundJobCommitProbe", BoundaryCancellation }, "database.RollbackAsync"), - (InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobControlStore", "ProbeExternalRecoveryAsync", - new[] { "LearnStack.Infrastructure.Jobs.OwnedBackgroundJobExternalRecovery", "LearnStack.Infrastructure.Jobs.BackgroundJobCommitProbe", BoundaryCancellation }, "database.RollbackAsync"), - (InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobControlStore", "ProbeExternalCheckpointAsync", - new[] { "LearnStack.Infrastructure.Jobs.BackgroundJobCheckpointHistoryOrigin", BoundaryCancellation }, "database.RollbackAsync"), - (InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobControlStore", "ProbeExternalTerminalNoStartAcquisitionAsync", - new[] { "LearnStack.Infrastructure.Jobs.OwnedBackgroundJobExternalRecovery", "LearnStack.Infrastructure.Jobs.BackgroundJobCommitProbe", BoundaryCancellation }, "database.RollbackAsync"), - (InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobControlStore", "ReadDurableObservationAsync", - new[] { "LearnStack.Infrastructure.Jobs.BackgroundJobObservationManifest", "System.Collections.Generic.IReadOnlyCollection`1", BoundaryCancellation }, "database.RollbackAsync"), - }) - { - var owner = types[(assembly, type)].Methods.Single(method => method.Name == name && ParametersMatch(method, parameters)); - var terminals = OwnedBodies(census).Where(item => item.Owner == owner) + var complete = OwnedBodies(census).Where(item => item.Owner.DeclaringType.FullName == DeliveryCoordinator + && item.Owner.Name == "ExecuteFrameAsync").SelectMany(item => item.Body.Body.Instructions) + .Single(instruction => instruction.Operand is MethodReference target && target.Name == "CompleteAsync" + && SameType(target.DeclaringType, scope)); + AssertMutation(census, "a missing real owner completion site", () => + ReplaceInstruction(complete, OpCodes.Ldstr, "missing owner completion"), IntegrationLifecycleOffenders); + var physicalCommit = OwnedBodies(census).Where(item => item.Owner.DeclaringType.FullName == LifecycleAdapter + && item.Owner.Name == "CommitFrameAsync").SelectMany(item => item.Body.Body.Instructions) + .Single(instruction => instruction.Operand is MethodReference target + && IntegrationLifecycleCapability(target, types) == "database.CommitAsync"); + AssertMutation(census, "a missing real physical completion site", () => + ReplaceInstruction(physicalCommit, OpCodes.Ldstr, "missing physical completion"), IntegrationLifecycleOffenders); + var ownedFailure = frame.Methods.Single(method => method.Name == "FailOwnedAsync"); + AssertMutation(census, "an exposed private frame cleanup capability", () => + ChangeAttributes(() => ownedFailure.Attributes, value => ownedFailure.Attributes = value, + (ownedFailure.Attributes & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Public), IntegrationLifecycleOffenders); + var cleanupCalls = OwnedBodies(census).Where(item => item.Owner.DeclaringType == frame) .SelectMany(item => item.Body.Body.Instructions).Where(instruction => instruction.Operand is MethodReference target - && IntegrationLifecycleCapability(target, types) == terminalCapability).ToArray(); - terminals.Should().ContainSingle("the exact job helper owner must execute its real physical terminal operation"); - AssertMutation(census, "a missing actual job helper terminal operation in " + MethodId(owner), () => - ReplaceInstruction(terminals[0], OpCodes.Ldstr, "missing job helper terminal operation"), IntegrationLifecycleOffenders); - } - var announcements = OwnedBodies(census).SelectMany(item => item.Body.Body.Instructions) - .Where(instruction => instruction.Operand is MethodReference target - && IntegrationLifecycleCapability(target, types) == "unit.announce").ToArray(); - announcements.Should().HaveCount(3, "Fix: retain the ordinary owner and both durable transport announcement sites"); - foreach (var announcement in announcements) - AssertMutation(census, "a missing real tenant announcement site", () => - ReplaceInstruction(announcement, OpCodes.Ldstr, "missing tenant announcement"), IntegrationLifecycleOffenders); - var clean = AddProbe(application, "CleanIntegrationLifecycleObserver"); - foreach (var method in unit.Methods.Where(method => method.IsGetter || method.Name == "MarkRollbackOnly") - .Concat(scope.Methods.Where(method => method.IsGetter))) - AddCall(clean, "Observe" + method.Name, method, OpCodes.Callvirt); - try { IntegrationLifecycleOffenders(census).Should().BeEmpty("ambient reads and poisoning cannot grant commit ownership"); } - finally { application.Types.Remove(clean); } + && IntegrationLifecycleCapability(target, types) == "owned-frame.fail").ToArray(); + cleanupCalls.Should().HaveCount(2, "only explicit frame failure and disposal share the private rollback cleanup"); + foreach (var call in cleanupCalls) + AssertMutation(census, "a missing real private frame cleanup path", () => + ReplaceInstruction(call, OpCodes.Nop, null!), IntegrationLifecycleOffenders); + foreach (var (assembly, type, name, parameters, terminalCapability) in new[] + { + (AuditAssembly, AuditStore, "WriteOwnTransactionCoreAsync", + new[] { "LearnStack.SharedKernel.Audit.AuditEntryDraft", "LearnStack.SharedKernel.Jobs.JobApplicationAuxiliaryResources", BoundaryCancellation }, "database.CommitAsync"), + (AuditAssembly, AuditStore, "WriteGlobalIdentityTransactionAsync", + new[] { "LearnStack.SharedKernel.Audit.GlobalIdentityCreationReference", "LearnStack.SharedKernel.Audit.AuditEntryDraft", BoundaryCancellation }, "database.CommitAsync"), + (AuditAssembly, AuditStore, "HasGlobalIdentityEvidenceAsync", + new[] { "LearnStack.SharedKernel.Audit.GlobalIdentityCreationReference", "LearnStack.SharedKernel.Audit.AuditEntryDraft", BoundaryCancellation }, "database.CommitAsync"), + (LifecycleIdentityAssembly, LifecycleIdentityBindings + "IdentityAuthorityDeploymentInstaller", "InstallAsync", + new[] { "Npgsql.NpgsqlConnection", LifecycleIdentityBindings + "IdentityAuthorityRegistration", BoundaryCancellation }, "database.CommitAsync"), + (LifecycleIdentityAssembly, LifecycleIdentityBindings + "IdentityAuthorityQualification", "QualifyCoreAsync", + new[] { BoundaryCancellation }, "database.CommitAsync"), + (InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobControlStore", "CommitAsync", + new[] { "LearnStack.Infrastructure.Jobs.BackgroundJobControlResources", BoundaryCancellation }, "database.CommitAsync"), + (InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobTerminalStore", "CommitAsync", + new[] { "LearnStack.Infrastructure.Jobs.BackgroundJobControlResources", BoundaryCancellation }, "database.CommitAsync"), + (InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobControlStore", "ProbeCommitAsync", + new[] { "LearnStack.Infrastructure.Jobs.BackgroundJobCommitProbe", BoundaryCancellation }, "database.RollbackAsync"), + (InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobControlStore", "ProbeExternalRecoveryAsync", + new[] { "LearnStack.Infrastructure.Jobs.OwnedBackgroundJobExternalRecovery", "LearnStack.Infrastructure.Jobs.BackgroundJobCommitProbe", BoundaryCancellation }, "database.RollbackAsync"), + (InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobControlStore", "ProbeExternalCheckpointAsync", + new[] { "LearnStack.Infrastructure.Jobs.BackgroundJobCheckpointHistoryOrigin", BoundaryCancellation }, "database.RollbackAsync"), + (InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobControlStore", "ProbeExternalTerminalNoStartAcquisitionAsync", + new[] { "LearnStack.Infrastructure.Jobs.OwnedBackgroundJobExternalRecovery", "LearnStack.Infrastructure.Jobs.BackgroundJobCommitProbe", BoundaryCancellation }, "database.RollbackAsync"), + (InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobControlStore", "ReadDurableObservationAsync", + new[] { "LearnStack.Infrastructure.Jobs.BackgroundJobObservationManifest", "System.Collections.Generic.IReadOnlyCollection`1", BoundaryCancellation }, "database.RollbackAsync"), + }) + { + var owner = types[(assembly, type)].Methods.Single(method => method.Name == name && ParametersMatch(method, parameters)); + var terminals = OwnedBodies(census).Where(item => item.Owner == owner) + .SelectMany(item => item.Body.Body.Instructions).Where(instruction => instruction.Operand is MethodReference target + && IntegrationLifecycleCapability(target, types) == terminalCapability).ToArray(); + terminals.Should().ContainSingle("the exact helper owner must execute its real physical terminal operation"); + AssertMutation(census, "a missing actual helper terminal operation in " + MethodId(owner), () => + ReplaceInstruction(terminals[0], OpCodes.Ldstr, "missing helper terminal operation"), IntegrationLifecycleOffenders); + } + var announcements = OwnedBodies(census).SelectMany(item => item.Body.Body.Instructions) + .Where(instruction => instruction.Operand is MethodReference target + && IntegrationLifecycleCapability(target, types) == "unit.announce").ToArray(); + announcements.Should().HaveCount(3, "Fix: retain the ordinary owner and both durable transport announcement sites"); + foreach (var announcement in announcements) + AssertMutation(census, "a missing real tenant announcement site", () => + ReplaceInstruction(announcement, OpCodes.Ldstr, "missing tenant announcement"), IntegrationLifecycleOffenders); + var clean = AddProbe(application, "CleanIntegrationLifecycleObserver"); + foreach (var method in unit.Methods.Where(method => method.IsGetter || method.Name == "MarkRollbackOnly") + .Concat(scope.Methods.Where(method => method.IsGetter))) + AddCall(clean, "Observe" + method.Name, method, OpCodes.Callvirt); + try { IntegrationLifecycleOffenders(census).Should().BeEmpty("ambient reads and poisoning cannot grant commit ownership"); } + finally { application.Types.Remove(clean); } - using var probes = ModuleDefinition.ReadModule(typeof(OutboxDispatchConventionTests).Assembly.Location); - census.Modules.Add(probes); - try - { - var sites = CallSites(census).Where(site => !site.Owner.StartsWith(probes.Assembly.Name.Name + ":", StringComparison.Ordinal) - || site.Owner.Contains("/IntegrationLifecycleProbe", StringComparison.Ordinal)); - var offenders = IntegrationLifecycleCallsiteOffenders(census.Types, sites); - foreach (var name in new[] { "Commit", "Rollback", "Begin", "Complete", "Fail", "Concrete", "RawCommit", "RawRollback", - "ConcreteRaw", "InheritedUnit", "InheritedRaw", "Async", "Capture", "Run", - "Announce", "ConcreteAnnounce", "InheritedAnnounce", "AsyncAnnounce", "CaptureAnnouncement", - "EfCommit", "EfRollback", "EfCommitAsync", "EfRollbackAsync", "EfConcreteCommitAsync", "EfCurrentCommitAsync", - "EfFacadeCommit", "EfFacadeRollback", "EfFacadeCommitAsync", "EfFacadeRollbackAsync", "EfAsync", "EfCapture" }) - offenders.Should().Contain(offender => offender.Contains("::" + name + "(", StringComparison.Ordinal), - "Fix: the real lifecycle predicate must reject compiled " + name); - offenders.Should().NotContain(offender => offender.Contains("/IntegrationLifecycleProbeClean::", StringComparison.Ordinal), - "ordinary unit observations and rollback-only marking remain available"); + using var probes = ModuleDefinition.ReadModule(typeof(OutboxDispatchConventionTests).Assembly.Location); + census.Modules.Add(probes); + try + { + var sites = CallSites(census).Where(site => !site.Owner.StartsWith(probes.Assembly.Name.Name + ":", StringComparison.Ordinal) + || site.Owner.Contains("/IntegrationLifecycleProbe", StringComparison.Ordinal)); + var offenders = IntegrationLifecycleCallsiteOffenders(census.Types, sites); + foreach (var name in new[] { "Commit", "Rollback", "Begin", "Complete", "Fail", "Concrete", "RawCommit", "RawRollback", + "ConcreteRaw", "InheritedUnit", "InheritedRaw", "Async", "Capture", "Run", + "Announce", "ConcreteAnnounce", "InheritedAnnounce", "AsyncAnnounce", "CaptureAnnouncement", + "EfCommit", "EfRollback", "EfCommitAsync", "EfRollbackAsync", "EfConcreteCommitAsync", "EfCurrentCommitAsync", + "EfFacadeCommit", "EfFacadeRollback", "EfFacadeCommitAsync", "EfFacadeRollbackAsync", "EfAsync", "EfCapture" }) + offenders.Should().Contain(offender => offender.Contains("::" + name + "(", StringComparison.Ordinal), + "Fix: the real lifecycle predicate must reject compiled " + name); + offenders.Should().NotContain(offender => offender.Contains("/IntegrationLifecycleProbeClean::", StringComparison.Ordinal), + "ordinary unit observations and rollback-only marking remain available"); + } + finally { census.Modules.Remove(probes); } } - finally { census.Modules.Remove(probes); } } private static SortedSet IntegrationLifecycleOffenders(ProductionCensus census) @@ -241,9 +255,13 @@ private static SortedSet IntegrationLifecycleCallsiteOffenders( ["unit.rollback"] = [], ["unit.announce"] = [Owner(DeliveryApplication, DeliveryCoordinator, "ExecuteFrameAsync"), Owner(DeliveryApplication, DeliveryPrepared, "CreateAsync"), Owner(InfrastructureAssembly, LifecycleAcceptance, "AcceptAsync")], - ["scope.complete"] = [Owner(DeliveryApplication, DeliveryCoordinator, "ExecuteFrameAsync"), Owner(InfrastructureAssembly, LifecycleAcceptance, "AcceptAsync")], + ["scope.complete"] = [Owner(DeliveryApplication, DeliveryCoordinator, "ExecuteFrameAsync"), Owner(InfrastructureAssembly, LifecycleAcceptance, "AcceptAsync"), + Owner(DeliveryApplication, LifecycleGlobalPrepared, "CompleteExistingAsync"), + Owner(LifecycleIdentityAssembly, LifecycleIdentityBindings + "GlobalIdentityBindingService", "ResolveExistingAsync")], ["scope.fail"] = [Owner(DeliveryApplication, DeliveryCoordinator, "ExecuteFrameAsync"), Owner(DeliveryApplication, DeliveryCoordinator, "ExecuteFrameAsync"), - Owner(DeliveryApplication, DeliveryPrepared, "CreateAsync"), Owner(InfrastructureAssembly, LifecycleAcceptance, "AcceptAsync")], + Owner(DeliveryApplication, DeliveryPrepared, "CreateAsync"), Owner(InfrastructureAssembly, LifecycleAcceptance, "AcceptAsync"), + Owner(DeliveryApplication, LifecycleGlobalPrepared, "CreateAsync"), + Owner(DeliveryApplication, LifecycleGlobalPrepared, "FailBeforeConsumptionAsync")], ["owned-frame.fail"] = [Owner(InfrastructureAssembly, LifecycleFrame, "FailAsync"), Owner(InfrastructureAssembly, LifecycleFrame, "DisposeAsync")], ["database.CommitAsync"] = [ @@ -258,6 +276,13 @@ private static SortedSet IntegrationLifecycleCallsiteOffenders( Owner(InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobBridgeStore", "UpdateAsync"), Owner(AuditAssembly, AuditStore, "WriteOwnTransactionCoreAsync", ["LearnStack.SharedKernel.Audit.AuditEntryDraft", "LearnStack.SharedKernel.Jobs.JobApplicationAuxiliaryResources", BoundaryCancellation]), + Owner(AuditAssembly, AuditStore, "WriteGlobalIdentityTransactionAsync", + ["LearnStack.SharedKernel.Audit.GlobalIdentityCreationReference", "LearnStack.SharedKernel.Audit.AuditEntryDraft", BoundaryCancellation]), + Owner(AuditAssembly, AuditStore, "HasGlobalIdentityEvidenceAsync", + ["LearnStack.SharedKernel.Audit.GlobalIdentityCreationReference", "LearnStack.SharedKernel.Audit.AuditEntryDraft", BoundaryCancellation]), + Owner(LifecycleIdentityAssembly, LifecycleIdentityBindings + "IdentityAuthorityDeploymentInstaller", "InstallAsync", + ["Npgsql.NpgsqlConnection", LifecycleIdentityBindings + "IdentityAuthorityRegistration", BoundaryCancellation]), + Owner(LifecycleIdentityAssembly, LifecycleIdentityBindings + "IdentityAuthorityQualification", "QualifyCoreAsync", [BoundaryCancellation]), Owner(InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobControlStore", "CommitAsync", ["LearnStack.Infrastructure.Jobs.BackgroundJobControlResources", BoundaryCancellation]), Owner(InfrastructureAssembly, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobTerminalStore", "CommitAsync", diff --git a/backend/tests/LearnStack.Tests.Architecture/LearnStack.Tests.Architecture.csproj b/backend/tests/LearnStack.Tests.Architecture/LearnStack.Tests.Architecture.csproj index f2efdc6ab..73962a6ee 100644 --- a/backend/tests/LearnStack.Tests.Architecture/LearnStack.Tests.Architecture.csproj +++ b/backend/tests/LearnStack.Tests.Architecture/LearnStack.Tests.Architecture.csproj @@ -31,6 +31,7 @@ a tool that could write across an aggregate boundary or set the tenant itself is exactly what these rules exist to see. --> + diff --git a/backend/tests/LearnStack.Tests.Architecture/ModuleDependencyTests.cs b/backend/tests/LearnStack.Tests.Architecture/ModuleDependencyTests.cs index 6a50994a8..366062a86 100644 --- a/backend/tests/LearnStack.Tests.Architecture/ModuleDependencyTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/ModuleDependencyTests.cs @@ -399,6 +399,13 @@ private static HashSet AllowedReferences(string moduleName, string layer break; case "Infrastructure": allowed.Add("LearnStack.Infrastructure"); + if (moduleName == "Identity") + { + // ADR-0072's exact common coordinator/central installer edges are + // member/type-confined by IdentityAuditConventionTests, not a general adapter dependency. + allowed.Add("LearnStack.Application"); + allowed.Add("LearnStack.Infrastructure.Audit"); + } allowed.Add(Own("Domain")); allowed.Add(Own("Application")); allowed.Add(Own("Application.Contracts")); diff --git a/backend/tests/LearnStack.Tests.Architecture/Modules.cs b/backend/tests/LearnStack.Tests.Architecture/Modules.cs index 07d6649e7..79532bac2 100644 --- a/backend/tests/LearnStack.Tests.Architecture/Modules.cs +++ b/backend/tests/LearnStack.Tests.Architecture/Modules.cs @@ -5,6 +5,8 @@ using LearnStack.Modules.Customization.Infrastructure.Persistence; using LearnStack.Modules.Education.Domain; using LearnStack.Modules.Education.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.Tenancy; @@ -62,14 +64,22 @@ internal static class Modules /// guard is on the reverse direction — having a schema and not being swept. /// /// - public static readonly (Assembly Domain, Func Context)[] Scoped = + private static readonly (Assembly Domain, Func Context, bool TenantScoped)[] Models = [ - (typeof(Tenant).Assembly, ModelOnly), - (typeof(TenantContentType).Assembly, ModelOnly), - (typeof(AuditEntry).Assembly, ModelOnly), - (typeof(Course).Assembly, ModelOnly), + (typeof(Tenant).Assembly, ModelOnly, true), + (typeof(TenantContentType).Assembly, ModelOnly, true), + (typeof(AuditEntry).Assembly, ModelOnly, true), + (typeof(Course).Assembly, ModelOnly, true), + (typeof(User).Assembly, ModelOnly, true), ]; + // Declared class populations, never inferred from whether a marker happened + // to survive: deleting a marker must not delete the module from the sweep. + public static readonly (Assembly Domain, Func Context)[] Mapped = + Models.Select(model => (model.Domain, model.Context)).ToArray(); + public static readonly (Assembly Domain, Func Context)[] Scoped = + Models.Where(model => model.TenantScoped).Select(model => (model.Domain, model.Context)).ToArray(); + /// /// A context built for its model alone. The connection string is never opened. /// @@ -85,6 +95,10 @@ public static DbContext ModelOnly() .UseNpgsql("Host=model-only;Database=model-only;Username=model-only") .Options; + if (typeof(TContext) == typeof(IdentityDbContext)) + return new IdentityDbContext((DbContextOptions)(object)options, + StaticTenantContextAccessor.Unresolved, EmptyIdentityScope.Instance); + return (DbContext)Activator.CreateInstance( typeof(TContext), options, StaticTenantContextAccessor.Unresolved)!; } diff --git a/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchBoundaryTests.cs index c51614402..4e668c383 100644 --- a/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchBoundaryTests.cs @@ -172,100 +172,103 @@ public void Credential_census_rejects_generic_direct_delegate_async_and_extra_he } - [Fact] - public void Credential_census_rejects_crossed_keys_changed_closures_and_missing_subjects() + public sealed class CredentialBindingMutationTests { - using var census = ProductionCensus.Read(); - foreach (var subject in new[] { (BoundaryApi, BoundaryWorker), (InfrastructureAssembly, BoundaryPlatform) }) + [Fact] + public void Credential_census_rejects_crossed_keys_changed_closures_and_missing_subjects() { - var parameter = census.Types[subject].Methods.Single(method => method.IsConstructor && !method.IsStatic) - .Parameters.Single(parameter => parameter.CustomAttributes.Any(attribute => - attribute.AttributeType.Name == "FromKeyedServicesAttribute")); - var attribute = parameter.CustomAttributes.Single(item => item.AttributeType.Name == "FromKeyedServicesAttribute"); - AssertMutation(census, "a consumer resolving the other privileged key", () => - { - var original = attribute.ConstructorArguments[0]; - attribute.ConstructorArguments[0] = new CustomAttributeArgument(original.Type, - subject.Item2 == BoundaryWorker ? PlatformAdminScope.PlatformDataSourceKey : OutboxDispatcherDataSource.Key); - return () => attribute.ConstructorArguments[0] = original; - }, CredentialOffenders); - AssertMutation(census, "a raw source replacing the required lazy binding", () => + using var census = ProductionCensus.Read(); + foreach (var subject in new[] { (BoundaryApi, BoundaryWorker), (InfrastructureAssembly, BoundaryPlatform) }) { - var original = parameter.ParameterType; - parameter.ParameterType = census.Types[subject].Module.ImportReference(typeof(NpgsqlDataSource)); - return () => parameter.ParameterType = original; - }, CredentialOffenders); - } + var parameter = census.Types[subject].Methods.Single(method => method.IsConstructor && !method.IsStatic) + .Parameters.Single(parameter => parameter.CustomAttributes.Any(attribute => + attribute.AttributeType.Name == "FromKeyedServicesAttribute")); + var attribute = parameter.CustomAttributes.Single(item => item.AttributeType.Name == "FromKeyedServicesAttribute"); + AssertMutation(census, "a consumer resolving the other privileged key", () => + { + var original = attribute.ConstructorArguments[0]; + attribute.ConstructorArguments[0] = new CustomAttributeArgument(original.Type, + subject.Item2 == BoundaryWorker ? PlatformAdminScope.PlatformDataSourceKey : OutboxDispatcherDataSource.Key); + return () => attribute.ConstructorArguments[0] = original; + }, CredentialOffenders); + AssertMutation(census, "a raw source replacing the required lazy binding", () => + { + var original = parameter.ParameterType; + parameter.ParameterType = census.Types[subject].Module.ImportReference(typeof(NpgsqlDataSource)); + return () => parameter.ParameterType = original; + }, CredentialOffenders); + } - foreach (var key in new[] { OutboxDispatcherDataSource.Key, PlatformAdminScope.PlatformDataSourceKey }) - { - var descriptor = BoundaryRegistrations().Single(item => item.IsKeyedService && Equals(item.ServiceKey, key) - && item.ServiceType == typeof(PrivilegedDataSource)); - var factory = FindRuntimeMethod(census, descriptor.KeyedImplementationFactory!.Method)!; - var leafReference = DelegateTargets(factory).Single(); - var leaf = census.Types[Key(leafReference.DeclaringType)].Methods.Single(method => MethodId(method) == MethodId(leafReference)); - var call = leaf.Body.Instructions.Single(instruction => instruction.Operand is MethodReference method - && method.ReturnType.FullName == "Npgsql.NpgsqlDataSource"); - var wrong = key == OutboxDispatcherDataSource.Key - ? census.Types[(BoundaryApi, BoundaryPersistence)].Methods.Single(method => method.Name == "BuildPlatformDataSource") - : census.Types[(InfrastructureAssembly, BoundarySource)].Methods.Single(method => method.Name == "Build"); - AssertMutation(census, "a facade callback constructing the other privileged pool", () => - ReplaceInstruction(call, OpCodes.Call, wrong), CredentialOffenders); - var captured = (FieldReference)call.Previous!.Operand; - var credentialOwner = census.Types[(BoundaryApi, key == OutboxDispatcherDataSource.Key ? BoundaryComposition : BoundaryPersistence)] - .Methods.Single(method => method.Name == (key == OutboxDispatcherDataSource.Key ? "AddLearnStackOutboxDispatcher" : "AddLearnStackPersistence")); - var assignment = credentialOwner.Body.Instructions.Single(instruction => instruction.OpCode == OpCodes.Stfld - && instruction.Operand is FieldReference field && field.FullName == captured.FullName); - AssertMutation(census, "a facade capturing a different credential instead of its declared read", () => - ReplaceInstruction(assignment.Previous!, OpCodes.Ldstr, "synthetic-unrelated-credential"), CredentialOffenders); - foreach (var method in new[] { leaf, factory }) + foreach (var key in new[] { OutboxDispatcherDataSource.Key, PlatformAdminScope.PlatformDataSourceKey }) { - AssertMutation(census, "the actual facade callback overwriting its captured credential", () => - InsertCaptureMutation(method, captured, address: false), CredentialOffenders); - AssertMutation(census, "the actual facade callback exposing its captured credential address", () => - InsertCaptureMutation(method, captured, address: true), CredentialOffenders); + var descriptor = BoundaryRegistrations().Single(item => item.IsKeyedService && Equals(item.ServiceKey, key) + && item.ServiceType == typeof(PrivilegedDataSource)); + var factory = FindRuntimeMethod(census, descriptor.KeyedImplementationFactory!.Method)!; + var leafReference = DelegateTargets(factory).Single(); + var leaf = census.Types[Key(leafReference.DeclaringType)].Methods.Single(method => MethodId(method) == MethodId(leafReference)); + var call = leaf.Body.Instructions.Single(instruction => instruction.Operand is MethodReference method + && method.ReturnType.FullName == "Npgsql.NpgsqlDataSource"); + var wrong = key == OutboxDispatcherDataSource.Key + ? census.Types[(BoundaryApi, BoundaryPersistence)].Methods.Single(method => method.Name == "BuildPlatformDataSource") + : census.Types[(InfrastructureAssembly, BoundarySource)].Methods.Single(method => method.Name == "Build"); + AssertMutation(census, "a facade callback constructing the other privileged pool", () => + ReplaceInstruction(call, OpCodes.Call, wrong), CredentialOffenders); + var captured = (FieldReference)call.Previous!.Operand; + var credentialOwner = census.Types[(BoundaryApi, key == OutboxDispatcherDataSource.Key ? BoundaryComposition : BoundaryPersistence)] + .Methods.Single(method => method.Name == (key == OutboxDispatcherDataSource.Key ? "AddLearnStackOutboxDispatcher" : "AddLearnStackPersistence")); + var assignment = credentialOwner.Body.Instructions.Single(instruction => instruction.OpCode == OpCodes.Stfld + && instruction.Operand is FieldReference field && field.FullName == captured.FullName); + AssertMutation(census, "a facade capturing a different credential instead of its declared read", () => + ReplaceInstruction(assignment.Previous!, OpCodes.Ldstr, "synthetic-unrelated-credential"), CredentialOffenders); + foreach (var method in new[] { leaf, factory }) + { + AssertMutation(census, "the actual facade callback overwriting its captured credential", () => + InsertCaptureMutation(method, captured, address: false), CredentialOffenders); + AssertMutation(census, "the actual facade callback exposing its captured credential address", () => + InsertCaptureMutation(method, captured, address: true), CredentialOffenders); + } + AssertMutation(census, "a closure helper overwriting the captured credential", () => + { + var helper = new MethodDefinition("RewriteCapturedCredential", MethodAttributes.Private, leaf.Module.TypeSystem.Void); + helper.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); + leaf.DeclaringType.Methods.Add(helper); + var undo = InsertCaptureMutation(helper, captured, address: false); + return () => { undo(); leaf.DeclaringType.Methods.Remove(helper); }; + }, CredentialOffenders); + AssertMutation(census, "the original credential owner overwriting its captured value after assignment", () => + InsertCaptureMutation(credentialOwner, captured, address: false, afterCapture: true), CredentialOffenders); } - AssertMutation(census, "a closure helper overwriting the captured credential", () => + + var root = census.Types[(BoundaryApi, BoundaryComposition)].Methods.Single(method => method.Name == "AddLearnStackOutboxDispatcher"); + var registrationKey = root.Body.Instructions.First(instruction => Equals(instruction.Operand, OutboxDispatcherDataSource.Key)); + AssertMutation(census, "a changed actual registration key", () => + ReplaceInstruction(registrationKey, OpCodes.Ldstr, PlatformAdminScope.PlatformDataSourceKey), CredentialOffenders); + var configurationKey = root.Body.Instructions.Single(instruction => Equals(instruction.Operand, "OutboxDispatcher")); + AssertMutation(census, "the dispatcher reading the platform configuration", () => + ReplaceInstruction(configurationKey, OpCodes.Ldstr, "PlatformAdmin"), CredentialOffenders); + var source = census.Types[(InfrastructureAssembly, BoundarySource)]; + AssertMutation(census, "a missing production data-source subject", () => { - var helper = new MethodDefinition("RewriteCapturedCredential", MethodAttributes.Private, leaf.Module.TypeSystem.Void); - helper.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); - leaf.DeclaringType.Methods.Add(helper); - var undo = InsertCaptureMutation(helper, captured, address: false); - return () => { undo(); leaf.DeclaringType.Methods.Remove(helper); }; + var module = source.Module; + module.Types.Remove(source); + return () => module.Types.Add(source); }, CredentialOffenders); - AssertMutation(census, "the original credential owner overwriting its captured value after assignment", () => - InsertCaptureMutation(credentialOwner, captured, address: false, afterCapture: true), CredentialOffenders); } - var root = census.Types[(BoundaryApi, BoundaryComposition)].Methods.Single(method => method.Name == "AddLearnStackOutboxDispatcher"); - var registrationKey = root.Body.Instructions.First(instruction => Equals(instruction.Operand, OutboxDispatcherDataSource.Key)); - AssertMutation(census, "a changed actual registration key", () => - ReplaceInstruction(registrationKey, OpCodes.Ldstr, PlatformAdminScope.PlatformDataSourceKey), CredentialOffenders); - var configurationKey = root.Body.Instructions.Single(instruction => Equals(instruction.Operand, "OutboxDispatcher")); - AssertMutation(census, "the dispatcher reading the platform configuration", () => - ReplaceInstruction(configurationKey, OpCodes.Ldstr, "PlatformAdmin"), CredentialOffenders); - var source = census.Types[(InfrastructureAssembly, BoundarySource)]; - AssertMutation(census, "a missing production data-source subject", () => - { - var module = source.Module; - module.Types.Remove(source); - return () => module.Types.Add(source); - }, CredentialOffenders); - } - - [Fact] - public void Credential_census_rejects_compiled_connection_string_indexers_and_composed_keys() - { - using var census = ProductionCensus.Read(); - var application = census.Modules.Single(module => module.Assembly.Name.Name == "LearnStack.Application"); - foreach (var name in new[] { "Concatenated", "ReadonlyName", "Interpolated", "Formatted", "Manager", "Root", "Section" }) - AssertMutation(census, "a compiled configuration credential indexer: " + name, () => - AddCompiledCredentialProbe(application, name), CredentialOffenders); - foreach (var name in new[] { "UnrelatedLiteral", "UnrelatedDynamic", "Dictionary", "CredentialDiagnostic" }) + [Fact] + public void Credential_census_rejects_compiled_connection_string_indexers_and_composed_keys() { - var undo = AddCompiledCredentialProbe(application, name); - try { EvaluateDetector(census, CredentialOffenders).Should().BeEmpty("Fix: unrelated configuration, dictionary indexers and diagnostics remain valid"); } - finally { undo(); } + using var census = ProductionCensus.Read(); + var application = census.Modules.Single(module => module.Assembly.Name.Name == "LearnStack.Application"); + foreach (var name in new[] { "Concatenated", "ReadonlyName", "Interpolated", "Formatted", "Manager", "Root", "Section" }) + AssertMutation(census, "a compiled configuration credential indexer: " + name, () => + AddCompiledCredentialProbe(application, name), CredentialOffenders); + foreach (var name in new[] { "UnrelatedLiteral", "UnrelatedDynamic", "Dictionary", "CredentialDiagnostic" }) + { + var undo = AddCompiledCredentialProbe(application, name); + try { EvaluateDetector(census, CredentialOffenders).Should().BeEmpty("Fix: unrelated configuration, dictionary indexers and diagnostics remain valid"); } + finally { undo(); } + } } } diff --git a/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchConventionTests.cs index 37ffa89e6..0cc5473b1 100644 --- a/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/OutboxDispatchConventionTests.cs @@ -249,55 +249,58 @@ public void Outbox_Type_Resolution_Is_Declared_And_Bounded() + "remove dynamic type loading or Activator construction from the resolver/validator/store helper graph"); } - [Fact] - public void Resolution_walk_detects_loading_construction_async_and_polymorphic_helpers() + public sealed class ResolutionMutationTests { - using var census = ProductionCensus.Read(); - var application = census.Modules.Single(module => module.Assembly.Name.Name == "LearnStack.Application"); - var root = census.Types[(InfrastructureAssembly, ResolutionRoots[0])]; - var targets = new[] - { - typeof(Type).GetMethod(nameof(Type.GetType), [typeof(string)])!, - typeof(System.Reflection.Assembly).GetMethod(nameof(System.Reflection.Assembly.Load), [typeof(string)])!, - typeof(System.Reflection.Assembly).GetMethod(nameof(System.Reflection.Assembly.LoadFrom), [typeof(string)])!, - typeof(System.Reflection.Assembly).GetMethod(nameof(System.Reflection.Assembly.GetType), [typeof(string)])!, - typeof(System.Reflection.Assembly).GetMethod(nameof(System.Reflection.Assembly.CreateInstance), [typeof(string)])!, - typeof(Activator).GetMethod(nameof(Activator.CreateInstance), [typeof(Type)])!, - }; - foreach (var target in targets) - foreach (var opcode in new[] { OpCodes.Call, OpCodes.Ldftn }) + [Fact] + public void Resolution_walk_detects_loading_construction_async_and_polymorphic_helpers() + { + using var census = ProductionCensus.Read(); + var application = census.Modules.Single(module => module.Assembly.Name.Name == "LearnStack.Application"); + var root = census.Types[(InfrastructureAssembly, ResolutionRoots[0])]; + var targets = new[] { - AssertResolutionMutation(census, target.DeclaringType!.Name + "." + target.Name + " using " + opcode.Name, () => + typeof(Type).GetMethod(nameof(Type.GetType), [typeof(string)])!, + typeof(System.Reflection.Assembly).GetMethod(nameof(System.Reflection.Assembly.Load), [typeof(string)])!, + typeof(System.Reflection.Assembly).GetMethod(nameof(System.Reflection.Assembly.LoadFrom), [typeof(string)])!, + typeof(System.Reflection.Assembly).GetMethod(nameof(System.Reflection.Assembly.GetType), [typeof(string)])!, + typeof(System.Reflection.Assembly).GetMethod(nameof(System.Reflection.Assembly.CreateInstance), [typeof(string)])!, + typeof(Activator).GetMethod(nameof(Activator.CreateInstance), [typeof(Type)])!, + }; + foreach (var target in targets) + foreach (var opcode in new[] { OpCodes.Call, OpCodes.Ldftn }) { - var helper = AddProbe(application, "DynamicResolutionHelper"); - AddCall(helper, "Resolve", application.ImportReference(target), opcode); - var field = new FieldDefinition("ReviewHelper", FieldAttributes.Private, root.Module.ImportReference(helper)); - root.Fields.Add(field); - return () => { root.Fields.Remove(field); application.Types.Remove(helper); }; - }); - } - AssertResolutionMutation(census, "an async cross-assembly resolver helper", () => - { - var helper = AddProbe(application, "AsyncResolutionHelper"); - var undoAsync = AddAsyncCall(helper, "Resolve", application.ImportReference(targets[0])); - var field = new FieldDefinition("ReviewHelper", FieldAttributes.Private, root.Module.ImportReference(helper)); - root.Fields.Add(field); - return () => { root.Fields.Remove(field); undoAsync(); application.Types.Remove(helper); }; - }); - foreach (var isInterface in new[] { true, false }) - { - AssertResolutionMutation(census, "a " + (isInterface ? "interface" : "virtual") + " resolver helper", () => + AssertResolutionMutation(census, target.DeclaringType!.Name + "." + target.Name + " using " + opcode.Name, () => + { + var helper = AddProbe(application, "DynamicResolutionHelper"); + AddCall(helper, "Resolve", application.ImportReference(target), opcode); + var field = new FieldDefinition("ReviewHelper", FieldAttributes.Private, root.Module.ImportReference(helper)); + root.Fields.Add(field); + return () => { root.Fields.Remove(field); application.Types.Remove(helper); }; + }); + } + AssertResolutionMutation(census, "an async cross-assembly resolver helper", () => { - var contract = AddProbe(application, "ResolutionContract"); - if (isInterface) contract.Attributes |= TypeAttributes.Interface | TypeAttributes.Abstract; - var helper = AddProbe(application, "ResolutionImplementation"); - if (isInterface) helper.Interfaces.Add(new InterfaceImplementation(contract)); - else helper.BaseType = contract; - AddCall(helper, "Resolve", application.ImportReference(targets[0]), OpCodes.Call); - var field = new FieldDefinition("ReviewHelper", FieldAttributes.Private, root.Module.ImportReference(contract)); + var helper = AddProbe(application, "AsyncResolutionHelper"); + var undoAsync = AddAsyncCall(helper, "Resolve", application.ImportReference(targets[0])); + var field = new FieldDefinition("ReviewHelper", FieldAttributes.Private, root.Module.ImportReference(helper)); root.Fields.Add(field); - return () => { root.Fields.Remove(field); application.Types.Remove(helper); application.Types.Remove(contract); }; + return () => { root.Fields.Remove(field); undoAsync(); application.Types.Remove(helper); }; }); + foreach (var isInterface in new[] { true, false }) + { + AssertResolutionMutation(census, "a " + (isInterface ? "interface" : "virtual") + " resolver helper", () => + { + var contract = AddProbe(application, "ResolutionContract"); + if (isInterface) contract.Attributes |= TypeAttributes.Interface | TypeAttributes.Abstract; + var helper = AddProbe(application, "ResolutionImplementation"); + if (isInterface) helper.Interfaces.Add(new InterfaceImplementation(contract)); + else helper.BaseType = contract; + AddCall(helper, "Resolve", application.ImportReference(targets[0]), OpCodes.Call); + var field = new FieldDefinition("ReviewHelper", FieldAttributes.Private, root.Module.ImportReference(contract)); + root.Fields.Add(field); + return () => { root.Fields.Remove(field); application.Types.Remove(helper); application.Types.Remove(contract); }; + }); + } } } diff --git a/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.cs index 125b92d75..91c0794a8 100644 --- a/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/PersistenceConventionTests.cs @@ -6,6 +6,7 @@ using LearnStack.Application.Persistence; using LearnStack.Infrastructure.Persistence; using LearnStack.Modules.Tenancy.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Domain; using LearnStack.SharedKernel.Jobs; using LearnStack.SharedKernel.Persistence; using Microsoft.CodeAnalysis; @@ -58,7 +59,7 @@ public void Aggregates_With_Optimistic_Concurrency_Map_RowVersion() // Standards 21 and ADR-0039 both describe it as covering every entity that // implements IOptimisticConcurrency. Measured — the forbidden IsRowVersion() // form passed on both new aggregates. - var contexts = Modules.Scoped.Select(module => module.Context()).ToList(); + var contexts = Modules.Mapped.Select(module => module.Context()).ToList(); try { @@ -174,13 +175,14 @@ public void Module_DbContexts_Enlist_In_The_Ambient_UnitOfWork() // SET LOCAL, so every read through it returns zero rows under the // corrected policy — silently. // - // Nine files under backend/src may reach for a connection at all: the five + // Eleven files under backend/src may reach for a connection at all: the six // design-time factories, where a connection string is the point — one per // migration chain, and a module that ships a schema ships one; the shared // module helper, which passes a connection rather than a string; the API's // separately guarded platform-role builder; and the shared application-role // builder used by both runtime hosts; and ADR-0046's confined dispatcher - // builder. Another site requires a new decision, not a wildcard exemption. + // builder; and the explicit deployment-only authority installer. Another site + // requires a new decision, not a wildcard exemption. // // The scan covers the raw constructors as well as `UseNpgsql` and // `AddDbContext`, because a call site that opened its own @@ -209,12 +211,14 @@ public void Module_DbContexts_Enlist_In_The_Ambient_UnitOfWork() "Persistence/TenancyDbContextFactory.cs", // One design-time factory per migration chain. Customization's is the - // third, Audit's the fourth and Education's the fifth. All are here + // third, Audit's the fourth, Education's the fifth and Identity's the sixth. All are here // rather than exempted: the list makes the next connection site a // reviewed diff. "Persistence/CustomizationDbContextFactory.cs", "Persistence/AuditDbContextFactory.cs", "Persistence/EducationDbContextFactory.cs", + "Persistence/IdentityDbContextFactory.cs", + "LearnStack.Tools.IdentityAuthorityInstaller/Program.cs", // Both runtime hosts delegate application-role construction to this // shared guard; the API retains its separate platform-role builder. @@ -740,7 +744,7 @@ public void Unique_Indexes_On_Soft_Deletable_Tables_Exclude_Deleted_Rows() // Declare, which the unfiltered index refused with 23505 (the fifth review of // Packet 9). Per-table schema cases had pinned the others; nothing swept for the // shape, so a new table repeated the omission and every case stayed green. - var contexts = Modules.Scoped.Select(module => module.Context()).ToList(); + var contexts = Modules.Mapped.Select(module => module.Context()).ToList(); try { @@ -751,6 +755,14 @@ public void Unique_Indexes_On_Soft_Deletable_Tables_Exclude_Deleted_Rows() soft.Should().NotBeEmpty("a sweep over no soft-deletable table passes vacuously"); + var user = soft.Single(entity => entity.ClrType == typeof(User)); + var permanentBinding = user.GetIndexes().Single(index => + index.GetDatabaseName() == "ux_users_authority_id_subject_key"); + permanentBinding.Properties.Select(property => property.Name) + .Should().Equal([nameof(User.AuthorityId), nameof(User.SubjectKey)], + "ADR-0072 exempts exactly the permanent authority/subject binding key"); + permanentBinding.IsUnique.Should().BeTrue(); + permanentBinding.GetFilter().Should().BeNull("a closed binding remains reserved permanently"); var counting = UniqueIndexesCountingDeletedRows(soft); counting.Except(HeldByDecision.Keys).Should().BeEmpty( @@ -792,6 +804,8 @@ public void The_Soft_Delete_Index_Sweep_Can_Actually_Fail() // with tenant termination, in Phase 02c, not by an index filter. ["Tenant.ux_tenants_slug"] = "a tenant slug is a hostname; its reissue is Phase 02c's decision", + ["User.ux_users_authority_id_subject_key"] = + "ADR-0072 retains the exact authority/subject binding after closure to refuse recreation", }; private static bool IsSoftDeletable(IReadOnlyEntityType entity) => @@ -1338,27 +1352,31 @@ public void Migrate_Target_Applies_The_Tenancy_Chain_First() var order = MigrateChainOrder(ReadMigrateRecipe()); MigrationDependencyOffenders(order).Should().BeEmpty( "Fix: apply Tenancy before Audit (tenants FK) and Education " - + "(the shared organization immutability function), per Standards 05 § Migrations"); + + "(the shared organization immutability function), and Audit before Identity " + + "(the central creation-witness installer), per Standards 05 § Migrations"); } [Theory] [InlineData("Audit")] [InlineData("Education")] + [InlineData("Identity")] public void The_Migration_Order_Guard_Rejects_Each_Dependent_Chain_First(string module) { - var dependent = module == "Audit" ? AuditChain : EducationChain; + var dependent = module switch { "Audit" => AuditChain, "Education" => EducationChain, _ => IdentityChain }; var glob = "backend/src/Modules/*/LearnStack.Modules.*.Infrastructure"; - var bad = MigrateChainOrder($"{dependent} {TenancyChain} {glob}"); + var bad = MigrateChainOrder(module == "Identity" + ? $"{TenancyChain} {IdentityChain} {AuditChain} {glob}" + : $"{dependent} {TenancyChain} {glob}"); MigrationDependencyOffenders(bad).Should().ContainSingle().Which.Should().Be(dependent); MigrationDependencyOffenders(MigrateChainOrder($"{TenancyChain} {glob}")) .Should().BeEmpty("the same glob expansion and detector must accept the repaired order"); } private static List MigrationDependencyOffenders(List order) => - new[] { AuditChain, EducationChain } - .Where(chain => !order.Contains(TenancyChain) || !order.Contains(chain) - || order.IndexOf(TenancyChain) >= order.IndexOf(chain)) - .ToList(); + new[] { (TenancyChain, AuditChain), (TenancyChain, EducationChain), (AuditChain, IdentityChain) } + .Where(edge => !order.Contains(edge.Item1) || !order.Contains(edge.Item2) + || order.IndexOf(edge.Item1) >= order.IndexOf(edge.Item2)) + .Select(edge => edge.Item2).Distinct(StringComparer.Ordinal).ToList(); private const string TenancyChain = "backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure"; @@ -1366,6 +1384,9 @@ private static List MigrationDependencyOffenders(List order) => private const string AuditChain = "backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure"; + private const string IdentityChain = + "backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure"; + private const string EducationChain = "backend/src/Modules/Education/LearnStack.Modules.Education.Infrastructure"; diff --git a/backend/tests/LearnStack.Tests.Architecture/PrivilegedDispatchCleanupBoundaryTests.cs b/backend/tests/LearnStack.Tests.Architecture/PrivilegedDispatchCleanupBoundaryTests.cs index 84d0806f5..e5bbf51b9 100644 --- a/backend/tests/LearnStack.Tests.Architecture/PrivilegedDispatchCleanupBoundaryTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/PrivilegedDispatchCleanupBoundaryTests.cs @@ -102,69 +102,72 @@ void CheckCallers(TypeDefinition type, string method, IEnumerable expect .Select(site => site.Owner), expected); } - [Fact] - public void Cleanup_owner_census_rejects_extra_acquisition_disposal_capture_and_observation_paths() + public sealed class CleanupOwnerMutationTests { - using var census = ProductionCensus.Read(); - EvaluateDetector(census, CredentialOffenders).Should().BeEmpty("the three actual cleanup owners are nonempty clean subjects"); - foreach (var name in new[] { Store, DeliveryStore, JobBridgeStore }) + [Fact] + public void Cleanup_owner_census_rejects_extra_acquisition_disposal_capture_and_observation_paths() { - var store = census.Types[(InfrastructureAssembly, name)]; - var owner = census.Types[(InfrastructureAssembly, name + "/OwnedConnection")]; - var reader = store.Methods.Single(method => method.Name == "OpenConnectionAsync"); - var getter = store.Methods.Single(method => method.Name == "get_HasUnconfirmedCleanup"); - var retain = store.Methods.Single(method => method.Name == "RetainConnection"); - var capture = owner.Fields.Single(field => field.Name == "P"); - var seal = store.Fields.Single(field => field.Name == "_cleanupUnconfirmed"); - AssertMutation(census, "a public cleanup holder", () => - ChangeAttributes(() => owner.Attributes, value => owner.Attributes = value, - (owner.Attributes & ~TypeAttributes.VisibilityMask) | TypeAttributes.NestedPublic), CredentialOffenders); - AssertMutation(census, "an unsealed cleanup holder", () => - ChangeAttributes(() => owner.Attributes, value => owner.Attributes = value, owner.Attributes & ~TypeAttributes.Sealed), CredentialOffenders); - AssertMutation(census, "a missing actual cleanup holder", () => + using var census = ProductionCensus.Read(); + EvaluateDetector(census, CredentialOffenders).Should().BeEmpty("the three actual cleanup owners are nonempty clean subjects"); + foreach (var name in new[] { Store, DeliveryStore, JobBridgeStore }) { - store.NestedTypes.Remove(owner); - return () => store.NestedTypes.Add(owner); - }, CredentialOffenders); - AssertMutation(census, "an extra acquisition helper inside the cleanup holder", () => - { - var method = AddCall(owner, "AdditionalAcquisition", reader, OpCodes.Call); - return () => owner.Methods.Remove(method); - }, CredentialOffenders); - AssertMutation(census, "an extra concrete disposal helper on an approved owner", () => - { - var target = owner.Module.ImportReference(typeof(NpgsqlConnection).GetMethod(nameof(NpgsqlConnection.DisposeAsync), Type.EmptyTypes)!); - var method = AddCall(owner, "AdditionalDisposal", target, OpCodes.Callvirt); - return () => owner.Methods.Remove(method); - }, CredentialOffenders); - foreach (var opcode in new[] { OpCodes.Ldfld, OpCodes.Ldflda, OpCodes.Stfld }) - AssertMutation(census, "an extra cleanup-owner capability capture access through " + opcode, () => + var store = census.Types[(InfrastructureAssembly, name)]; + var owner = census.Types[(InfrastructureAssembly, name + "/OwnedConnection")]; + var reader = store.Methods.Single(method => method.Name == "OpenConnectionAsync"); + var getter = store.Methods.Single(method => method.Name == "get_HasUnconfirmedCleanup"); + var retain = store.Methods.Single(method => method.Name == "RetainConnection"); + var capture = owner.Fields.Single(field => field.Name == "P"); + var seal = store.Fields.Single(field => field.Name == "_cleanupUnconfirmed"); + AssertMutation(census, "a public cleanup holder", () => + ChangeAttributes(() => owner.Attributes, value => owner.Attributes = value, + (owner.Attributes & ~TypeAttributes.VisibilityMask) | TypeAttributes.NestedPublic), CredentialOffenders); + AssertMutation(census, "an unsealed cleanup holder", () => + ChangeAttributes(() => owner.Attributes, value => owner.Attributes = value, owner.Attributes & ~TypeAttributes.Sealed), CredentialOffenders); + AssertMutation(census, "a missing actual cleanup holder", () => { - var method = owner.Methods.Single(item => item.Name == ".ctor"); - var instruction = Instruction.Create(opcode, capture); - method.Body.Instructions.Add(instruction); - return () => method.Body.Instructions.Remove(instruction); + store.NestedTypes.Remove(owner); + return () => store.NestedTypes.Add(owner); }, CredentialOffenders); - var write = retain.Body.Instructions.Single(instruction => instruction.OpCode == OpCodes.Stfld - && instruction.Operand is FieldReference field && field.Name == seal.Name); - AssertMutation(census, "a cleanup seal reset instead of monotonic failure", () => - ReplaceInstruction(write.Previous!, OpCodes.Ldc_I4_0, null!), CredentialOffenders); - AssertMutation(census, "a cleanup observer that acquires physical SQL", () => - { - var instruction = Instruction.Create(OpCodes.Call, reader); - getter.Body.Instructions.Add(instruction); - return () => getter.Body.Instructions.Remove(instruction); - }, CredentialOffenders); - AssertMutation(census, "a writable cleanup observer", () => - { - var property = store.Properties.Single(item => item.Name == "HasUnconfirmedCleanup"); - var setter = new MethodDefinition("set_HasUnconfirmedCleanup", MethodAttributes.Public, store.Module.TypeSystem.Void); - property.SetMethod = setter; - return () => property.SetMethod = null; - }, CredentialOffenders); - var clean = AddCall(owner, "ReadDeclaredRuntimeType", owner.Module.ImportReference(typeof(object).GetMethod(nameof(GetType))!), OpCodes.Callvirt); - try { EvaluateDetector(census, CredentialOffenders).Should().BeEmpty("a memory-only helper grants no acquisition, disposal or store capability"); } - finally { owner.Methods.Remove(clean); } + AssertMutation(census, "an extra acquisition helper inside the cleanup holder", () => + { + var method = AddCall(owner, "AdditionalAcquisition", reader, OpCodes.Call); + return () => owner.Methods.Remove(method); + }, CredentialOffenders); + AssertMutation(census, "an extra concrete disposal helper on an approved owner", () => + { + var target = owner.Module.ImportReference(typeof(NpgsqlConnection).GetMethod(nameof(NpgsqlConnection.DisposeAsync), Type.EmptyTypes)!); + var method = AddCall(owner, "AdditionalDisposal", target, OpCodes.Callvirt); + return () => owner.Methods.Remove(method); + }, CredentialOffenders); + foreach (var opcode in new[] { OpCodes.Ldfld, OpCodes.Ldflda, OpCodes.Stfld }) + AssertMutation(census, "an extra cleanup-owner capability capture access through " + opcode, () => + { + var method = owner.Methods.Single(item => item.Name == ".ctor"); + var instruction = Instruction.Create(opcode, capture); + method.Body.Instructions.Add(instruction); + return () => method.Body.Instructions.Remove(instruction); + }, CredentialOffenders); + var write = retain.Body.Instructions.Single(instruction => instruction.OpCode == OpCodes.Stfld + && instruction.Operand is FieldReference field && field.Name == seal.Name); + AssertMutation(census, "a cleanup seal reset instead of monotonic failure", () => + ReplaceInstruction(write.Previous!, OpCodes.Ldc_I4_0, null!), CredentialOffenders); + AssertMutation(census, "a cleanup observer that acquires physical SQL", () => + { + var instruction = Instruction.Create(OpCodes.Call, reader); + getter.Body.Instructions.Add(instruction); + return () => getter.Body.Instructions.Remove(instruction); + }, CredentialOffenders); + AssertMutation(census, "a writable cleanup observer", () => + { + var property = store.Properties.Single(item => item.Name == "HasUnconfirmedCleanup"); + var setter = new MethodDefinition("set_HasUnconfirmedCleanup", MethodAttributes.Public, store.Module.TypeSystem.Void); + property.SetMethod = setter; + return () => property.SetMethod = null; + }, CredentialOffenders); + var clean = AddCall(owner, "ReadDeclaredRuntimeType", owner.Module.ImportReference(typeof(object).GetMethod(nameof(GetType))!), OpCodes.Callvirt); + try { EvaluateDetector(census, CredentialOffenders).Should().BeEmpty("a memory-only helper grants no acquisition, disposal or store capability"); } + finally { owner.Methods.Remove(clean); } + } } } } diff --git a/backend/tests/LearnStack.Tests.Architecture/TenancyConventionTests.cs b/backend/tests/LearnStack.Tests.Architecture/TenancyConventionTests.cs index e9870773b..2a7d060a9 100644 --- a/backend/tests/LearnStack.Tests.Architecture/TenancyConventionTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/TenancyConventionTests.cs @@ -263,7 +263,7 @@ public void The_Setter_Scan_Can_Actually_Fail() /// must write. /// private static readonly string[] WritingSetters = - ["LearnStack.Infrastructure.Audit/PostgresAuditStore.cs"]; + ["LearnStack.Infrastructure.Audit/PostgresAuditStore.cs", "LearnStack.Infrastructure.Audit/PostgresAuditStore.GlobalIdentity.cs"]; /// /// The readers, each in a short read-only transaction of its own: the host resolver, the @@ -422,7 +422,7 @@ public void Tenant_Scope_Widening_Is_Never_Set_From_Request_Input() Directory.EnumerateFiles(SourceScan.SourceRoot, "*.cs", SearchOption.AllDirectories) .Where(file => !file.Split(Path.DirectorySeparatorChar).Any(segment => segment is "bin" or "obj")) - .Where(file => ScopeSetter().IsMatch(SourceText.WithoutComments(File.ReadAllText(file)))) + .Where(file => ScopeSetter().IsMatch(WithoutGlobalAuthorityClears(file, "app.scope"))) .Select(file => Path.GetRelativePath(SourceScan.SourceRoot, file).Replace('\\', '/')) .Where(file => !ScopeSetterSites.Contains(file)) .Should().BeEmpty( @@ -439,11 +439,37 @@ public void The_Scope_Setter_Scan_Can_Actually_Fail() ScopeSetter().IsMatch("set session app.scope to 'tenant'").Should().BeTrue(); ScopeSetter().IsMatch("OR current_setting('app.scope', true) = 'tenant'").Should().BeFalse( "a policy reading the variable is its subject, not a setter"); + + const string GlobalUnit = "LearnStack.Infrastructure/Persistence/NpgsqlUnitOfWork.cs"; + const string Empty = "SELECT set_config('app.scope', '', true)"; + ScopeSetter().IsMatch(WithoutGlobalAuthorityClears(GlobalUnit, Empty, "app.scope")).Should().BeFalse(); + ScopeSetter().IsMatch(WithoutGlobalAuthorityClears(GlobalUnit, + "SELECT set_config('app.scope', @scope, true)", "app.scope")).Should().BeTrue(); + ScopeSetter().IsMatch(WithoutGlobalAuthorityClears(GlobalUnit, + "SELECT set_config('app.scope', 'tenant', true)", "app.scope")).Should().BeTrue(); + ScopeSetter().IsMatch(WithoutGlobalAuthorityClears("Unlisted.cs", Empty, "app.scope")).Should().BeTrue(); } /// Files allowed to set app.scope, by path under backend/src. Empty until Phase 03. private static readonly HashSet ScopeSetterSites = new(StringComparer.Ordinal); + private static string WithoutGlobalAuthorityClears(string file, string variable) + { + var source = SourceText.WithoutComments(File.ReadAllText(file)); + var relative = Path.GetRelativePath(SourceScan.SourceRoot, file).Replace('\\', '/'); + return WithoutGlobalAuthorityClears(relative, source, variable); + } + + private static string WithoutGlobalAuthorityClears(string relative, string source, string variable) + { + // These exact empty resets remove authority; neither site may acquire + // tenant scope or host-lookup provenance. Nonempty/parameterized setters still fail. + return relative is "LearnStack.Infrastructure/Persistence/NpgsqlUnitOfWork.cs" + or "LearnStack.Infrastructure.Audit/PostgresAuditStore.GlobalIdentity.cs" + ? source.Replace("set_config('" + variable + "', '', true)", string.Empty, StringComparison.Ordinal) + : source; + } + [GeneratedRegex( @"set_config\s*\(\s*'app\.scope'|\bSET\s+(?:LOCAL\s+|SESSION\s+)?app\.scope\b", RegexOptions.IgnoreCase)] @@ -971,7 +997,7 @@ public void Resolving_Host_Is_Set_In_One_Place() Path.GetRelativePath(RepositoryPaths.BackendSrc(), file), SoleSetter, StringComparison.Ordinal)) - .Where(file => SourceText.WithoutComments(File.ReadAllText(file)) + .Where(file => WithoutGlobalAuthorityClears(file, "app.resolving_host") .Contains(Setter, StringComparison.Ordinal)) .Select(file => Path.GetRelativePath(RepositoryPaths.BackendSrc(), file)) .ToList(); diff --git a/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.Organizations.cs b/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.Organizations.cs index dbf8a359f..c8a4ef765 100644 --- a/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.Organizations.cs +++ b/backend/tests/LearnStack.Tests.Architecture/TenantContextConstructionTests.Organizations.cs @@ -13,12 +13,24 @@ public sealed partial class TenantContextConstructionTests private const string OrganizationHistory = "LearnStack.Infrastructure/Jobs/PostgresBackgroundJobControlStore.RecipientHistory.cs"; private const string OrganizationCompletion = "LearnStack.Infrastructure/Jobs/PostgresBackgroundJobRecipientCompletion.cs"; private const string OrganizationOccurrences = "LearnStack.Infrastructure/Jobs/PostgresBackgroundJobControlStore.Occurrences.cs"; + private const string OrganizationIdentityLifecycle = "Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/IdentityScopeLifecycleReader.cs"; private const string OrganizationPointSql = "SELECT status,deleted_at FROM organizations WHERE tenant_id=@tenant AND id=@organization"; private const string OrganizationPageSql = """ SELECT tenant_id,id,status,deleted_at FROM organizations WHERE ROW(tenant_id,id)>ROW(@afterTenant,@afterOrganization) AND ROW(tenant_id,id)<=ROW(@upperTenant,@upperOrganization) ORDER BY tenant_id,id LIMIT @limit """; + private const string OrganizationIdentityLifecycleSql = """ + SELECT t.deleted_at IS NULL, + 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', + current_setting('transaction_isolation') = 'read committed' + FROM public.tenants AS t + LEFT JOIN public.organizations AS o + ON o.tenant_id = t.id AND o.id = @organization + WHERE t.id = @tenant + """; private sealed record OrganizationSqlSubject(string Path, string Type, string Member, string Sql); @@ -31,6 +43,8 @@ private sealed record OrganizationSqlSubject(string Path, string Type, string Me new(OrganizationOccurrences, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobControlStore", "OrganizationLifecyclePageSql", OrganizationPageSql), new(OrganizationOccurrences, "LearnStack.Infrastructure.Jobs.PostgresBackgroundJobControlStore", "FreezeOccurrenceBoundsAsync", "SELECT tenant_id,id FROM organizations ORDER BY tenant_id DESC,id DESC LIMIT 1"), + new(OrganizationIdentityLifecycle, "LearnStack.Modules.Tenancy.Infrastructure.Persistence.IdentityScopeLifecycleReader", + "ReadAsync", OrganizationIdentityLifecycleSql), ]; private static (string Path, string Code)[] OrganizationSources() => @@ -96,11 +110,20 @@ private static string[] OrganizationReadOffenders(IEnumerable<(string Path, stri "command.Parameters.AddWithValue(\"upperOrganization\", cursor.UpperOrganization!.Value)", "command.Parameters.AddWithValue(\"limit\", options.FanoutPageSize)", "Command(resources, cursor.Organizations ? OrganizationLifecyclePageSql : TenantLifecyclePageSql)"); + Require(OrganizationIdentityLifecycle, "IdentityScopeLifecycleReader", "ReadAsync", + "command.Parameters.AddWithValue(\"tenant\", tenantId.Value)", + "command.Parameters.AddWithValue(\"organization\", NpgsqlDbType.Uuid, organizationId is { } org ? org.Value : DBNull.Value)", + "command.ExecuteReaderAsync(cancellationToken)"); return offenders.Distinct(StringComparer.Ordinal).ToArray(); void Require(string path, string type, string method, params string[] calls) { - var expectedNamespace = path == OrganizationValidator ? "LearnStack.Infrastructure.MultiTenancy." : "LearnStack.Infrastructure.Jobs."; + var expectedNamespace = path switch + { + OrganizationValidator => "LearnStack.Infrastructure.MultiTenancy.", + OrganizationIdentityLifecycle => "LearnStack.Modules.Tenancy.Infrastructure.Persistence.", + _ => "LearnStack.Infrastructure.Jobs.", + }; var methods = roots.TryGetValue(path, out var root) ? root.DescendantNodes().OfType().Where(item => item.Identifier.ValueText == method && item.Parent is TypeDeclarationSyntax owner && OrganizationTypeIdentity(owner) == expectedNamespace + type).ToArray() : []; @@ -112,6 +135,7 @@ void Require(string path, string type, string method, params string[] calls) "RecipientHistoryCommand" => ("BackgroundJobControlResources resources, BackgroundJobRecipientClaim claim, string sql", "NpgsqlCommand", SyntaxKind.PrivateKeyword, false), "CreateCommand" => ("string sql", "NpgsqlCommand", SyntaxKind.PrivateKeyword, false), "ReadLifecyclePageAsync" => ("BackgroundJobControlResources resources, OccurrenceCursor cursor, CancellationToken token", "Task>", SyntaxKind.PrivateKeyword, true), + "ReadAsync" => ("TenantId tenantId, OrganizationId? organizationId, CancellationToken cancellationToken = default", "Task", SyntaxKind.PublicKeyword, true), _ => throw new InvalidOperationException("Unknown organization binding owner."), }; if (ownerMethod.Body is null || ownerMethod.TypeParameterList is not null @@ -158,6 +182,13 @@ private static bool ExecutedBinding(InvocationExpressionSyntax call, MethodDecla .Any(node => node is LocalFunctionStatementSyntax or AnonymousFunctionExpressionSyntax)) return false; var statement = call.Ancestors().OfType().FirstOrDefault(); if (statement?.Parent == owner.Body) return true; + // This exact reader translates store failures around one unconditional + // command. Its bindings execute in that root try body, never its catch, + // a nested conditional or a deferred helper. + if (owner.Identifier.ValueText == "ReadAsync" && owner.Parent is TypeDeclarationSyntax lifecycle + && OrganizationTypeIdentity(lifecycle) == "LearnStack.Modules.Tenancy.Infrastructure.Persistence.IdentityScopeLifecycleReader" + && statement?.Parent is BlockSyntax { Parent: TryStatementSyntax guarded } tryBody + && guarded.Parent == owner.Body && ReferenceEquals(guarded.Block, tryBody)) return true; // Only these two cursor values are conditional; they are bound on the // exact branch that selected the organization page, never a local function. return owner.Identifier.ValueText == "ReadLifecyclePageAsync" @@ -193,6 +224,8 @@ private static bool OrganizationSqlUseIsExact(string path, string member, Litera OrganizationHistory => "RecipientHistoryCommand(resources, claim, " + sql + ")", OrganizationOccurrences => "Command(resources, cursor.Organizations ? " + sql + " : \"SELECT id FROM tenants ORDER BY id DESC LIMIT 1\")", + OrganizationIdentityLifecycle => "new NpgsqlCommand(" + sql + + ", (NpgsqlConnection)unit.Connection, (NpgsqlTransaction)transaction) { CommandTimeout = 10 }", _ => null, }; if (expression is null) return false; @@ -208,7 +241,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 five real SQL subjects and their bound keys must exist"); + OrganizationReadOffenders(production).Should().BeEmpty("all six real SQL subjects and their bound keys must exist"); foreach (var subject in OrganizationSqlSubjects) { var source = production.Single(file => file.Path == subject.Path); @@ -257,6 +290,32 @@ public void Organization_reader_census_rejects_missing_keys_extra_readers_and_un "var rebound = command.Parameters.AddWithValue(\"tenant\", claim.TenantId.Value); rebound.Value = Guid.Empty;", StringComparison.Ordinal)); Dirty(history.Path, history.Code.Replace(TenantBinding, "if (false) { " + TenantBinding + " }", StringComparison.Ordinal)); Dirty(history.Path, history.Code + "\ninternal sealed class SplitReader { string Sql() => \"SELECT status FROM \" + \"organizations WHERE id=@organization\"; }"); + var identity = production.Single(file => file.Path == OrganizationIdentityLifecycle); + const string IdentityTenantBinding = "command.Parameters.AddWithValue(\"tenant\", tenantId.Value);"; + const string IdentityOrganizationBinding = "command.Parameters.AddWithValue(\"organization\", NpgsqlDbType.Uuid, organizationId is { } org\n ? org.Value : DBNull.Value);"; + foreach (var binding in new[] { IdentityTenantBinding, IdentityOrganizationBinding }) + { + identity.Code.Should().Contain(binding, "the mutation must reach the actual lifecycle reader's protected binding"); + Dirty(identity.Path, identity.Code.Replace(binding, "", StringComparison.Ordinal)); + Dirty(identity.Path, identity.Code.Replace(binding, "void UnusedBinding() { " + binding + " }", StringComparison.Ordinal)); + Dirty(identity.Path, identity.Code.Replace(binding, "if (false) { " + binding + " }", StringComparison.Ordinal)); + } + foreach (var (from, to) in new[] + { + ("o.tenant_id = t.id AND ", ""), ("WHERE t.id = @tenant", "WHERE t.id IS NOT NULL"), + ("\"tenant\", tenantId.Value", "\"tenant\", Guid.Empty"), + ("? org.Value : DBNull.Value", "? Guid.Empty : DBNull.Value"), + ("OrganizationId? organizationId", "OrganizationId organizationId"), + ("Task", "Task"), + ("(NpgsqlConnection)unit.Connection", "unit.Connection"), + ("(NpgsqlTransaction)transaction", "transaction"), + ("CommandTimeout = 10", "CommandTimeout = 20"), + ("command.ExecuteReaderAsync(cancellationToken)", "command.ExecuteReaderAsync(CancellationToken.None)"), + }) Dirty(identity.Path, identity.Code.Replace(from, to, StringComparison.Ordinal)); + Dirty(identity.Path, identity.Code.Replace(IdentityTenantBinding, IdentityTenantBinding + + " command.Parameters[\"tenant\"].Value = Guid.Empty;", StringComparison.Ordinal)); + Dirty(identity.Path, identity.Code.Replace(IdentityTenantBinding, + "var rebound = command.Parameters.AddWithValue(\"tenant\", tenantId.Value); rebound.Value = Guid.Empty;", StringComparison.Ordinal)); OrganizationReadOffenders(production.Select(file => (file.Path, "// FROM organizations is a harmless comment\n" + file.Code))) .Should().BeEmpty("comments and source formatting cannot create or authorize SQL subjects"); OrganizationReadOffenders(production).Should().BeEmpty("the actual source is restored after every planted copy"); diff --git a/backend/tests/LearnStack.Tests.Architecture/TenantScopingTests.cs b/backend/tests/LearnStack.Tests.Architecture/TenantScopingTests.cs index 35dd2eb0d..f2b833935 100644 --- a/backend/tests/LearnStack.Tests.Architecture/TenantScopingTests.cs +++ b/backend/tests/LearnStack.Tests.Architecture/TenantScopingTests.cs @@ -10,6 +10,9 @@ using LearnStack.SharedKernel.Tenancy; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations.Operations; using Xunit; namespace LearnStack.Tests.Architecture; @@ -342,7 +345,16 @@ private static string MigrationSql() files.Should().NotBeEmpty("the migration scan has nothing to read"); - return string.Join("\n", files.Select(File.ReadAllText)); + // Resolve the actual compiled Identity migration operations too: its + // finite installer emits one policy per table without duplicating the + // template into five source literals. Removing the installer call removes + // these operations, so the scan cannot vouch for an uninvoked helper. + using var identity = Modules.ModelOnly(); + var assembly = identity.GetService(); + var installed = assembly.Migrations.SelectMany(pair => + assembly.CreateMigration(pair.Value, identity.Database.ProviderName!).UpOperations) + .OfType().Select(operation => operation.Sql.Replace("public.", "", StringComparison.Ordinal)); + return string.Join("\n", files.Select(File.ReadAllText).Concat(installed)); } private static void AssertRowSecurity(string migrations, string table, string keyColumn) diff --git a/backend/tests/LearnStack.Tests.Contract/DevelopmentWebApplicationFactory.cs b/backend/tests/LearnStack.Tests.Contract/DevelopmentWebApplicationFactory.cs index c3ddb10f2..e2affba55 100644 --- a/backend/tests/LearnStack.Tests.Contract/DevelopmentWebApplicationFactory.cs +++ b/backend/tests/LearnStack.Tests.Contract/DevelopmentWebApplicationFactory.cs @@ -1,5 +1,6 @@ using LearnStack.Api.Messaging; using LearnStack.Api.Jobs; +using LearnStack.Api.Authentication; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; @@ -20,8 +21,8 @@ namespace LearnStack.Tests.Contract; /// in CI without it. Packet 4 removed that gate — the document is the contract /// the SDK generates from and CI diffs, so it is served in every environment — /// and the environment override keeps the contract suite on one known environment. -/// This served-contract fixture also removes the dispatcher workers because it owns -/// no dispatcher database. Its retained private outbox and delivery health checks +/// This served-contract fixture removes dispatcher and identity startup workers because +/// it owns no database. Its retained private outbox and delivery health checks /// intentionally remain Unhealthy; the static /healthz liveness endpoint stays independent. /// public sealed class DevelopmentWebApplicationFactory : WebApplicationFactory @@ -29,21 +30,22 @@ public sealed class DevelopmentWebApplicationFactory : WebApplicationFactory { foreach (var descriptor in services.Where(descriptor => descriptor.ServiceType == typeof(IHostedService) - && IsDispatcher(descriptor)).ToArray()) + && IsDatabaseStartupWorker(descriptor)).ToArray()) services.Remove(descriptor); }); } - private static bool IsDispatcher(ServiceDescriptor descriptor) + private static bool IsDatabaseStartupWorker(ServiceDescriptor descriptor) { var implementation = descriptor.ImplementationType ?? descriptor.ImplementationFactory?.Method.ReturnType; return implementation == typeof(OutboxProcessor) || implementation == typeof(DeliveryProcessor) - || implementation == typeof(BackgroundJobHostedService); + || implementation == typeof(BackgroundJobHostedService) + || implementation == typeof(TenantIdentityAuthorityStartupService); } } diff --git a/backend/tests/LearnStack.Tests.Integration/AuthenticatedRateLimitTests.Admission.cs b/backend/tests/LearnStack.Tests.Integration/AuthenticatedRateLimitTests.Admission.cs index 771fa29f9..be56f3e4d 100644 --- a/backend/tests/LearnStack.Tests.Integration/AuthenticatedRateLimitTests.Admission.cs +++ b/backend/tests/LearnStack.Tests.Integration/AuthenticatedRateLimitTests.Admission.cs @@ -102,7 +102,7 @@ public async Task Signed_admission_exports_quota_capacity_and_sticky_fault_witho replay.Features.Set(HostClassification.Platform("admission-replay-canary.example")); replay.Features.Set(new TenantCredentialFeature { - Identity = new ValidatedTenantIdentity( + VerifiedSubject = new VerifiedProviderSubject( issuer.Issuer, "replay-subject-canary", UserId.From(TenantAuthenticationIssuer.Actor), null, null) }); var middleware = new TenantSubjectAdmissionMiddleware( @@ -208,6 +208,7 @@ private HttpClient AdmissionClient(TenantAuthenticationIssuer issuer, AdmissionS SubjectQuotaObservation observed, AdmissionMembershipObservation memberships, string? endpoint = null) => fixture.ClientFor(SeedData.English.Host, services => { + AddQuotaBindings(services, issuer); services.RemoveAll(); services.AddSingleton(_ => scenario.Owner); services.AddScoped(); diff --git a/backend/tests/LearnStack.Tests.Integration/AuthenticatedRateLimitTests.cs b/backend/tests/LearnStack.Tests.Integration/AuthenticatedRateLimitTests.cs index d9d5739a4..36da519ab 100644 --- a/backend/tests/LearnStack.Tests.Integration/AuthenticatedRateLimitTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/AuthenticatedRateLimitTests.cs @@ -28,6 +28,7 @@ public async Task Authenticated_Rate_Limits_Use_Validated_Subject() var observed = new SubjectQuotaObservation(); using var client = fixture.ClientFor(SeedData.English.Host, services => { + AddQuotaBindings(services, issuer); services.RemoveAll(); services.AddSingleton(_ => new TenantSubjectRateLimiter( () => TenantSubjectRateLimiter.CreateBudget(permitLimit: 3), @@ -101,6 +102,7 @@ public async Task Production_visitor_quota_blocks_validated_subjects_with_replen await using var issuer = await TenantAuthenticationIssuer.StartAsync(); using var client = fixture.ClientFor(SeedData.English.Host, services => { + AddQuotaBindings(services, issuer); // Keep the production coordinator, quota and window. Disable only // its visitor timer so slow DB-backed HTTP calls cannot replenish // this proof's spent quota. Above asserts the stock automatic-timer @@ -126,6 +128,12 @@ public async Task Production_visitor_quota_blocks_validated_subjects_with_replen fixture.Observation.Reads.Should().Be(reads + RateLimitingExtensions.AnonymousPermitPerWindow); } + private static void AddQuotaBindings(IServiceCollection services, TenantAuthenticationIssuer issuer) => + services.AddSingleton(new FixtureTenantIdentityBindingResolver(issuer.Issuer, + ["opaque-keycloak-subject", "independent-subject-B", "fresh-subject", "admission-subject-A", + "admission-subject-B", "admission-subject-C", "blocked-retiring-subject", + "blocked-retained-subject", "blocked-competing-subject"])); + private sealed class SubjectQuotaObservation : IStartupFilter, ILogEventSink { internal IServiceProvider Services { get; private set; } = null!; diff --git a/backend/tests/LearnStack.Tests.Integration/ConstructionOnlyApiFactory.cs b/backend/tests/LearnStack.Tests.Integration/ConstructionOnlyApiFactory.cs index a572e1b3e..b1b45861e 100644 --- a/backend/tests/LearnStack.Tests.Integration/ConstructionOnlyApiFactory.cs +++ b/backend/tests/LearnStack.Tests.Integration/ConstructionOnlyApiFactory.cs @@ -1,5 +1,6 @@ using LearnStack.Api.Messaging; using LearnStack.Api.Jobs; +using LearnStack.Api.Authentication; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; @@ -9,8 +10,9 @@ namespace LearnStack.Tests.Integration; /// -/// Request/composition proofs own no background dispatcher. Production startup -/// proofs use an ordinary factory and must supply its confined credential. +/// Request/composition proofs own no background dispatcher or identity authority. +/// Real identity derivatives explicitly retain qualification; production worker +/// proofs use an ordinary factory and supply their confined credentials. /// /// /// The retained private outbox health check intentionally remains Unhealthy when @@ -22,7 +24,23 @@ protected sealed override void ConfigureWebHost(IWebHostBuilder builder) { ArgumentNullException.ThrowIfNull(builder); ConfigureTestHost(builder); - builder.ConfigureTestServices(RemoveDispatcher); + builder.ConfigureTestServices(services => + { + RemoveDispatcher(services); + if (!RetainIdentityQualification) + RemoveIdentityQualification(services); + }); + } + + /// Real provider/database derivatives retain the production startup qualification. + protected virtual bool RetainIdentityQualification => false; + + internal static void RemoveIdentityQualification(IServiceCollection services) + { + foreach (var descriptor in services.Where(descriptor => descriptor.ServiceType == typeof(IHostedService) + && (descriptor.ImplementationType ?? descriptor.ImplementationFactory?.Method.ReturnType) + == typeof(TenantIdentityAuthorityStartupService)).ToArray()) + services.Remove(descriptor); } protected virtual void ConfigureTestHost(IWebHostBuilder builder) diff --git a/backend/tests/LearnStack.Tests.Integration/ConstructionOnlyApiFactoryTests.cs b/backend/tests/LearnStack.Tests.Integration/ConstructionOnlyApiFactoryTests.cs index 443559652..6e5e4ed6c 100644 --- a/backend/tests/LearnStack.Tests.Integration/ConstructionOnlyApiFactoryTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/ConstructionOnlyApiFactoryTests.cs @@ -1,6 +1,7 @@ using LearnStack.Infrastructure.Persistence; using FluentAssertions; using LearnStack.Api.Messaging; +using LearnStack.Api.Authentication; using LearnStack.Infrastructure.Messaging; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; @@ -18,9 +19,12 @@ public void Request_only_test_composition_removes_exactly_both_dispatchers_and_p services.AddHostedService(); services.AddHostedService(); services.AddHostedService(); - services.Count(descriptor => descriptor.ServiceType == typeof(IHostedService)).Should().Be(3); + services.AddHostedService(); + services.Count(descriptor => descriptor.ServiceType == typeof(IHostedService)).Should().Be(4); ConstructionOnlyApiFactory.RemoveDispatcher(services); + services.Where(descriptor => descriptor.ServiceType == typeof(IHostedService)).Should().HaveCount(2); + ConstructionOnlyApiFactory.RemoveIdentityQualification(services); services.Where(descriptor => descriptor.ServiceType == typeof(IHostedService)) .Should().ContainSingle().Which.ImplementationType.Should().Be(); @@ -33,6 +37,7 @@ public async Task Construction_only_host_leaves_the_dispatcher_source_unresolved using var client = host.CreateClient(); host.Services.GetServices().Should().NotContain(service => service is OutboxProcessor || service is DeliveryProcessor); + host.Services.GetServices().Should().NotContain(service => service is TenantIdentityAuthorityStartupService); host.Services.GetRequiredKeyedService(OutboxDispatcherDataSource.Key) .IsValueCreated.Should().BeFalse(); (await client.GetAsync("/healthz")).IsSuccessStatusCode.Should().BeTrue(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AccountSiteHttpTests.Audit.cs b/backend/tests/LearnStack.Tests.Integration/Database/AccountSiteHttpTests.Audit.cs index 43fd12d90..1dbbc82fa 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/AccountSiteHttpTests.Audit.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/AccountSiteHttpTests.Audit.cs @@ -2,6 +2,7 @@ using System.Text.Json; using FluentAssertions; using LearnStack.Api.Tenancy; +using LearnStack.SharedKernel.Identifiers; using LearnStack.Tools.Seeder; using Npgsql; using Xunit; @@ -19,8 +20,10 @@ public sealed partial class AccountSiteHttpTests public async Task Actual_account_route_preserves_claim_and_membership_codes_and_durable_host_attribution(int row) { await using var issuer = await TenantAuthenticationIssuer.StartAsync(); + await using var fixture = await IdentityPublicReadFixture.CreateAsync(parent, issuer.Issuer, + new Dictionary { [UserId.From(TenantAuthenticationIssuer.Actor)] = "opaque-keycloak-subject" }); var tenant = row is 7 or 8 ? SeedData.English : SeedData.Yoga; - using var client = Client(issuer, tenant.Host); + using var client = Client(fixture, issuer, tenant.Host); var token = row switch { 8 => Token(issuer, tenant, claimedTenant: SeedData.Yoga.TenantId.Value), @@ -67,7 +70,9 @@ await TenantAuthenticationHttpTests.Problem(response, HttpStatusCode.NotFound, public async Task Actual_authenticated_header_rejection_preserves_actor_correlation_and_trusted_organization(bool claimless) { await using var issuer = await TenantAuthenticationIssuer.StartAsync(); - using var client = Client(issuer, SeedData.Yoga.Host); + await using var fixture = await IdentityPublicReadFixture.CreateAsync(parent, issuer.Issuer, + new Dictionary { [UserId.From(TenantAuthenticationIssuer.Actor)] = "opaque-keycloak-subject" }); + using var client = Client(fixture, issuer, SeedData.Yoga.Host); var token = claimless ? issuer.Token(issuer.Without("tenant_id", "organization_id")) : Token(issuer, SeedData.Yoga, organization: true); var reads = fixture.Observation.Reads; @@ -91,7 +96,9 @@ public async Task Actual_authenticated_header_rejection_preserves_actor_correlat public async Task Anonymous_header_mismatch_and_malformed_assertions_keep_their_distinct_errors_without_query_reads(string path) { await using var issuer = await TenantAuthenticationIssuer.StartAsync(); - using var client = Client(issuer, SeedData.English.Host); + await using var fixture = await IdentityPublicReadFixture.CreateAsync(parent, issuer.Issuer, + new Dictionary { [UserId.From(TenantAuthenticationIssuer.Actor)] = "opaque-keycloak-subject" }); + using var client = Client(fixture, issuer, SeedData.English.Host); var reads = fixture.Observation.Reads; using var anonymous = await TenantAuthenticationHttpRequest.Send(client, SeedData.English.Host, TenantAuthenticationHttpRequest.PublicPath, tenantAssertion: SeedData.Yoga.TenantId.Value.ToString("D")); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AccountSiteHttpTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/AccountSiteHttpTests.cs index 5b8e76d73..7beff7a90 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/AccountSiteHttpTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/AccountSiteHttpTests.cs @@ -19,13 +19,15 @@ namespace LearnStack.Tests.Integration.Database; /// Signed credentials through the production route, real host mappings and application-role reads. [Collection(PublicReadTestGroup.Name)] [Trait(RequiresDocker.Key, RequiresDocker.Value)] -public sealed partial class AccountSiteHttpTests(PublicReadFixture fixture) +public sealed partial class AccountSiteHttpTests(PublicReadFixture parent) { [Fact] public async Task Actual_account_HTTP_reads_English_and_Yoga_row_9_under_ReadOnly_without_query_audits() { await using var issuer = await TenantAuthenticationIssuer.StartAsync(); - using var client = Client(issuer, SeedData.English.Host); + await using var fixture = await IdentityPublicReadFixture.CreateAsync(parent, issuer.Issuer, + new Dictionary { [UserId.From(TenantAuthenticationIssuer.Actor)] = "opaque-keycloak-subject" }); + using var client = Client(fixture, issuer, SeedData.English.Host); var englishAudits = await fixture.AuditCountAsync(SeedData.English); var yogaAudits = await fixture.AuditCountAsync(SeedData.Yoga); var reads = fixture.Observation.Reads; @@ -50,8 +52,10 @@ public async Task Actual_account_HTTP_reads_English_and_Yoga_row_9_under_ReadOnl public async Task Anonymous_public_site_survives_an_unavailable_issuer_and_failed_credentials_never_fall_back() { await using var issuer = await TenantAuthenticationIssuer.StartAsync(); + await using var fixture = await IdentityPublicReadFixture.CreateAsync(parent, issuer.Issuer, + new Dictionary { [UserId.From(TenantAuthenticationIssuer.Actor)] = "opaque-keycloak-subject" }); issuer.DiscoveryStatusCode = 503; - using var client = Client(issuer, SeedData.English.Host); + using var client = Client(fixture, issuer, SeedData.English.Host); using var anonymous = await TenantAuthenticationHttpRequest.Send(client, SeedData.English.Host, TenantAuthenticationHttpRequest.PublicPath); anonymous.StatusCode.Should().Be(HttpStatusCode.OK); @@ -78,8 +82,10 @@ public async Task Anonymous_public_site_survives_an_unavailable_issuer_and_faile public async Task Claimless_signed_profiles_keep_the_public_ceiling_and_emit_one_fixed_Debug_event_per_admitted_request() { await using var issuer = await TenantAuthenticationIssuer.StartAsync(); + await using var fixture = await IdentityPublicReadFixture.CreateAsync(parent, issuer.Issuer, + new Dictionary { [UserId.From(TenantAuthenticationIssuer.Actor)] = "opaque-keycloak-subject" }); var logs = new AccountHttpLogObservation(); - using var client = Client(issuer, SeedData.Yoga.Host, services => services.AddSingleton(logs)); + using var client = Client(fixture, issuer, SeedData.Yoga.Host, services => services.AddSingleton(logs)); var token = issuer.Token(issuer.Without("tenant_id", "organization_id")); var audits = await fixture.AuditCountAsync(SeedData.Yoga); using var publicResponse = await TenantAuthenticationHttpRequest.Send(client, SeedData.Yoga.Host, @@ -100,7 +106,9 @@ public async Task Claimless_signed_profiles_keep_the_public_ceiling_and_emit_one public async Task Actual_account_HTTP_rechecks_a_suspended_mapped_organization_after_host_cache_warmup() { await using var issuer = await TenantAuthenticationIssuer.StartAsync(); - using var client = Client(issuer, SeedData.Yoga.Host); + await using var fixture = await IdentityPublicReadFixture.CreateAsync(parent, issuer.Issuer, + new Dictionary { [UserId.From(TenantAuthenticationIssuer.Actor)] = "opaque-keycloak-subject" }); + using var client = Client(fixture, issuer, SeedData.Yoga.Host); var token = Token(issuer, SeedData.Yoga, organization: true); using var warm = await Send(client, SeedData.Yoga, token); await Account(warm, SeedData.Yoga, organization: true); @@ -127,8 +135,10 @@ await fixture.ExecuteAsync(SeedData.Yoga, public async Task Future_platform_membership_success_still_masks_AccountSite_before_configuration_access() { await using var issuer = await TenantAuthenticationIssuer.StartAsync(); + await using var fixture = await IdentityPublicReadFixture.CreateAsync(parent, issuer.Issuer, + new Dictionary { [UserId.From(TenantAuthenticationIssuer.Actor)] = "opaque-keycloak-subject" }); var membership = new ConfirmedAccountMembership(); - using var client = Client(issuer, "localhost", services => services.AddSingleton(membership)); + using var client = Client(fixture, issuer, "localhost", services => services.AddSingleton(membership)); var reads = fixture.Observation.Reads; var audits = await fixture.AuditCountAsync(SeedData.Yoga); using var response = await TenantAuthenticationHttpRequest.Send(client, "localhost", @@ -151,7 +161,9 @@ public async Task Future_platform_membership_success_still_masks_AccountSite_bef public async Task Actual_account_HTTP_admits_only_the_enumerated_GET(string method) { await using var issuer = await TenantAuthenticationIssuer.StartAsync(); - using var client = Client(issuer, SeedData.English.Host); + await using var fixture = await IdentityPublicReadFixture.CreateAsync(parent, issuer.Issuer, + new Dictionary { [UserId.From(TenantAuthenticationIssuer.Actor)] = "opaque-keycloak-subject" }); + using var client = Client(fixture, issuer, SeedData.English.Host); var reads = fixture.Observation.Reads; using var response = await TenantAuthenticationHttpRequest.Send(client, SeedData.English.Host, token: Token(issuer, SeedData.English), method: method); @@ -179,7 +191,9 @@ public async Task Actual_account_HTTP_admits_only_the_enumerated_GET(string meth public async Task Application_body_limit_refusals_keep_no_store_before_credential_admission(string path) { await using var issuer = await TenantAuthenticationIssuer.StartAsync(); - using var client = Client(issuer, SeedData.English.Host); + await using var fixture = await IdentityPublicReadFixture.CreateAsync(parent, issuer.Issuer, + new Dictionary { [UserId.From(TenantAuthenticationIssuer.Actor)] = "opaque-keycloak-subject" }); + using var client = Client(fixture, issuer, SeedData.English.Host); var reads = fixture.Observation.Reads; using var request = new HttpRequestMessage(HttpMethod.Get, path); request.Headers.TryAddWithoutValidation("Authorization", "Bearer invalid"); @@ -195,7 +209,9 @@ public async Task Application_body_limit_refusals_keep_no_store_before_credentia public async Task Account_query_parameters_are_rejected_before_configuration_and_stay_no_store() { await using var issuer = await TenantAuthenticationIssuer.StartAsync(); - using var client = Client(issuer, SeedData.English.Host); + await using var fixture = await IdentityPublicReadFixture.CreateAsync(parent, issuer.Issuer, + new Dictionary { [UserId.From(TenantAuthenticationIssuer.Actor)] = "opaque-keycloak-subject" }); + using var client = Client(fixture, issuer, SeedData.English.Host); var reads = fixture.Observation.Reads; using var response = await TenantAuthenticationHttpRequest.Send(client, SeedData.English.Host, TenantAuthenticationHttpRequest.AccountPath + "?tenantId=" + SeedData.Yoga.TenantId.Value.ToString("D"), @@ -206,7 +222,7 @@ public async Task Account_query_parameters_are_rejected_before_configuration_and fixture.Observation.Reads.Should().Be(reads); } - private HttpClient Client(TenantAuthenticationIssuer issuer, string host, Action? configure = null) => + private static HttpClient Client(PublicReadFixture fixture, TenantAuthenticationIssuer issuer, string host, Action? configure = null) => fixture.ClientFor(host, configure, builder => { builder.UseSetting(TenantAuthenticationOptions.IssuerConfigurationKey, issuer.Issuer); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/AuditStoreTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/AuditStoreTests.cs index a58ac32c2..684aa873f 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/AuditStoreTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/AuditStoreTests.cs @@ -409,7 +409,7 @@ public async Task A_best_effort_failure_is_logged_and_dropped() logger, MeterFactory, health, - new AuditCatalog([]), StaticTenantContextAccessor.Unresolved); + new AuditCatalog([]), StaticTenantContextAccessor.Unresolved, new LearnStack.Infrastructure.Persistence.GlobalIdentityEnrollment()); // TenantB is a real tenant, but the draft's own announcement makes the row legal — // so to force a failure the row has to break something the announcement cannot @@ -769,7 +769,7 @@ public async Task A_best_effort_write_swallows_a_data_source_that_cannot_be_buil NullLogger.Instance, MeterFactory, new AuditHealth(), - new AuditCatalog([]), StaticTenantContextAccessor.Unresolved); + new AuditCatalog([]), StaticTenantContextAccessor.Unresolved, new LearnStack.Infrastructure.Persistence.GlobalIdentityEnrollment()); var bestEffort = async () => await store.WriteBestEffortAsync(Draft(organizationId: null)); @@ -954,7 +954,7 @@ public async Task A_standalone_failure_is_Critical_counted_and_leaves_the_check_ logger, MeterFactory, health, - new AuditCatalog([]), StaticTenantContextAccessor.Unresolved); + new AuditCatalog([]), StaticTenantContextAccessor.Unresolved, new LearnStack.Infrastructure.Persistence.GlobalIdentityEnrollment()); var counted = 0L; using var listener = new MeterListener(); @@ -1010,7 +1010,7 @@ public async Task A_failure_the_store_cannot_translate_is_still_Critical_counted logger, MeterFactory, health, - new AuditCatalog([]), StaticTenantContextAccessor.Unresolved); + new AuditCatalog([]), StaticTenantContextAccessor.Unresolved, new LearnStack.Infrastructure.Persistence.GlobalIdentityEnrollment()); var counted = 0L; using var listener = new MeterListener(); @@ -1127,7 +1127,7 @@ private static PostgresAuditStore Store(AuditStateCapture capture, NpgsqlDataSou private static PostgresAuditStore Store( AuditStateCapture capture, NpgsqlDataSource dataSource, IAuditHealth health) => new(capture, new Lazy(() => dataSource), - NullLogger.Instance, MeterFactory, health, new AuditCatalog([]), StaticTenantContextAccessor.Unresolved); + NullLogger.Instance, MeterFactory, health, new AuditCatalog([]), StaticTenantContextAccessor.Unresolved, new LearnStack.Infrastructure.Persistence.GlobalIdentityEnrollment()); /// A real meter factory, so the counter the store increments is a real one. private static readonly IMeterFactory MeterFactory = diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobApplicationSourceTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobApplicationSourceTests.cs index d1f846224..01cd755ea 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobApplicationSourceTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobApplicationSourceTests.cs @@ -53,7 +53,7 @@ public async Task Actual_main_and_audit_helpers_share_two_slots_and_clean_SQL_fa owner.RequireOwnedMainUnit(unit); var store = new PostgresAuditStore(new AuditStateCapture(), new Lazy(() => source), NullLogger.Instance, metrics.GetRequiredService(), new AuditHealth(), - new AuditCatalog([]), new StaticTenantContextAccessor(Context)); + new AuditCatalog([]), new StaticTenantContextAccessor(Context), new LearnStack.Infrastructure.Persistence.GlobalIdentityEnrollment()); var invalid = Draft() with { Metadata = "not-json" }; var failed = () => store.WriteStandaloneAsync(invalid); await failed.Should().ThrowAsync(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobControlTests.Terminal.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobControlTests.Terminal.cs index 6e834bbaf..a9ee437b0 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobControlTests.Terminal.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobControlTests.Terminal.cs @@ -417,6 +417,14 @@ public ValueTask DisposeAsync() private sealed class JobAuditDecorator(IAuditStore inner, Func terminal) : IAuditStore { + public Task WriteGlobalIdentityPendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unit, + GlobalIdentityCreationReference creation, CancellationToken cancellationToken = default) => + inner.WriteGlobalIdentityPendingAsync(unit, creation, cancellationToken); + + public Task ReconcileGlobalIdentityAsync(AuditIntent intent, IReadOnlyList changes, + AuditIntentState state, DateTimeOffset timestamp, CancellationToken cancellationToken = default) => + inner.ReconcileGlobalIdentityAsync(intent, changes, state, timestamp, cancellationToken); + public Task WritePendingAsync(IUnitOfWork unit, CancellationToken token = default) => inner.WritePendingAsync(unit, token); public Task WriteStandaloneAsync(AuditEntryDraft entry, CancellationToken token = default) => inner.WriteStandaloneAsync(entry, token); public Task WriteBestEffortAsync(AuditEntryDraft entry, CancellationToken token = default) => inner.WriteBestEffortAsync(entry, token); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobExternalIsolationTests.Helpers.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobExternalIsolationTests.Helpers.cs index ddffb5386..0cc57d71f 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobExternalIsolationTests.Helpers.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobExternalIsolationTests.Helpers.cs @@ -46,7 +46,7 @@ public async Task Concrete_cold_helpers_refuse_source_less_live_and_retained_ext var overlay = new KillswitchOverlay(lazy, cache, NullLogger.Instance); var flags = new FeatureFlags(context, new NullEntitlementProvider(), overlay, lazy, cache, NullLogger.Instance); var store = new PostgresAuditStore(new AuditStateCapture(), lazy, NullLogger.Instance, - meterFactory, new AuditHealth(), new AuditCatalog([]), new StaticTenantContextAccessor(context)); + meterFactory, new AuditHealth(), new AuditCatalog([]), new StaticTenantContextAccessor(context), new LearnStack.Infrastructure.Persistence.GlobalIdentityEnrollment()); var draft = HelperDraft(); var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); Task inherited; diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CombinedPhysicalCapacity.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CombinedPhysicalCapacity.cs index 48754de52..53b9c4ea3 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CombinedPhysicalCapacity.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobRuntimeFacadeTests.CombinedPhysicalCapacity.cs @@ -248,6 +248,14 @@ private sealed class CombinedTerminalHold private sealed class CombinedTerminalAuditStore(PostgresAuditStore inner, CombinedTerminalHold outbox, CombinedTerminalHold delivery) : IAuditStore, IAsyncDisposable { + public Task WriteGlobalIdentityPendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unit, + GlobalIdentityCreationReference creation, CancellationToken cancellationToken = default) => + inner.WriteGlobalIdentityPendingAsync(unit, creation, cancellationToken); + + public Task ReconcileGlobalIdentityAsync(AuditIntent intent, IReadOnlyList changes, + AuditIntentState state, DateTimeOffset timestamp, CancellationToken cancellationToken = default) => + inner.ReconcileGlobalIdentityAsync(intent, changes, state, timestamp, cancellationToken); + private CombinedTerminalHold? _hold; public Task WritePendingAsync(IUnitOfWork unit, CancellationToken token = default) => inner.WritePendingAsync(unit, token); public Task WriteStandaloneAsync(AuditEntryDraft entry, CancellationToken token = default) => inner.WriteStandaloneAsync(entry, token); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobStorageMigrationTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobStorageMigrationTests.cs index be2bdf902..9b3e75891 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobStorageMigrationTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/BackgroundJobStorageMigrationTests.cs @@ -60,7 +60,9 @@ public async Task Fresh_down_reapply_restores_every_job_object_and_retains_exist await using (var owner = await PostgresFixture.OpenAsync(database.MigrationConnectionString)) { (await SchemaQueries.ReadStringsAsync(owner, SchemaQueries.TableNames)).Should() - .BeEquivalentTo(SchemaTableClasses.Existing, "all preexisting data tables survive this additive migration reversal"); + .BeEquivalentTo(SchemaTableClasses.Existing.Concat(SchemaTableClasses.GlobalIdentity) + .Concat(SchemaTableClasses.IdentityPlatform).Concat(SchemaTableClasses.IdentityContextual), + "all event-era and independently added Identity data tables survive this Platform-only reversal"); } await context.Database.MigrateAsync(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/CustomizationDefaultDeliveryTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/CustomizationDefaultDeliveryTests.cs index 5c97f69ab..6aa8d2bcb 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/CustomizationDefaultDeliveryTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/CustomizationDefaultDeliveryTests.cs @@ -1,4 +1,5 @@ using FluentAssertions; +using LearnStack.Api.Authentication; using LearnStack.Api.Messaging; using LearnStack.Infrastructure.Messaging; using LearnStack.Modules.Tenancy.Application.Contracts.IntegrationEvents; @@ -10,6 +11,7 @@ using MediatR; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging.Abstractions; @@ -420,6 +422,14 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) builder.UseSetting("ConnectionStrings:Default", database.AppConnectionString); builder.UseSetting("ConnectionStrings:PlatformAdmin", database.PlatformConnectionString); builder.UseSetting("ConnectionStrings:OutboxDispatcher", database.OutboxConnectionString); + builder.ConfigureTestServices(services => + { + // This fixture owns real default delivery and provisioning, but no Identity authority. + foreach (var descriptor in services.Where(descriptor => descriptor.ServiceType == typeof(IHostedService) + && (descriptor.ImplementationType ?? descriptor.ImplementationFactory?.Method.ReturnType) + == typeof(TenantIdentityAuthorityStartupService)).ToArray()) + services.Remove(descriptor); + }); } } } diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DeliveryDispatchStoreTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryDispatchStoreTests.cs index de0f5a21f..141eb7caf 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/DeliveryDispatchStoreTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryDispatchStoreTests.cs @@ -789,6 +789,14 @@ public ValueTask DisposeAsync() private sealed class AuditDecorator(IAuditStore inner, Func terminal) : IAuditStore { + public Task WriteGlobalIdentityPendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unit, + GlobalIdentityCreationReference creation, CancellationToken cancellationToken = default) => + inner.WriteGlobalIdentityPendingAsync(unit, creation, cancellationToken); + + public Task ReconcileGlobalIdentityAsync(AuditIntent intent, IReadOnlyList changes, + AuditIntentState state, DateTimeOffset timestamp, CancellationToken cancellationToken = default) => + inner.ReconcileGlobalIdentityAsync(intent, changes, state, timestamp, cancellationToken); + public Task WriteJobTerminalAsync(AuditEntryDraft entry, JobTerminalTransition transition, DbConnection connection, DbTransaction transaction, CancellationToken token = default) => inner.WriteJobTerminalAsync(entry, transition, connection, transaction, token); public Task WritePendingAsync(IUnitOfWork unit, CancellationToken token = default) => inner.WritePendingAsync(unit, token); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DeliveryProcessorTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryProcessorTests.cs index 1634d0548..68e85d760 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/DeliveryProcessorTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/DeliveryProcessorTests.cs @@ -2,6 +2,7 @@ using System.Collections.Concurrent; using System.Diagnostics; using FluentAssertions; +using LearnStack.Api.Authentication; using LearnStack.Api.Jobs; using LearnStack.Api.Messaging; using LearnStack.Application.Messaging; @@ -861,9 +862,11 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) builder.UseSetting("ConnectionStrings:OutboxDispatcher", fixture._database.OutboxConnectionString); builder.ConfigureTestServices(services => { + // This fixture owns the real delivery worker and its storage, but no Identity authority. foreach (var descriptor in services.Where(descriptor => descriptor.ServiceType == typeof(IHostedService) && (descriptor.ImplementationType ?? descriptor.ImplementationFactory?.Method.ReturnType) is { } implementation && (implementation == typeof(OutboxProcessor) || implementation == typeof(BackgroundJobHostedService) + || implementation == typeof(TenantIdentityAuthorityStartupService) || removeWorker && implementation == typeof(DeliveryProcessor))).ToArray()) services.Remove(descriptor); services.RemoveAll(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/DomainEventProductionTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/DomainEventProductionTests.cs index 82df8eda8..c79dc5ab9 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/DomainEventProductionTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/DomainEventProductionTests.cs @@ -818,7 +818,7 @@ private static Task RunAsync(IServiceProvider services, Fu services.GetRequiredService(), services.GetRequiredService(), services.GetRequiredService(), services.GetRequiredService(), services.GetRequiredService(), services.GetRequiredService(), - NullLogger.Instance); + NullLogger.Instance, services.GetRequiredService()); return audit.ExecuteAsync(audited ? typeof(AuditedProbe) : typeof(SilentProbe), null, () => services.GetRequiredService().ExecuteAsync( null, TransactionMode.ReadWrite, "domain-production-proof", body, cancellationToken), cancellationToken); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.Detectors.cs b/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.Detectors.cs index 4892d4389..67806478e 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.Detectors.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.Detectors.cs @@ -3,6 +3,7 @@ using System.Text.RegularExpressions; using LearnStack.Modules.Education.Domain; using LearnStack.Modules.Education.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Infrastructure.Persistence; using LearnStack.SharedKernel.Persistence; using LearnStack.SharedKernel.Tenancy; using Microsoft.EntityFrameworkCore; @@ -18,13 +19,21 @@ public sealed partial class EducationStructureTests // database FK is therefore a failure, as is introducing an unclassified relation. private sealed record ParentRelation(string Child, string Parent, string ParentId, string DeleteAction); - private static readonly ParentRelation[] ParentRelations = + private static readonly ParentRelation[] EducationParentRelations = [ new("lessons", "courses", "course_id", "r"), new("course_translations", "courses", "course_id", "c"), new("lesson_translations", "lessons", "lesson_id", "c"), ]; + private static readonly ParentRelation[] IdentityParentRelations = + [ + new("membership_profiles", "memberships", "membership_id", "r"), + new("membership_role_assignments", "memberships", "membership_id", "r"), + ]; + + private static readonly ParentRelation[] ParentRelations = [.. EducationParentRelations, .. IdentityParentRelations]; + private sealed record PatternRoot(Type Root, Type Satellite, string Table, string SatelliteTable, string ParentId, string[] Columns); // The current Education spec owns these exact satellite shapes. Pattern A @@ -44,16 +53,14 @@ private sealed record PatternRoot(Type Root, Type Satellite, string Table, strin StaticTenantContextAccessor.Unresolved); private static async Task> ParentGuardOffendersAsync( - DbConnection connection, DbTransaction? transaction = null, ParentRelation[]? declarations = null) + DbConnection connection, DbTransaction? transaction = null, ParentRelation[]? declarations = null, + List? modelRelations = null) { declarations ??= ParentRelations; var offenders = new List(); using var context = ModelOnly(); - var modelRelations = context.Model.GetEntityTypes() - .Where(entity => typeof(IOrganizationScoped).IsAssignableFrom(entity.ClrType)) - .SelectMany(entity => entity.GetForeignKeys()) - .Where(key => typeof(IOrganizationScoped).IsAssignableFrom(key.PrincipalEntityType.ClrType)) - .ToList(); + using var identity = IdentityModelOnly(); + modelRelations ??= ParentModelRelations(context.Model, identity.Model); if (declarations.Length == 0 || modelRelations.Count == 0) { @@ -70,7 +77,8 @@ private static async Task> ParentGuardOffendersAsync( offenders.Add($"{child}: undeclared model relation"); } else if (!Columns(key.Properties).SequenceEqual(["tenant_id", declaration.ParentId]) - || !Columns(key.PrincipalKey.Properties).SequenceEqual(["tenant_id", "id"])) + || !Columns(key.PrincipalKey.Properties).SequenceEqual(["tenant_id", "id"]) + || (IdentityParentRelations.Contains(declaration) && key.DeleteBehavior != DeleteBehavior.Restrict)) { offenders.Add($"{child}: model tenant-composite FK"); } @@ -91,7 +99,7 @@ private static async Task> ParentGuardOffendersAsync( AND t.tgenabled IN ('O', 'A') AND t.tgqual IS NULL AND t.tgnargs = 0 AND cardinality(t.tgattr::smallint[]) = 0)::text, - f.proname, t.tgtype::text, t.tgdeferrable::text, t.tginitdeferred::text + f.proname, t.tgtype::text, t.tgdeferrable::text, t.tginitdeferred::text, f.provolatile::text FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid JOIN pg_proc f ON f.oid = t.tgfoid JOIN pg_namespace n ON n.oid = f.pronamespace @@ -112,14 +120,20 @@ WHERE c.oid IN ({SchemaQueries.TableOids}) AND NOT t.tgisinternal { offenders.Add($"{relation.Child}: missing parent FK"); } - else if (!ValidForeignKey(keys[0], relation)) + else if (!ValidForeignKey(keys[0], relation) + || (IdentityParentRelations.Contains(relation) && keys[0].DeleteAction != relation.DeleteAction)) { offenders.Add($"{relation.Child}: tenant-composite FK"); } + var identityRelation = IdentityParentRelations.Contains(relation); 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))) + && trigger[3] == "true" && trigger[5] == (identityRelation ? "31" : "23") + && trigger[6] == "false" && trigger[7] == "false" + && (identityRelation + ? trigger[4] == "fn_identity_contextual_mutation_guard" && trigger[8] == "v" + && IsIdentityParentGuardBody(trigger[2]) + : IsParentGuardBody(trigger[2], relation)))) { offenders.Add($"{relation.Child}: parent guard"); } @@ -129,6 +143,18 @@ WHERE c.oid IN ({SchemaQueries.TableOids}) AND NOT t.tgisinternal return offenders.Distinct(StringComparer.Ordinal).Order(StringComparer.Ordinal).ToList(); } + private static IdentityDbContext IdentityModelOnly() => new( + new DbContextOptionsBuilder() + .UseNpgsql("Host=model-only;Database=model-only;Username=model-only").Options, + StaticTenantContextAccessor.Unresolved, EmptyIdentityScope.Instance); + + private static List ParentModelRelations(params IModel[] models) => models + .SelectMany(model => model.GetEntityTypes()) + .Where(entity => typeof(IOrganizationScoped).IsAssignableFrom(entity.ClrType)) + .SelectMany(entity => entity.GetForeignKeys()) + .Where(key => typeof(IOrganizationScoped).IsAssignableFrom(key.PrincipalEntityType.ClrType)) + .ToList(); + /// /// A deliberately bounded grammar for Standards 05's canonical function, not /// a general PL/pgSQL verifier. Whole-body matching rejects early returns, @@ -270,7 +296,7 @@ WHERE c.oid IN ({SchemaQueries.TableOids}) } } - foreach (var relation in ParentRelations) + foreach (var relation in EducationParentRelations) { if (!foreignKeys.Any(key => key.Child == relation.Child && key.Parent == relation.Parent && ValidForeignKey(key, relation) && key.DeleteAction == relation.DeleteAction)) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.IdentityGuard.cs b/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.IdentityGuard.cs new file mode 100644 index 000000000..736b69f53 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.IdentityGuard.cs @@ -0,0 +1,96 @@ +namespace LearnStack.Tests.Integration.Database; + +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. + 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; + 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 + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; + END IF; + IF TG_TABLE_NAME = 'memberships' THEN + IF TG_OP = 'DELETE' OR (TG_OP = 'INSERT' AND (NEW.status <> 'Active' OR NEW.deleted_at IS NOT NULL OR NEW.deleted_by IS NOT NULL)) THEN + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; + END IF; + IF TG_OP = 'UPDATE' AND (NEW.id IS DISTINCT FROM OLD.id OR NEW.user_id IS DISTINCT FROM OLD.user_id + OR OLD.status = 'Revoked' OR NEW.status NOT IN ('Active','Suspended','Revoked')) THEN + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; + END IF; + IF TG_OP = 'INSERT' THEN + require_exclusive := NOT EXISTS (SELECT 1 FROM public.memberships WHERE tenant_id = target_tenant); + ELSIF NEW.status IS DISTINCT FROM OLD.status OR NEW.deleted_at IS DISTINCT FROM OLD.deleted_at THEN + SELECT EXISTS (SELECT 1 FROM public.membership_role_assignments AS assignment + JOIN public.roles AS role ON role.tenant_id = assignment.tenant_id AND role.id = assignment.role_id + WHERE assignment.tenant_id = target_tenant AND assignment.membership_id = OLD.id + AND OLD.organization_id IS NULL AND role.built_in_key = 'TenantAdmin' AND role.permission_scope = 'Tenant') INTO require_exclusive; + END IF; + ELSIF TG_TABLE_NAME IN ('membership_profiles','membership_role_assignments') THEN + target_member := CASE WHEN TG_OP = 'DELETE' THEN OLD.membership_id ELSE NEW.membership_id END; + 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 + 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 + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; + END IF; + 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 + IF TG_OP = 'UPDATE' THEN RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; END IF; + target_role := CASE WHEN TG_OP = 'DELETE' THEN OLD.role_id ELSE NEW.role_id END; + SELECT role.permission_scope, role.built_in_key INTO role_scope, role_key FROM public.roles AS role + WHERE role.tenant_id = target_tenant AND role.id = target_role FOR KEY SHARE; + IF NOT FOUND OR (parent_org IS NULL AND role_scope <> 'Tenant') OR (parent_org IS NOT NULL AND role_scope <> 'Organization') THEN + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; + END IF; + require_exclusive := parent_org IS NULL AND role_key = 'TenantAdmin'; + END IF; + ELSIF TG_TABLE_NAME IN ('roles','role_permission_grants') THEN + IF NULLIF(current_setting('app.organization_id',true),'') IS NOT NULL THEN + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; + END IF; + SELECT EXISTS (SELECT 1 FROM public.memberships WHERE tenant_id = target_tenant) INTO has_history; + IF TG_TABLE_NAME = 'roles' THEN + IF TG_OP = 'DELETE' OR (TG_OP = 'UPDATE' AND (NEW.id IS DISTINCT FROM OLD.id + OR NEW.built_in_key IS DISTINCT FROM OLD.built_in_key OR NEW.permission_scope IS DISTINCT FROM OLD.permission_scope)) THEN + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; + END IF; + IF NOT has_history AND TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; + END IF; + require_exclusive := has_history AND NEW.built_in_key = 'TenantAdmin'; + ELSE + IF TG_OP = 'UPDATE' THEN RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; END IF; + target_role := CASE WHEN TG_OP = 'DELETE' THEN OLD.role_id ELSE NEW.role_id END; + SELECT role.permission_scope, role.built_in_key, role.xmin = pg_current_xact_id()::text::xid + INTO role_scope, role_key, parent_fresh FROM public.roles AS role + WHERE role.tenant_id = target_tenant AND role.id = target_role FOR KEY SHARE; + IF NOT FOUND OR role_scope IS DISTINCT FROM (CASE WHEN TG_OP = 'DELETE' THEN OLD.permission_scope ELSE NEW.permission_scope END) + OR (NOT has_history AND (TG_OP <> 'INSERT' OR NOT parent_fresh)) + OR (TG_OP = 'INSERT' AND NEW.permission_key = 'identity.role.admin' AND role_key <> 'TenantAdmin') THEN + RAISE EXCEPTION 'identity graph is invalid' USING ERRCODE = 'P0304'; + END IF; + require_exclusive := has_history AND role_key = 'TenantAdmin'; + END IF; + ELSE + RAISE EXCEPTION 'identity mutation plan is unavailable' USING ERRCODE = 'P0301'; + END IF; + PERFORM public.fn_identity_assert_tenant_fence(target_tenant,require_exclusive); + IF TG_OP = 'DELETE' THEN RETURN OLD; END IF; + RETURN NEW; + END; + """; +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.IdentityRelations.cs b/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.IdentityRelations.cs new file mode 100644 index 000000000..eb0c7e79d --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/EducationStructureTests.IdentityRelations.cs @@ -0,0 +1,151 @@ +using FluentAssertions; +using Microsoft.EntityFrameworkCore; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class EducationStructureTests +{ + [Theory] + [InlineData("membership_profiles")] + [InlineData("membership_role_assignments")] + public async Task The_Identity_Parent_Guard_Requires_Both_Model_And_Applied_Relations(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 relation = IdentityParentRelations.Single(item => item.Child == table); + var key = (await ReadForeignKeysAsync(owner, transaction)) + .Single(item => item.Child == table && item.Parent == relation.Parent); + await SchemaQueries.ExecuteAsync(owner, transaction, $"ALTER TABLE {table} DROP CONSTRAINT {key.Name}"); + (await ParentGuardOffendersAsync(owner, transaction)).Should() + .ContainSingle().Which.Should().Be($"{table}: missing parent FK"); + await SchemaQueries.ExecuteAsync(owner, transaction, + $"ALTER TABLE {table} ADD CONSTRAINT {key.Name} {key.Definition}"); + (await ParentGuardOffendersAsync(owner, transaction)).Should().BeEmpty(); + + foreach (var definition in new[] + { + "FOREIGN KEY (membership_id) REFERENCES memberships(id) ON DELETE RESTRICT", + key.Definition.Replace("ON DELETE RESTRICT", "ON DELETE CASCADE", StringComparison.Ordinal), + key.Definition + " DEFERRABLE INITIALLY IMMEDIATE", + key.Definition + " NOT VALID", + }) + { + definition.Should().NotBe(key.Definition); + await SchemaQueries.ExecuteAsync(owner, transaction, + $"ALTER TABLE {table} DROP CONSTRAINT {key.Name}; " + + $"ALTER TABLE {table} ADD CONSTRAINT {key.Name} {definition}"); + (await ParentGuardOffendersAsync(owner, transaction)).Should() + .ContainSingle().Which.Should().Be($"{table}: tenant-composite FK"); + await SchemaQueries.ExecuteAsync(owner, transaction, + $"ALTER TABLE {table} DROP CONSTRAINT {key.Name}; " + + $"ALTER TABLE {table} ADD CONSTRAINT {key.Name} {key.Definition}"); + (await ParentGuardOffendersAsync(owner, transaction)).Should().BeEmpty(); + } + + (await ParentGuardOffendersAsync(owner, transaction, + ParentRelations.Where(item => item.Child != table).ToArray())).Should().BeEquivalentTo( + $"{table}: undeclared model relation", $"{table}: undeclared applied relation"); + (await ParentGuardOffendersAsync(owner, transaction)).Should().BeEmpty(); + + using var education = ModelOnly(); + using var identity = IdentityModelOnly(); + var models = ParentModelRelations(education.Model, identity.Model); + models.Count(item => item.DeclaringEntityType.GetTableName() == table).Should().Be(1); + (await ParentGuardOffendersAsync(owner, transaction, + modelRelations: models.Where(item => item.DeclaringEntityType.GetTableName() != table).ToList())) + .Should().ContainSingle().Which.Should().Be($"{table}: missing model relation"); + (await ParentGuardOffendersAsync(owner, transaction)).Should().BeEmpty(); + } + + [Theory] + [InlineData("membership_profiles", "missing")] + [InlineData("membership_profiles", "disabled")] + [InlineData("membership_profiles", "after")] + [InlineData("membership_role_assignments", "missing")] + [InlineData("membership_role_assignments", "disabled")] + [InlineData("membership_role_assignments", "after")] + public async Task The_Identity_Parent_Guard_Rejects_Inert_Trigger_Metadata(string table, string defect) + { + await using var owner = await PostgresFixture.OpenAsync(_schema.Postgres.MigrationConnectionString); + await using var transaction = await owner.BeginTransactionAsync(); + (await ParentGuardOffendersAsync(owner, transaction)).Should().BeEmpty(); + var name = $"tg_{table}_mutation_guard"; + var original = await DefinitionAsync(owner, transaction, + $"SELECT pg_get_triggerdef(oid) FROM pg_trigger WHERE tgname = '{name}'"); + await SchemaQueries.ExecuteAsync(owner, transaction, $"DROP TRIGGER {name} ON {table}"); + if (defect != "missing") + { + var timing = defect == "after" ? "AFTER" : "BEFORE"; + await SchemaQueries.ExecuteAsync(owner, transaction, + $"CREATE TRIGGER {name} {timing} INSERT OR UPDATE OR DELETE ON {table} " + + "FOR EACH ROW EXECUTE FUNCTION public.fn_identity_contextual_mutation_guard()"); + if (defect == "disabled") + await SchemaQueries.ExecuteAsync(owner, transaction, $"ALTER TABLE {table} DISABLE TRIGGER {name}"); + } + (await ParentGuardOffendersAsync(owner, transaction)).Should() + .ContainSingle().Which.Should().Be($"{table}: parent guard"); + await SchemaQueries.ExecuteAsync(owner, transaction, $"DROP TRIGGER IF EXISTS {name} ON {table}; " + original); + (await ParentGuardOffendersAsync(owner, transaction)).Should().BeEmpty(); + } + + [Theory] + [InlineData("security-definer")] + [InlineData("search-path")] + [InlineData("stable")] + [InlineData("unqualified-parent")] + [InlineData("no-lock")] + [InlineData("lifecycle-key-share")] + [InlineData("wrong-tenant")] + [InlineData("wrong-parent")] + [InlineData("nullable-compare")] + [InlineData("missing-parent-accepted")] + [InlineData("wrong-sqlstate")] + [InlineData("wrong-constraint")] + [InlineData("missing-constraint")] + [InlineData("wrong-branch")] + [InlineData("early-return")] + public async Task The_Identity_Parent_Guard_Rejects_A_Weakened_Applied_Function(string defect) + { + await using var owner = await PostgresFixture.OpenAsync(_schema.Postgres.MigrationConnectionString); + await using var transaction = await owner.BeginTransactionAsync(); + (await ParentGuardOffendersAsync(owner, transaction)).Should().BeEmpty(); + var original = await DefinitionAsync(owner, transaction, + "SELECT pg_get_functiondef('public.fn_identity_contextual_mutation_guard()'::regprocedure)"); + var body = await DefinitionAsync(owner, transaction, + "SELECT prosrc FROM pg_proc WHERE oid = 'public.fn_identity_contextual_mutation_guard()'::regprocedure"); + var mutated = defect switch + { + "unqualified-parent" => body.Replace("public.memberships AS member", "memberships AS member", StringComparison.Ordinal), + "no-lock" => body.Replace("FOR NO KEY UPDATE", "", StringComparison.Ordinal) + .Replace("FOR KEY SHARE", "", StringComparison.Ordinal), + "lifecycle-key-share" => body.Replace("target_member FOR NO KEY UPDATE;", + "target_member FOR KEY SHARE;", StringComparison.Ordinal), + "wrong-tenant" => body.Replace("member.tenant_id = target_tenant", "member.tenant_id = member.tenant_id", StringComparison.Ordinal), + "wrong-parent" => body.Replace("member.id = target_member", "member.id = member.id", StringComparison.Ordinal), + "nullable-compare" => body.Replace("parent_org IS DISTINCT FROM", "parent_org <>", StringComparison.Ordinal), + "missing-parent-accepted" => body.Replace("NOT FOUND OR parent_org", "parent_org", StringComparison.Ordinal), + "wrong-sqlstate" => body.Replace("ERRCODE = '23514'", "ERRCODE = 'P0304'", StringComparison.Ordinal), + "wrong-constraint" => body.Replace("CONSTRAINT = 'membership_parent_scope'", "CONSTRAINT = 'unclassified_parent_scope'", StringComparison.Ordinal), + "missing-constraint" => body.Replace(", CONSTRAINT = 'membership_parent_scope'", "", StringComparison.Ordinal), + "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), + _ => body, + }; + if (defect is not ("security-definer" or "search-path" or "stable")) + mutated.Should().NotBe(body, "the planted violation must change the applied function"); + var security = defect == "security-definer" ? "DEFINER" : "INVOKER"; + var path = defect == "search-path" ? "public, pg_catalog" : "pg_catalog"; + var volatility = defect == "stable" ? "STABLE" : "VOLATILE"; + await SchemaQueries.ExecuteAsync(owner, transaction, + "CREATE OR REPLACE FUNCTION public.fn_identity_contextual_mutation_guard() RETURNS trigger " + + $"LANGUAGE plpgsql {volatility} SECURITY {security} SET search_path = {path} AS $probe${mutated}$probe$"); + (await ParentGuardOffendersAsync(owner, transaction)).Should().BeEquivalentTo( + "membership_profiles: parent guard", "membership_role_assignments: parent guard"); + await SchemaQueries.ExecuteAsync(owner, transaction, original); + (await ParentGuardOffendersAsync(owner, transaction)).Should().BeEmpty(); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityAuthorityToolTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityAuthorityToolTests.cs new file mode 100644 index 000000000..bab8d5850 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityAuthorityToolTests.cs @@ -0,0 +1,81 @@ +using System.Diagnostics; +using System.Reflection; +using FluentAssertions; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed class GlobalIdentityAuthorityToolTests(SchemaFixture schema) +{ + private const string Authority = "019a1929-5450-7bbb-8df1-516e8e002501"; + private const string Issuer = "https://installer-proof.invalid/realms/learnstack"; + + [Fact] + public async Task Deployment_child_installs_once_verifies_repeat_and_refuses_rebind_or_app_credentials_without_values() + { + await using var database = await DisposableSchemaDatabase.CreateAsync(schema.Postgres); + (await RunAsync(database.MigrationConnectionString, Issuer)).Code.Should().Be(0); + (await RunAsync(database.MigrationConnectionString, Issuer)).Code.Should().Be(0); + var mismatch = await RunAsync(database.MigrationConnectionString, + "https://private-issuer-canary.invalid/realms/learnstack"); + mismatch.Code.Should().Be(2); + mismatch.Text.Should().NotContain("private-issuer-canary"); + var app = await RunAsync(database.AppConnectionString, Issuer); + app.Code.Should().Be(2); + foreach (var result in new[] { mismatch, app }) + { + result.Text.Should().NotContain(database.MigrationConnectionString).And.NotContain(database.AppConnectionString); + result.Text.Should().NotContain(Authority).And.NotContain(Issuer); + result.Text.Length.Should().BeLessThan(1024); + } + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString); + await using var read = new NpgsqlCommand("SELECT authority_id::text, issuer FROM public.identity_authority WHERE id = 1", connection); + await using var reader = await read.ExecuteReaderAsync(); + (await reader.ReadAsync()).Should().BeTrue(); + reader.GetString(0).Should().Be(Authority); + reader.GetString(1).Should().Be(Issuer); + (await reader.ReadAsync()).Should().BeFalse(); + } + + private static async Task<(int Code, string Text)> RunAsync(string connection, string issuer) + { + var start = new ProcessStartInfo("dotnet") + { + WorkingDirectory = AppContext.BaseDirectory, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + }; + start.ArgumentList.Add("exec"); + start.ArgumentList.Add("--runtimeconfig"); + start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "LearnStack.Tests.Integration.runtimeconfig.json")); + start.ArgumentList.Add("--depsfile"); + start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "LearnStack.Tests.Integration.deps.json")); + start.ArgumentList.Add(Assembly.Load("LearnStack.Tools.IdentityAuthorityInstaller").Location); + start.Environment.Clear(); + foreach (var key in new[] { "PATH", "SystemRoot", "DOTNET_ROOT", "HOME" }) + if (Environment.GetEnvironmentVariable(key) is { } value) start.Environment[key] = value; + start.Environment["DOTNET_CLI_TELEMETRY_OPTOUT"] = "1"; + start.Environment["ConnectionStrings__Migration"] = connection; + start.Environment["Identity__AuthorityId"] = Authority; + start.Environment["Authentication__Tenant__Issuer"] = issuer; + using var child = new Process { StartInfo = start }; + child.Start().Should().BeTrue(); + var output = child.StandardOutput.ReadToEndAsync(); + var errors = child.StandardError.ReadToEndAsync(); + using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(45)); + try { await child.WaitForExitAsync(deadline.Token); } + finally + { + if (!child.HasExited) + { + child.Kill(entireProcessTree: true); + await child.WaitForExitAsync(CancellationToken.None); + } + } + return (child.ExitCode, await output + await errors); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.Deadline.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.Deadline.cs new file mode 100644 index 000000000..08156bd40 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.Deadline.cs @@ -0,0 +1,111 @@ +using System.Diagnostics; +using FluentAssertions; +using LearnStack.Modules.Identity.Application.Contracts.Bindings; +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Persistence; +using Microsoft.Extensions.DependencyInjection; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class GlobalIdentityBootstrapTests +{ + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task A_stalled_global_audit_INSERT_honors_its_deadline_or_caller_cancellation_and_reconciles(bool cancelCaller) + { + await ExecuteDeploymentAsync(""" + CREATE FUNCTION public.proof_stall_global_success() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + IF NEW.operation = 'identity.user.create' AND NEW.outcome = 'success' THEN + PERFORM pg_sleep(30); + END IF; + RETURN NEW; + END $$; + CREATE TRIGGER proof_stall_global_success BEFORE INSERT ON public.audit_log + FOR EACH ROW EXECUTE FUNCTION public.proof_stall_global_success(); + """); + var appConnection = new NpgsqlConnectionStringBuilder(_database.AppConnectionString) + { CommandTimeout = 0, CancellationTimeout = 1000 }.ConnectionString; + await using var provider = BuildProvider(appConnection, Registration, new FixtureAdmission(Subject, Actor)); + await QualifyAsync(provider); + using var watchdog = new CancellationTokenSource(TimeSpan.FromSeconds(25)); + using var caller = CancellationTokenSource.CreateLinkedTokenSource(watchdog.Token); + await using var scope = provider.CreateAsyncScope(); + var services = scope.ServiceProvider; + var unit = services.GetRequiredService(); + using (var inherited = unit.Connection.CreateCommand()) + inherited.CommandTimeout.Should().Be(0, "the physical application connection has an unlimited default"); + await SchemaQueries.AssertApplicationRoleAsync(unit.Connection); + var running = services.GetRequiredService().AdoptAsync(Subject, Actor, caller.Token); + try + { + await WaitForGlobalAuditSleepAsync(appConnection, running); + if (cancelCaller) + { + await caller.CancelAsync(); + await FluentActions.Awaiting(() => running).Should().ThrowAsync(); + } + else + { + var result = await running; + result.Outcome.Should().Be(IdentityBindingOutcome.StorageUnavailable, + "an INSERT deadline before COMMIT is a known failure, not an indeterminate commit"); + result.Actor.Should().BeNull(); + caller.IsCancellationRequested.Should().BeFalse(); + } + watchdog.IsCancellationRequested.Should().BeFalse("the independent watchdog did not terminate the stalled INSERT"); + unit.HasActiveTransaction.Should().BeFalse(); + unit.IsRollbackOnly.Should().BeTrue(); + services.GetRequiredService().Intents.Should().BeEmpty(); + provider.GetRequiredService().IsHealthy.Should().BeTrue( + "failed-attempt reconciliation retains its own budget after the caller has stopped"); + (await CountsAsync()).Should().Be((0L, 1L)); + (await AuditRowsAsync()).Should().ContainSingle().Which.Outcome.Should().Be("failed"); + } + finally + { + await caller.CancelAsync(); + try { await running; } + catch (Exception) when (running.IsCompleted) + { + // Join the real owner; its primary failure or cancellation was + // already asserted, and cleanup must not replace that assertion. + } + await ExecuteDeploymentAsync(""" + DROP TRIGGER proof_stall_global_success ON public.audit_log; + DROP FUNCTION public.proof_stall_global_success(); + """); + } + + (await AdoptAsync(provider, Subject, Actor)).Outcome.Should().Be(IdentityBindingOutcome.Created, + "a clean new owner succeeds once the stalled INSERT trigger is removed"); + (await CountsAsync()).Should().Be((1L, 2L)); + (await AuditRowsAsync()).Should().ContainSingle(row => row.Outcome == "success"); + } + + private static async Task WaitForGlobalAuditSleepAsync(string connectionString, Task running) + { + await using var connection = await OpenConnectionAsync(connectionString); + var elapsed = Stopwatch.StartNew(); + while (elapsed.Elapsed < TimeSpan.FromSeconds(5)) + { + if (running.IsCompleted) + { + await running; + throw new InvalidOperationException("The identity owner completed before its audit INSERT was observed sleeping."); + } + await using var command = new NpgsqlCommand(""" + SELECT EXISTS (SELECT 1 FROM pg_stat_activity + WHERE datname = current_database() AND usename = 'learnstack_app' + AND wait_event = 'PgSleep' AND query LIKE '%INSERT INTO audit_log%') + """, connection) { CommandTimeout = 1 }; + if (await command.ExecuteScalarAsync() is true) return; + await Task.Delay(TimeSpan.FromMilliseconds(25)); + } + throw new TimeoutException("The real global audit INSERT did not reach its test-owned PostgreSQL sleep."); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.Evidence.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.Evidence.cs new file mode 100644 index 000000000..ecebe62cc --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.Evidence.cs @@ -0,0 +1,222 @@ +using System.Data; +using System.Data.Common; +using FluentAssertions; +using LearnStack.Infrastructure.Audit; +using LearnStack.Modules.Identity.Application.Abstractions; +using LearnStack.Modules.Identity.Application.Contracts.Bindings; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Persistence; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.EntityFrameworkCore; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class GlobalIdentityBootstrapTests +{ + [Fact] + public async Task Original_success_evidence_requires_the_complete_captured_key_scope_source_target_and_outcome() + { + var observed = new EvidenceObservation(); + await using var provider = BuildProvider(_database.AppConnectionString, Registration, + new FixtureAdmission(Subject, Actor), services => DecorateEvidence(services, observed)); + await QualifyAsync(provider); + (await AdoptAsync(provider, Subject, Actor)).Outcome.Should().Be(IdentityBindingOutcome.Created); + observed.Creation.Should().NotBeNull(); + var creation = observed.Creation!; + (await EvidenceAsync(creation, creation.Timestamp, "success")).Should().BeTrue(); + foreach (var mismatch in new[] { "id", "timestamp", "authority", "subject", "target", "source", "outcome", "announcement" }) + (await EvidenceAsync(creation, creation.Timestamp, "success", mismatch)).Should().BeFalse(mismatch); + (await CountsAsync()).Should().Be((1L, 1L)); + } + + [Fact] + public async Task Duplicate_non_success_is_proved_on_a_clean_transaction_without_a_User_witness() + { + await RequireReadOnlyEvidenceAsync(); + var observed = new EvidenceObservation { RefusePending = true, RepeatReconciliation = true }; + await using var provider = BuildProvider(_database.AppConnectionString, Registration, + new FixtureAdmission(Subject, Actor), services => DecorateEvidence(services, observed)); + await QualifyAsync(provider); + (await AdoptAsync(provider, Subject, Actor)).Outcome.Should().Be(IdentityBindingOutcome.StorageUnavailable); + observed.ReconciliationCalls.Should().Be(2); + observed.Creation.Should().NotBeNull(); + var creation = observed.Creation!; + (await CountsAsync()).Should().Be((0L, 1L)); + provider.GetRequiredService().IsHealthy.Should().BeTrue(); + var writableEvidence = await FluentActions.Awaiting(() => + EvidenceAsync(creation, observed.ReconciliationTimestamp, "failed", readOnly: false)) + .Should().ThrowAsync(); + writableEvidence.Which.SqlState.Should().Be(PostgresErrorCodes.ReadOnlySqlTransaction); + (await EvidenceAsync(creation, observed.ReconciliationTimestamp, "failed")).Should().BeTrue(); + (await EvidenceAsync(creation, creation.Timestamp, "success")).Should().BeFalse(); + (await EvidenceAsync(creation, observed.ReconciliationTimestamp, "success")).Should().BeFalse(); + foreach (var mismatch in new[] { "timestamp", "subject", "target", "source", "outcome", "announcement" }) + (await EvidenceAsync(creation, observed.ReconciliationTimestamp, "failed", mismatch)).Should().BeFalse(mismatch); + await using var clean = BuildProvider(_database.AppConnectionString, Registration, new FixtureAdmission(Subject, Actor)); + await QualifyAsync(clean); + (await AdoptAsync(clean, Subject, Actor)).Outcome.Should().Be(IdentityBindingOutcome.Created); + (await CountsAsync()).Should().Be((1L, 2L)); + (await EvidenceAsync(creation, observed.ReconciliationTimestamp, "failed")).Should().BeTrue( + "failed-row evidence remains valid when a User exists and therefore cannot establish User absence"); + } + + [Fact] + public async Task Unavailable_duplicate_evidence_keeps_the_original_failure_and_marks_audit_health_unhealthy() + { + await using (var connection = await PostgresFixture.OpenAsync(_database.MigrationConnectionString)) + await using (var command = new NpgsqlCommand(""" + REVOKE EXECUTE ON FUNCTION public.fn_identity_audit_evidence(uuid,timestamptz,uuid,bytea,uuid,text,text) FROM learnstack_app + """, (NpgsqlConnection)connection)) + await command.ExecuteNonQueryAsync(); + var observed = new EvidenceObservation { RefusePending = true, RepeatReconciliation = true }; + await using var provider = BuildProvider(_database.AppConnectionString, Registration, + new FixtureAdmission(Subject, Actor), services => DecorateEvidence(services, observed)); + await QualifyAsync(provider); + (await AdoptAsync(provider, Subject, Actor)).Outcome.Should().Be(IdentityBindingOutcome.StorageUnavailable); + provider.GetRequiredService().IsHealthy.Should().BeFalse(); + provider.GetRequiredService().FailingOperation.Should().Be(GlobalIdentityCreationReference.Operation); + (await CountsAsync()).Should().Be((0L, 1L)); + } + + [Fact] + public async Task Reenlisted_context_is_refused_before_snapshot_capture_and_a_fresh_owner_remains_usable() + { + await using (var provider = BuildProvider(_database.AppConnectionString, Registration, + new FixtureAdmission(Subject, Actor), services => services.Replace(ServiceDescriptor.Scoped(scope => + { + var context = scope.GetRequiredService(); + return new DetachedIdentityStore(new UserBindingStore(context, + scope.GetRequiredService()), context); + })))) + { + await QualifyAsync(provider); + await FluentActions.Awaiting(() => AdoptAsync(provider, Subject, Actor)) + .Should().ThrowAsync() + .WithMessage("Global identity capture requires its original physical transaction and connection."); + } + (await CountsAsync()).Should().Be((0L, 1L)); + (await AuditRowsAsync()).Should().ContainSingle().Which.Snapshots.Should().BeEmpty(); + await using var clean = BuildProvider(_database.AppConnectionString, Registration, new FixtureAdmission(Subject, Actor)); + await QualifyAsync(clean); + (await AdoptAsync(clean, Subject, Actor)).Outcome.Should().Be(IdentityBindingOutcome.Created); + (await CountsAsync()).Should().Be((1L, 2L)); + } + + private static void DecorateEvidence(IServiceCollection services, EvidenceObservation observed) => + services.Replace(ServiceDescriptor.Scoped(provider => + new EvidenceAuditStore(ActivatorUtilities.CreateInstance(provider), observed))); + + private async Task RequireReadOnlyEvidenceAsync() + { + // Instrument only this test's isolated database, retaining the actual function and grants. + await using var connection = await OpenConnectionAsync(_database.MigrationConnectionString); + await using var command = new NpgsqlCommand(""" + SELECT pg_get_functiondef('public.fn_identity_audit_evidence(uuid,timestamptz,uuid,bytea,uuid,text,text)'::regprocedure) + """, connection); + var definition = (string)(await command.ExecuteScalarAsync())!; + var bodyStart = definition.IndexOf("BEGIN", StringComparison.Ordinal); + bodyStart.Should().BeGreaterThan(0); + command.CommandText = definition.Insert(bodyStart + "BEGIN".Length, """ + + IF current_setting('transaction_read_only') <> 'on' THEN + RAISE EXCEPTION 'Evidence requires a physically read-only transaction.' USING ERRCODE='25006'; + END IF; + + """); + await command.ExecuteNonQueryAsync(); + } + + private async Task EvidenceAsync(GlobalIdentityCreationReference creation, + DateTimeOffset timestamp, string outcome, string? mismatch = null, bool readOnly = true) + { + await using var connection = await PostgresFixture.OpenAsync(_database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(connection); + await using var transaction = await connection.BeginTransactionAsync(IsolationLevel.ReadCommitted); + await using var setup = new NpgsqlCommand(readOnly ? "SET TRANSACTION READ ONLY" : "SET TRANSACTION READ WRITE", + (NpgsqlConnection)connection, (NpgsqlTransaction)transaction); + await setup.ExecuteNonQueryAsync(); + setup.CommandText = """ + SELECT set_config('app.identity_authority_id',@authority,true), + set_config('app.identity_subject_key',@subject,true) + """; + setup.Parameters.AddWithValue("authority", creation.AuthorityId.Value.ToString("D")); + setup.Parameters.AddWithValue("subject", mismatch == "announcement" + ? IdentitySubjectKey.Compute(creation.AuthorityId, "different-announced-subject").Hex : creation.SubjectKey.Hex); + await setup.ExecuteNonQueryAsync(); + await using var command = new NpgsqlCommand(""" + SELECT public.fn_identity_audit_evidence(@id,@timestamp,@authority,@subject,@target,@source,@outcome) + """, (NpgsqlConnection)connection, (NpgsqlTransaction)transaction); + command.Parameters.AddWithValue("id", mismatch == "id" ? Guid.CreateVersion7() : creation.AuditId.Value); + command.Parameters.AddWithValue("timestamp", mismatch == "timestamp" ? timestamp.AddTicks(10) : timestamp); + command.Parameters.AddWithValue("authority", mismatch == "authority" ? Guid.CreateVersion7() : creation.AuthorityId.Value); + command.Parameters.AddWithValue("subject", mismatch == "subject" + ? IdentitySubjectKey.Compute(creation.AuthorityId, "different-evidence-subject").ToByteArray() : creation.SubjectKey.ToByteArray()); + command.Parameters.AddWithValue("target", mismatch == "target" ? Guid.CreateVersion7() : creation.TargetUserId.Value); + command.Parameters.AddWithValue("source", mismatch == "source" ? "identity-bootstrap" : creation.Source); + command.Parameters.AddWithValue("outcome", mismatch == "outcome" ? "indeterminate" : outcome); + var result = await command.ExecuteScalarAsync() is true; + await transaction.CommitAsync(); + return result; + } + + private sealed class EvidenceObservation + { + public GlobalIdentityCreationReference? Creation { get; set; } + public bool RefusePending { get; init; } + public bool RepeatReconciliation { get; init; } + public DateTimeOffset ReconciliationTimestamp { get; set; } + public int ReconciliationCalls { get; set; } + } + + private sealed class DetachedIdentityStore(IUserBindingStore inner, IdentityDbContext context) : IUserBindingStore + { + public Task FindExactAsync(GlobalIdentitySubject subject, CancellationToken cancellationToken = default) => + inner.FindExactAsync(subject, cancellationToken); + + public Task AddAsync(User user, CancellationToken cancellationToken = default) + { + context.Database.UseTransaction(null); + return inner.AddAsync(user, cancellationToken); + } + } + + private sealed class EvidenceAuditStore(IAuditStore inner, EvidenceObservation observed) : IAuditStore + { + public Task WriteGlobalIdentityPendingAsync(IUnitOfWork unit, GlobalIdentityCreationReference creation, + CancellationToken cancellationToken = default) + { + observed.Creation = creation; + if (observed.RefusePending) throw new AuditWriteFailedException("Deliberate central MUST refusal."); + return inner.WriteGlobalIdentityPendingAsync(unit, creation, cancellationToken); + } + + public async Task ReconcileGlobalIdentityAsync(AuditIntent intent, IReadOnlyList changes, + AuditIntentState state, DateTimeOffset timestamp, CancellationToken cancellationToken = default) + { + observed.ReconciliationTimestamp = timestamp; + observed.ReconciliationCalls++; + await inner.ReconcileGlobalIdentityAsync(intent, changes, state, timestamp, cancellationToken); + if (observed.RepeatReconciliation) + { + observed.ReconciliationCalls++; + await inner.ReconcileGlobalIdentityAsync(intent, changes, state, timestamp, cancellationToken); + } + } + + public Task WritePendingAsync(IUnitOfWork unit, CancellationToken cancellationToken = default) => inner.WritePendingAsync(unit, cancellationToken); + public Task WriteStandaloneAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => inner.WriteStandaloneAsync(entry, cancellationToken); + public Task WriteBestEffortAsync(AuditEntryDraft entry, CancellationToken cancellationToken = default) => inner.WriteBestEffortAsync(entry, cancellationToken); + public Task WritePlatformScopeAsync(AuditEntryDraft entry, DbConnection connection, DbTransaction transaction, + CancellationToken cancellationToken = default) => inner.WritePlatformScopeAsync(entry, connection, transaction, cancellationToken); + public Task WriteEventTerminalAsync(AuditEntryDraft entry, EventTerminalTransition transition, DbConnection connection, + DbTransaction transaction, CancellationToken cancellationToken = default) => inner.WriteEventTerminalAsync(entry, transition, connection, transaction, cancellationToken); + public Task WriteJobTerminalAsync(AuditEntryDraft entry, JobTerminalTransition transition, DbConnection connection, + DbTransaction transaction, CancellationToken cancellationToken = default) => inner.WriteJobTerminalAsync(entry, transition, connection, transaction, cancellationToken); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.Faults.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.Faults.cs new file mode 100644 index 000000000..f208d2a77 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.Faults.cs @@ -0,0 +1,207 @@ +using System.Diagnostics; +using FluentAssertions; +using LearnStack.Modules.Identity.Application.Abstractions; +using LearnStack.Modules.Identity.Application.Contracts.Bindings; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Persistence; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class GlobalIdentityBootstrapTests +{ + [Fact] + public async Task A_waiting_creator_reads_the_committed_winner_after_the_real_subject_lock() + { + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + await using var first = BuildProvider(_database.AppConnectionString, Registration, new FixtureAdmission(Subject, Actor), services => + services.Replace(ServiceDescriptor.Scoped(provider => + new PausingStore(new UserBindingStore(provider.GetRequiredService(), + provider.GetRequiredService()), entered, release.Task)))); + await using var second = BuildProvider(_database.AppConnectionString, Registration, new FixtureAdmission(Subject, Actor)); + await QualifyAsync(first); + await QualifyAsync(second); + var creating = AdoptAsync(first, Subject, Actor); + if (await Task.WhenAny(entered.Task, creating).WaitAsync(TimeSpan.FromSeconds(5)) == creating) + { + var early = await creating; + throw new InvalidOperationException($"The first creator exited before its locked lookup ({early.Outcome})."); + } + var waiting = AdoptAsync(second, Subject, Actor); + try + { + await WaitForSubjectWaiterAsync(waiting); + waiting.IsCompleted.Should().BeFalse("PostgreSQL reports the second physical owner waiting for the held advisory lock"); + } + finally { release.TrySetResult(); } + var outcomes = await Task.WhenAll(creating, waiting).WaitAsync(TimeSpan.FromSeconds(10)); + outcomes.Select(result => result.Outcome).Should().Equal(IdentityBindingOutcome.Created, IdentityBindingOutcome.Existing); + (await CountsAsync()).Should().Be((1L, 1L)); + } + + [Fact] + public async Task MUST_failure_rolls_back_User_and_preserves_failed_attempt_then_clean_twin_succeeds() + { + await ExecuteDeploymentAsync(""" + CREATE FUNCTION public.proof_reject_global_success() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + IF NEW.operation = 'identity.user.create' AND NEW.outcome = 'success' THEN + RAISE EXCEPTION 'fixed audit proof refusal' USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END $$; + CREATE TRIGGER proof_reject_global_success BEFORE INSERT ON public.audit_log + FOR EACH ROW EXECUTE FUNCTION public.proof_reject_global_success(); + """); + await using (var provider = BuildProvider(_database.AppConnectionString, Registration, new FixtureAdmission(Subject, Actor))) + { + await QualifyAsync(provider); + var refused = await AdoptAsync(provider, Subject, Actor); + refused.Outcome.Should().Be(IdentityBindingOutcome.StorageUnavailable); + refused.Actor.Should().BeNull(); + } + (await CountsAsync()).Should().Be((0L, 1L)); + (await AuditRowsAsync()).Should().ContainSingle(row => row.Outcome == "failed"); + await ExecuteDeploymentAsync("DROP TRIGGER proof_reject_global_success ON public.audit_log; DROP FUNCTION public.proof_reject_global_success();"); + await using var clean = BuildProvider(_database.AppConnectionString, Registration, new FixtureAdmission(Subject, Actor)); + await QualifyAsync(clean); + (await AdoptAsync(clean, Subject, Actor)).Outcome.Should().Be(IdentityBindingOutcome.Created); + (await CountsAsync()).Should().Be((1L, 2L)); + } + + [Fact] + public async Task Reciprocal_guard_failure_is_known_precommit_failure_and_not_unknown_COMMIT() + { + await using (var provider = BuildProvider(_database.AppConnectionString, Registration, new FixtureAdmission(Subject, Actor), services => + services.Replace(ServiceDescriptor.Scoped(provider => + new WrongCreationReferenceStore(new UserBindingStore(provider.GetRequiredService(), + provider.GetRequiredService())))))) + { + await QualifyAsync(provider); + (await AdoptAsync(provider, Subject, Actor)).Outcome.Should().Be(IdentityBindingOutcome.StorageUnavailable); + } + (await CountsAsync()).Should().Be((0L, 1L)); + (await AuditRowsAsync()).Should().ContainSingle(row => row.Outcome == "failed"); + await using var clean = BuildProvider(_database.AppConnectionString, Registration, new FixtureAdmission(Subject, Actor)); + await QualifyAsync(clean); + (await AdoptAsync(clean, Subject, Actor)).Outcome.Should().Be(IdentityBindingOutcome.Created); + (await CountsAsync()).Should().Be((1L, 2L)); + } + + [Fact] + public async Task EF_constraint_failure_is_translated_without_retaining_the_provider_exception() + { + await using (var first = BuildProvider(_database.AppConnectionString, Registration, new FixtureAdmission(Subject, Actor))) + { + await QualifyAsync(first); + (await AdoptAsync(first, Subject, Actor)).Outcome.Should().Be(IdentityBindingOutcome.Created); + } + var colliding = new GlobalIdentitySubject(Subject.AuthorityId, Subject.Issuer, "different-subject-same-reserved-actor"); + UserBindingStorageException? observed = null; + await using var provider = BuildProvider(_database.AppConnectionString, Registration, new FixtureAdmission(colliding, Actor), services => + services.Replace(ServiceDescriptor.Scoped(serviceProvider => + new ObservingFailureStore(new UserBindingStore(serviceProvider.GetRequiredService(), + serviceProvider.GetRequiredService()), + failure => observed = failure)))); + await QualifyAsync(provider); + (await AdoptAsync(provider, colliding, Actor)).Outcome.Should().Be(IdentityBindingOutcome.StorageUnavailable); + observed.Should().NotBeNull("the real EF duplicate actor failure must cross the bounded adapter boundary"); + observed!.InnerException.Should().BeNull(); + observed.Message.Should().Be("Identity binding storage is unavailable."); + (await CountsAsync()).Should().Be((1L, 1L)); + (await CountsAsync(colliding)).Should().Be((0L, 1L)); + (await AuditRowsAsync(colliding)).Should().ContainSingle(row => row.Outcome == "failed"); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Real_lost_ack_and_unsent_COMMIT_remain_uncertain_without_asserting_a_User_outcome(bool dropRequest) + { + await using var proxy = new CommitResponseDroppingProxy(_database.AppConnectionString, + commitsToPass: 1, dropCommitRequest: dropRequest); + await using (var provider = BuildProvider(proxy.ConnectionString, Registration, new FixtureAdmission(Subject, Actor))) + { + await QualifyAsync(provider); // The proxy passes this separate read-only qualification COMMIT. + var result = await AdoptAsync(provider, Subject, Actor).WaitAsync(TimeSpan.FromSeconds(15)); + result.Outcome.Should().Be(IdentityBindingOutcome.Indeterminate); + result.Actor.Should().BeNull(); + } + if (dropRequest) proxy.DroppedCommitRequests.Should().Be(1); + else proxy.DroppedCommitResponses.Should().Be(1); + (await CountsAsync()).Should().Be(dropRequest ? (0L, 1L) : (1L, 2L)); + (await AuditRowsAsync()).Should().ContainSingle(row => row.Outcome == "indeterminate"); + await using var clean = BuildProvider(_database.AppConnectionString, Registration, new FixtureAdmission(Subject, Actor)); + await QualifyAsync(clean); + (await AdoptAsync(clean, Subject, Actor)).Outcome.Should().Be( + dropRequest ? IdentityBindingOutcome.Created : IdentityBindingOutcome.Existing); + (await CountsAsync()).Should().Be((1L, 2L)); + } + + private async Task ExecuteDeploymentAsync(string sql) + { + await using var connection = await OpenConnectionAsync(_database.MigrationConnectionString); + await using var command = new NpgsqlCommand(sql, connection); + await command.ExecuteNonQueryAsync(); + } + + private async Task WaitForSubjectWaiterAsync(Task waiting) + { + var deadline = Stopwatch.StartNew(); + await using var connection = await OpenConnectionAsync(_database.MigrationConnectionString); + while (deadline.Elapsed < TimeSpan.FromSeconds(1.5)) + { + if (waiting.IsCompleted) + { + var early = await waiting; + throw new InvalidOperationException($"The competing creator exited before waiting for its subject lock ({early.Outcome})."); + } + await using var command = new NpgsqlCommand("SELECT EXISTS (SELECT 1 FROM pg_locks WHERE locktype='advisory' " + + "AND database=(SELECT oid FROM pg_database WHERE datname=current_database()) AND NOT granted)", connection); + if (await command.ExecuteScalarAsync() is true) return; + await Task.Delay(10); + } + throw new InvalidOperationException("The actual competing identity owner did not reach its subject-lock wait."); + } + + private sealed class PausingStore(IUserBindingStore inner, TaskCompletionSource entered, Task release) : IUserBindingStore + { + public async Task FindExactAsync(GlobalIdentitySubject subject, CancellationToken cancellationToken = default) + { + var user = await inner.FindExactAsync(subject, cancellationToken); + entered.TrySetResult(); + await release.WaitAsync(cancellationToken); + return user; + } + public Task AddAsync(User user, CancellationToken cancellationToken = default) => inner.AddAsync(user, cancellationToken); + } + + private sealed class WrongCreationReferenceStore(IUserBindingStore inner) : IUserBindingStore + { + public Task FindExactAsync(GlobalIdentitySubject subject, CancellationToken cancellationToken = default) => + inner.FindExactAsync(subject, cancellationToken); + public Task AddAsync(User user, CancellationToken cancellationToken = default) + { + // A test-only mutation of the actual business row leaves the real database witness to refuse it. + typeof(User).GetProperty(nameof(User.CreationAuditTimestamp))!.SetValue(user, user.CreationAuditTimestamp.AddTicks(10)); + return inner.AddAsync(user, cancellationToken); + } + } + + private sealed class ObservingFailureStore(IUserBindingStore inner, Action observe) : IUserBindingStore + { + public Task FindExactAsync(GlobalIdentitySubject subject, CancellationToken cancellationToken = default) => + inner.FindExactAsync(subject, cancellationToken); + public async Task AddAsync(User user, CancellationToken cancellationToken = default) + { + try { await inner.AddAsync(user, cancellationToken); } + catch (UserBindingStorageException failure) { observe(failure); throw; } + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.Lifecycle.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.Lifecycle.cs new file mode 100644 index 000000000..a7c46c835 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.Lifecycle.cs @@ -0,0 +1,276 @@ +using System.Data.Common; +using FluentAssertions; +using LearnStack.Modules.Identity.Application.Abstractions; +using LearnStack.Modules.Identity.Application.Contracts.Bindings; +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.Modules.Tenancy.Application.Contracts.Tenant; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.Tools.Seeder; +using MediatR; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class GlobalIdentityBootstrapTests +{ + [Fact] + public async Task Precontext_binding_lookup_does_not_pin_common_coordinators_before_tenant_resolution() + { + await using var dataSource = NpgsqlDataSource.Create(_database.AppConnectionString); + var seed = new SeedRunner( + context => SeedComposition.Build(dataSource, context, NullLoggerFactory.Instance), + NullLogger.Instance); + (await seed.RunAsync(CancellationToken.None, [SeedData.English with { Curriculum = null }])) + .Should().Be(0); + await using (var creation = BuildProvider(_database.AppConnectionString, Registration, + new FixtureAdmission(Subject, Actor))) + { + await QualifyAsync(creation); + (await AdoptAsync(creation, Subject, Actor)).Outcome.Should().Be(IdentityBindingOutcome.Created); + } + + var accessor = new StaticTenantContextAccessor(null); + await using var provider = BuildProvider(_database.AppConnectionString, Registration, + new FixtureAdmission(Subject, Actor), services => + { + services.Replace(ServiceDescriptor.Singleton(accessor)); + services.AddMediatR(configuration => configuration.RegisterServicesFromAssembly( + typeof(LearnStack.Modules.Tenancy.Application.AssemblyMarker).Assembly)); + }); + await QualifyAsync(provider); + await using var scope = provider.CreateAsyncScope(); + var services = scope.ServiceProvider; + var reader = services.GetRequiredService(); + (await reader.ResolveExistingAsync(Subject)).Outcome.Should().Be(IdentityBindingOutcome.Existing); + + accessor.Current = new ResolvedBindingLifecycleContext(SeedData.English.TenantId, Actor); + var organization = OrganizationId.From(Guid.CreateVersion7()); + var result = await services.GetRequiredService().Send( + new CreateOrganizationCommand(organization, "binding-lifecycle-branch", "Binding lifecycle branch")); + result.IsSuccess.Should().BeTrue("the real ordinary audit/transaction pipeline sees the newly resolved context"); + services.GetRequiredService().HasActiveTransaction.Should().BeFalse(); + services.GetRequiredService().IsRollbackOnly.Should().BeFalse(); + services.GetRequiredService().Intents.Should().BeEmpty(); + + (await reader.ResolveExistingAsync(Subject)).Outcome.Should().Be(IdentityBindingOutcome.AdmissionDenied); + (await services.GetRequiredService().AdoptAsync(Subject, Actor)) + .Outcome.Should().Be(IdentityBindingOutcome.AdmissionDenied); + (await CountsAsync()).Should().Be((1L, 1L)); + + await using var connection = await OpenConnectionAsync(_database.AppConnectionString); + await using var transaction = await connection.BeginTransactionAsync(); + await SchemaQueries.SetTenantAsync(connection, transaction, SeedData.English.TenantId.Value); + await SchemaQueries.AssertApplicationRoleAsync(connection); + await using var read = new NpgsqlCommand(""" + SELECT tenant_id, actor_user_id, outcome, after_state::text + FROM public.audit_log + WHERE operation = 'tenancy.organization.create' AND entity_id = @target + """, connection, transaction); + read.Parameters.AddWithValue("target", organization.Value.ToString("D")); + await using var rows = await read.ExecuteReaderAsync(); + (await rows.ReadAsync()).Should().BeTrue("the ordinary business write has its durable MUST audit"); + rows.GetGuid(0).Should().Be(SeedData.English.TenantId.Value); + rows.GetGuid(1).Should().Be(Actor.Value); + rows.GetString(2).Should().Be("success"); + rows.GetString(3).Should().Contain("Binding lifecycle branch"); + (await rows.ReadAsync()).Should().BeFalse(); + } + + [Theory] + [InlineData(false, false)] + [InlineData(false, true)] + [InlineData(true, false)] + [InlineData(true, true)] + public async Task Lookup_failure_or_cancellation_survives_awaited_cleanup_failure(bool adoption, bool cancelled) + { + const string PrimaryCanary = "private-lookup-failure-canary"; + using var cancellation = new CancellationTokenSource(); + var control = new BindingCleanupFault(); + var logger = new BindingCleanupLogger(); + Exception primary = cancelled + ? new OperationCanceledException(PrimaryCanary, cancellation.Token) + : new NpgsqlException(PrimaryCanary); + await using var provider = CleanupFaultProvider(control, logger, () => + { + if (cancelled) cancellation.Cancel(); + throw primary; + }); + await QualifyAsync(provider); + await using var scope = provider.CreateAsyncScope(); + var services = scope.ServiceProvider; + var operation = adoption + ? services.GetRequiredService().AdoptAsync(Subject, Actor, cancellation.Token) + : services.GetRequiredService().ResolveExistingAsync(Subject, cancellationToken: cancellation.Token); + await AssertCleanupIsJoinedAsync(operation, control, services); + + if (cancelled) + { + var observed = await Assert.ThrowsAnyAsync(() => operation); + observed.Should().BeSameAs(primary); + observed.CancellationToken.Should().Be(cancellation.Token); + } + else + { + var result = await operation; + result.Outcome.Should().Be(IdentityBindingOutcome.StorageUnavailable); + result.Actor.Should().BeNull(); + } + AssertBoundedCleanupDiagnostic(logger, PrimaryCanary); + services.GetRequiredService().Intents.Should().BeEmpty(); + (await CountsAsync()).Should().Be((0L, 0L)); + } + + [Fact] + public async Task Otherwise_normal_lookup_with_failed_cleanup_returns_a_bounded_storage_refusal() + { + var control = new BindingCleanupFault(); + var logger = new BindingCleanupLogger(); + await using var provider = CleanupFaultProvider(control, logger, () => null); + await QualifyAsync(provider); + await using var scope = provider.CreateAsyncScope(); + var services = scope.ServiceProvider; + var operation = services.GetRequiredService().ResolveExistingAsync(Subject); + await AssertCleanupIsJoinedAsync(operation, control, services); + var result = await operation; + result.Outcome.Should().Be(IdentityBindingOutcome.StorageUnavailable); + result.Actor.Should().BeNull(); + AssertBoundedCleanupDiagnostic(logger, "unused-primary-canary"); + } + + private ServiceProvider CleanupFaultProvider(BindingCleanupFault control, BindingCleanupLogger logger, + Func lookup) => BuildProvider(_database.AppConnectionString, Registration, + new FixtureAdmission(Subject, Actor), services => + { + services.Replace(ServiceDescriptor.Scoped(provider => + new BindingCleanupUnit((IGlobalIdentityUnitOfWork)provider.GetRequiredService(), control))); + services.Replace(ServiceDescriptor.Scoped(_ => new FailingBindingLookup(lookup))); + services.AddSingleton>(logger); + }); + + private static async Task AssertCleanupIsJoinedAsync(Task operation, + BindingCleanupFault control, IServiceProvider services) + { + var first = await Task.WhenAny(control.Entered.Task, operation).WaitAsync(TimeSpan.FromSeconds(10)); + if (first == operation) + { + await operation; + throw new InvalidOperationException("The binding operation returned without awaiting its owner cleanup."); + } + try + { + operation.IsCompleted.Should().BeFalse("independent owner cleanup remains part of the binding operation"); + services.GetRequiredService().HasActiveTransaction.Should().BeFalse( + "the decorated frame completed its real PostgreSQL cleanup before the injected cleanup fault"); + } + finally { control.Release.TrySetResult(); } + } + + private static void AssertBoundedCleanupDiagnostic(BindingCleanupLogger logger, string primaryCanary) + { + var entry = logger.Entries.Should().ContainSingle().Subject; + entry.Level.Should().Be(LogLevel.Error); + entry.Exception.Should().BeNull(); + entry.Message.Should().Be("Global identity owner cleanup failed; its scope retains connection cleanup responsibility.") + .And.NotContain(primaryCanary).And.NotContain(BindingCleanupFault.Canary); + } + + private sealed class ResolvedBindingLifecycleContext(TenantId tenant, UserId actor) : ITenantContext + { + public bool IsResolved => true; + public TenantId TenantId => tenant; + public OrganizationId? OrganizationId => null; + public UserId? UserId => actor; + public TenantContextOrigin? Origin => TenantContextOrigin.Ambient; + public string? CorrelationId => null; + public string? ModuleName => null; + } + + private sealed class FailingBindingLookup(Func lookup) : IUserBindingStore + { + public Task FindExactAsync(GlobalIdentitySubject subject, CancellationToken cancellationToken = default) => + Task.FromResult(lookup()); + public Task AddAsync(User user, CancellationToken cancellationToken = default) => + throw new InvalidOperationException("Lookup failure must precede handler construction and mutation."); + } + + private sealed class BindingCleanupFault + { + public const string Canary = "private-owner-cleanup-failure-canary"; + public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + } + + private sealed class BindingCleanupFrame(IUnitOfWorkScope inner, BindingCleanupFault control) : IUnitOfWorkScope + { + public bool IsOwner => inner.IsOwner; + public Task CompleteAsync(CancellationToken cancellationToken = default) => inner.CompleteAsync(cancellationToken); + public Task FailAsync(CancellationToken cancellationToken = default) => inner.FailAsync(cancellationToken); + public async ValueTask DisposeAsync() + { + await inner.DisposeAsync(); + control.Entered.TrySetResult(); + await control.Release.Task; + throw new IOException(BindingCleanupFault.Canary); + } + } + + private sealed class BindingCleanupUnit(IGlobalIdentityUnitOfWork inner, BindingCleanupFault control) + : IGlobalIdentityUnitOfWork + { + public DbConnection Connection => inner.Connection; + public DbTransaction? Transaction => inner.Transaction; + public bool HasActiveTransaction => inner.HasActiveTransaction; + public TransactionMode? Mode => inner.Mode; + public bool IsRollbackOnly => inner.IsRollbackOnly; + public bool IsGlobalIdentityTransaction => inner.IsGlobalIdentityTransaction; + public Task BeginTransactionAsync(CancellationToken cancellationToken = default) => + inner.BeginTransactionAsync(cancellationToken); + public Task BeginTransactionAsync(TransactionMode mode, CancellationToken cancellationToken = default) => + inner.BeginTransactionAsync(mode, cancellationToken); + public async Task BeginGlobalIdentityTransactionAsync(GlobalIdentityOwnerDescriptor descriptor, + TransactionMode mode, CancellationToken cancellationToken = default) => + new BindingCleanupFrame(await inner.BeginGlobalIdentityTransactionAsync(descriptor, mode, cancellationToken), control); + public Task AcquireGlobalIdentitySubjectLockAsync(GlobalIdentityOwnerDescriptor descriptor, + CancellationToken cancellationToken = default) => inner.AcquireGlobalIdentitySubjectLockAsync(descriptor, cancellationToken); + public GlobalIdentityContextAnnouncement? GetGlobalIdentityAnnouncement(DbTransaction? transaction) => + inner.GetGlobalIdentityAnnouncement(transaction); + public void EnrollGlobalIdentityContext(object context, GlobalIdentityOwnerDescriptor descriptor) => + inner.EnrollGlobalIdentityContext(context, descriptor); + public bool IsGlobalIdentityContextEnrolled(object context, DbTransaction? transaction) => + inner.IsGlobalIdentityContextEnrolled(context, transaction); + public Task ValidateGlobalIdentityConstraintsAsync(GlobalIdentityOwnerDescriptor descriptor, + CancellationToken cancellationToken = default) => inner.ValidateGlobalIdentityConstraintsAsync(descriptor, cancellationToken); + public Task SetTenantContextAsync(ITenantContext context, CancellationToken cancellationToken = default) => + inner.SetTenantContextAsync(context, cancellationToken); + public bool IsTenantContextIssuedOn(DbTransaction? transaction) => inner.IsTenantContextIssuedOn(transaction); + public TenantContextAnnouncement? GetTenantContextAnnouncement(DbTransaction? transaction) => + inner.GetTenantContextAnnouncement(transaction); + public Task SetProvisioningTenantContextAsync(TenantId tenantId, CancellationToken cancellationToken = default) => + inner.SetProvisioningTenantContextAsync(tenantId, cancellationToken); + public Task CommitAsync(CancellationToken cancellationToken = default) => inner.CommitAsync(cancellationToken); + public Task RollbackAsync(CancellationToken cancellationToken = default) => inner.RollbackAsync(cancellationToken); + public void MarkRollbackOnly() => inner.MarkRollbackOnly(); + // The original scoped IUnitOfWork registration owns the real connection. + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + + private sealed class BindingCleanupLogger : ILogger + { + public List<(LogLevel Level, string Message, Exception? Exception)> 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((logLevel, formatter(state, exception), exception)); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.Provider.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.Provider.cs new file mode 100644 index 000000000..805c76e71 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.Provider.cs @@ -0,0 +1,67 @@ +using System.Net; +using FluentAssertions; +using LearnStack.Modules.Identity.Application.Contracts.Bindings; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Identity; +using LearnStack.Tests.Integration.TenancyIdentity; +using LearnStack.Tools.Seeder; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class GlobalIdentityBootstrapTests +{ + private static readonly string[] MfaSetupActions = ["CONFIGURE_TOTP"]; + + [Fact] + public async Task Signed_provider_and_authenticated_readback_facts_bind_the_preserved_actor_without_password_reuse() + { + await using var providerFixture = await KeycloakFixture.StartAsync(); + using var admin = await providerFixture.CreateAdminClientAsync(); + var declaration = SeedData.IdentityUsers[0]; + using var browser = providerFixture.Browser(); + var authorization = await browser.AuthorizeAsync(declaration.Username, KeycloakFixture.DemoPassword, + "https://" + declaration.Tenant.Host + ":3000/api/auth/callback/keycloak"); + authorization.Authorized.Should().BeTrue(); + var exchange = await browser.RedeemAsync(authorization); + exchange.StatusCode.Should().Be(HttpStatusCode.OK); + var signed = await KeycloakTokenVerifier.ValidateAsync(providerFixture, exchange.AccessToken, "learnstack-api"); + var account = await admin.UserAsync(declaration.Username); + var opaqueSubject = signed.GetProperty("sub").GetString() + ?? throw new InvalidOperationException("The verified fixture subject is absent."); + (account.GetProperty("id").GetString() == opaqueSubject).Should().BeTrue(); + (signed.GetProperty("user_id").GetString() == declaration.UserId.Value.ToString("D")).Should().BeTrue(); + (account.GetProperty("attributes").GetProperty("user_id")[0].GetString() + == declaration.UserId.Value.ToString("D")).Should().BeTrue(); + + await using var database = await DisposableSchemaDatabase.CreateAsync(_schema.Postgres); + var registration = new IdentityAuthorityRegistration(AuthorityId, providerFixture.Issuer); + await InstallAsync(database.MigrationConnectionString, registration); + var subject = new GlobalIdentitySubject(AuthorityId, providerFixture.Issuer, opaqueSubject); + await using var services = BuildProvider(database.AppConnectionString, registration, + new FixtureAdmission(subject, declaration.UserId)); + await QualifyAsync(services); + var created = await AdoptAsync(services, subject, declaration.UserId); + created.Outcome.Should().Be(IdentityBindingOutcome.Created); + created.Actor.Should().Be(declaration.UserId); + + // The disposable provider now requires a different password and MFA setup. + // Adoption consumes authenticated provider facts, never the user's login credential. + var accountId = account.GetProperty("id").GetString()!; + (await admin.PutAsync("users/" + Uri.EscapeDataString(accountId) + "/reset-password", + new { type = "password", value = "changed-fixture-bootstrap-password", temporary = false })) + .Should().Be(HttpStatusCode.NoContent); + (await admin.PutAsync("users/" + Uri.EscapeDataString(accountId), + new { requiredActions = MfaSetupActions })).Should().Be(HttpStatusCode.NoContent); + var preserved = await admin.UserAsync(declaration.Username); + (preserved.GetProperty("id").GetString() == opaqueSubject).Should().BeTrue(); + (preserved.GetProperty("attributes").GetProperty("user_id")[0].GetString() + == declaration.UserId.Value.ToString("D")).Should().BeTrue(); + (await AdoptAsync(services, subject, declaration.UserId)).Outcome.Should().Be(IdentityBindingOutcome.Existing); + (await ReadAsync(services, subject, declaration.UserId)).Outcome.Should().Be(IdentityBindingOutcome.Existing); + (await AdoptAsync(services, new(AuthorityId, providerFixture.Issuer, "unverified-asserted-subject"), declaration.UserId)) + .Outcome.Should().Be(IdentityBindingOutcome.AdmissionDenied); + (await AdoptAsync(services, subject, SeedData.IdentityUsers[1].UserId)) + .Outcome.Should().Be(IdentityBindingOutcome.AdmissionDenied); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.cs new file mode 100644 index 000000000..f575a0e29 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityBootstrapTests.cs @@ -0,0 +1,287 @@ +using FluentAssertions; +using LearnStack.Api.Composition; +using LearnStack.Application.Pipeline; +using LearnStack.Infrastructure.Caching; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Application.Abstractions; +using LearnStack.Modules.Identity.Application.Contracts.Bindings; +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Caching; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Secrets; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using LearnStack.Tools.Seeder; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// Real production global consumers on app-role PostgreSQL, without an HTTP creation surface. +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed partial class GlobalIdentityBootstrapTests(SchemaFixture schema) : IAsyncLifetime +{ + private readonly SchemaFixture _schema = schema; + private static readonly IdentityAuthorityId AuthorityId = IdentityAuthorityId.From( + Guid.Parse("01930000-0000-7000-8000-00000000f301")); + private static readonly IdentityAuthorityRegistration Registration = new(AuthorityId, "https://localhost/realms/learnstack"); + private static readonly UserId Actor = SeedData.IdentityUsers[0].UserId; + private static GlobalIdentitySubject Subject => new(AuthorityId, Registration.Issuer, "opaque-bootstrap-subject-canary"); + private DisposableSchemaDatabase _database = null!; + + public async Task InitializeAsync() + { + _database = await DisposableSchemaDatabase.CreateAsync(_schema.Postgres); + await InstallAsync(_database.MigrationConnectionString, Registration); + } + + public Task DisposeAsync() => _database.DisposeAsync().AsTask(); + + [Fact] + public async Task Production_creation_and_existing_reads_use_one_binding_one_MUST_row_and_no_repair() + { + await using var provider = BuildProvider(_database.AppConnectionString, Registration, + new FixtureAdmission(Subject, Actor)); + await QualifyAsync(provider); + (await AdoptAsync(provider, Subject, Actor)).Outcome.Should().Be(IdentityBindingOutcome.Created); + (await AdoptAsync(provider, Subject, Actor)).Outcome.Should().Be(IdentityBindingOutcome.Existing); + (await ReadAsync(provider, Subject)).Outcome.Should().Be(IdentityBindingOutcome.Existing); + (await ReadAsync(provider, Subject, SeedData.IdentityUsers[1].UserId)).Outcome.Should().Be(IdentityBindingOutcome.Conflict); + (await ReadAsync(provider, new(AuthorityId, Registration.Issuer, "unbound-other-subject"))) + .Outcome.Should().Be(IdentityBindingOutcome.NotFound); + (await CountsAsync()).Should().Be((1L, 1L)); + var rows = await AuditRowsAsync(); + rows.Should().ContainSingle(); + rows[0].Outcome.Should().Be("success"); + rows[0].Metadata.Should().Contain("identity-seed-adoption").And.Contain(Subject.SubjectKey.Hex) + .And.NotContain(Subject.Subject); + rows[0].Snapshots.Should().Contain(SensitiveTokenCatalog.RedactedValue).And.NotContain(Subject.Subject); + } + + [Fact] + public async Task API_composition_denies_seed_adoption_before_opening_any_global_owner() + { + await using var provider = BuildProvider(_database.AppConnectionString, Registration); + await using var scope = provider.CreateAsyncScope(); + var services = scope.ServiceProvider; + var result = await services.GetRequiredService().AdoptAsync(Subject, Actor); + result.Outcome.Should().Be(IdentityBindingOutcome.AdmissionDenied); + result.Actor.Should().BeNull(); + services.GetRequiredService().HasActiveTransaction.Should().BeFalse(); + services.GetRequiredService().Intents.Should().BeEmpty(); + (await CountsAsync()).Should().Be((0L, 0L)); + } + + [Fact] + public async Task Read_only_normalization_completes_then_a_tenant_owner_can_begin_in_the_same_scope() + { + await using var provider = BuildProvider(_database.AppConnectionString, Registration, + new FixtureAdmission(Subject, Actor)); + await QualifyAsync(provider); + await AdoptAsync(provider, Subject, Actor); + await using var scope = provider.CreateAsyncScope(); + var services = scope.ServiceProvider; + (await services.GetRequiredService().ResolveExistingAsync(Subject)) + .Outcome.Should().Be(IdentityBindingOutcome.Existing); + var unit = services.GetRequiredService(); + unit.HasActiveTransaction.Should().BeFalse(); + unit.IsRollbackOnly.Should().BeFalse(); + await using var tenant = await unit.BeginTransactionAsync(); + await unit.SetTenantContextAsync(new SeedTenantContext(SeedData.English.TenantId, null)); + await SchemaQueries.AssertApplicationRoleAsync(unit.Connection); + await tenant.CompleteAsync(); + unit.HasActiveTransaction.Should().BeFalse(); + } + + [Fact] + public async Task Existing_seed_adoption_completes_without_intent_and_permits_same_scope_reuse() + { + await using var provider = BuildProvider(_database.AppConnectionString, Registration, + new FixtureAdmission(Subject, Actor)); + await QualifyAsync(provider); + (await AdoptAsync(provider, Subject, Actor)).Outcome.Should().Be(IdentityBindingOutcome.Created); + await using var scope = provider.CreateAsyncScope(); + var services = scope.ServiceProvider; + var adopter = services.GetRequiredService(); + for (var attempt = 0; attempt < 2; attempt++) + { + (await adopter.AdoptAsync(Subject, Actor)).Outcome.Should().Be(IdentityBindingOutcome.Existing); + services.GetRequiredService().HasActiveTransaction.Should().BeFalse(); + services.GetRequiredService().IsRollbackOnly.Should().BeFalse(); + services.GetRequiredService().Intents.Should().BeEmpty(); + } + var unit = services.GetRequiredService(); + await using var tenant = await unit.BeginTransactionAsync(); + await unit.SetTenantContextAsync(new SeedTenantContext(SeedData.English.TenantId, null)); + await SchemaQueries.AssertApplicationRoleAsync(unit.Connection); + await tenant.CompleteAsync(); + (await CountsAsync()).Should().Be((1L, 1L)); + } + + [Fact] + public async Task Resolved_tenant_context_cannot_read_or_adopt_even_an_existing_binding() + { + await using (var normal = BuildProvider(_database.AppConnectionString, Registration, new FixtureAdmission(Subject, Actor))) + { + await QualifyAsync(normal); + (await AdoptAsync(normal, Subject, Actor)).Outcome.Should().Be(IdentityBindingOutcome.Created); + } + var storeResolutions = 0; + await using var provider = BuildProvider(_database.AppConnectionString, Registration, new FixtureAdmission(Subject, Actor), services => + { + services.Replace(ServiceDescriptor.Singleton( + new StaticTenantContextAccessor(new SeedTenantContext(SeedData.English.TenantId, null)))); + services.Replace(ServiceDescriptor.Scoped(_ => + { + Interlocked.Increment(ref storeResolutions); + throw new InvalidOperationException("The inherited-context proof must refuse before resolving its store."); + })); + }); + await QualifyAsync(provider); + await using var scope = provider.CreateAsyncScope(); + var services = scope.ServiceProvider; + (await services.GetRequiredService().ResolveExistingAsync(Subject)) + .Outcome.Should().Be(IdentityBindingOutcome.AdmissionDenied); + (await services.GetRequiredService().AdoptAsync(Subject, Actor)) + .Outcome.Should().Be(IdentityBindingOutcome.AdmissionDenied); + storeResolutions.Should().Be(0); + services.GetRequiredService().HasActiveTransaction.Should().BeFalse(); + services.GetRequiredService().Current.Should().BeNull(); + services.GetRequiredService().Intents.Should().BeEmpty(); + (await CountsAsync()).Should().Be((1L, 1L)); + } + + [Fact] + public async Task Qualification_refuses_missing_or_changed_anchor_without_installing_or_rebinding() + { + await using (var missing = await DisposableSchemaDatabase.CreateAsync(_schema.Postgres)) + await using (var unqualified = BuildProvider(missing.AppConnectionString, Registration, new FixtureAdmission(Subject, Actor))) + { + await FluentActions.Awaiting(() => QualifyAsync(unqualified)).Should().ThrowAsync() + .WithMessage("Identity authority startup qualification is unavailable or does not match deployment configuration."); + (await AdoptAsync(unqualified, Subject, Actor)).Outcome.Should().Be(IdentityBindingOutcome.AuthorityUnavailable); + } + var changed = new IdentityAuthorityRegistration(AuthorityId, "https://other.invalid/realms/learnstack"); + await using var provider = BuildProvider(_database.AppConnectionString, changed, new FixtureAdmission(Subject, Actor)); + await FluentActions.Awaiting(() => QualifyAsync(provider)).Should().ThrowAsync() + .WithMessage("Identity authority startup qualification is unavailable or does not match deployment configuration."); + (await AdoptAsync(provider, Subject, Actor)).Outcome.Should().Be(IdentityBindingOutcome.AuthorityUnavailable); + await using var connection = await OpenConnectionAsync(_database.MigrationConnectionString); + await FluentActions.Awaiting(() => IdentityAuthorityDeploymentInstaller.InstallAsync(connection, changed)) + .Should().ThrowAsync().WithMessage("Identity authority deployment installation was refused."); + (await CountsAsync()).Should().Be((0L, 0L)); + } + + private static ServiceProvider BuildProvider(string appConnection, IdentityAuthorityRegistration registration, + ISeedIdentityFoundationAdmission? admission = null, Action? configure = null) + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddLearnStackMediatRPipeline(); + services.AddSingleton(StaticTenantContextAccessor.Unresolved); + services.AddTransient(provider => + provider.GetRequiredService().Current ?? UnresolvedTenantContext.Instance); + if (admission is not null) services.AddSingleton(admission); + services.AddLearnStackPersistence(new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + { + ["ConnectionStrings:Default"] = appConnection, + ["Identity:AuthorityId"] = registration.AuthorityId.Value.ToString("D"), + ["Authentication:Tenant:Issuer"] = registration.Issuer, + }).Build()); + configure?.Invoke(services); + return services.BuildServiceProvider(validateScopes: true); + } + + private static Task QualifyAsync(ServiceProvider provider) => provider.GetRequiredService().QualifyAsync(); + + private static async Task OpenConnectionAsync(string connectionString) => + (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); + + private static async Task InstallAsync(string connectionString, IdentityAuthorityRegistration registration) + { + await using var connection = await OpenConnectionAsync(connectionString); + await IdentityAuthorityDeploymentInstaller.InstallAsync(connection, registration); + } + + private static async Task AdoptAsync(ServiceProvider provider, GlobalIdentitySubject subject, UserId actor) + { + await using var scope = provider.CreateAsyncScope(); + return await scope.ServiceProvider.GetRequiredService().AdoptAsync(subject, actor); + } + + private static async Task ReadAsync(ServiceProvider provider, GlobalIdentitySubject subject, UserId? actor = null) + { + await using var scope = provider.CreateAsyncScope(); + return await scope.ServiceProvider.GetRequiredService().ResolveExistingAsync(subject, actor); + } + + private async Task<(long Users, long Audits)> CountsAsync(GlobalIdentitySubject? subject = null) + { + var selected = subject ?? Subject; + await using var connection = await OpenConnectionAsync(_database.MigrationConnectionString); + await using var transaction = await AnnounceEvidenceAsync(connection, selected); + await using var command = new NpgsqlCommand("SELECT (SELECT count(*) FROM public.users WHERE authority_id=@authority " + + "AND subject_key=@key), (SELECT count(*) FROM public.audit_log WHERE operation='identity.user.create' " + + "AND metadata->>'identity_authority_id'=@authority_text AND metadata->>'identity_subject_key'=@key_hex)", connection, transaction); + command.Parameters.AddWithValue("authority", selected.AuthorityId.Value); + command.Parameters.AddWithValue("key", selected.SubjectKey.ToByteArray()); + command.Parameters.AddWithValue("authority_text", selected.AuthorityId.Value.ToString("D")); + command.Parameters.AddWithValue("key_hex", selected.SubjectKey.Hex); + await using var reader = await command.ExecuteReaderAsync(); + await reader.ReadAsync(); + return (reader.GetInt64(0), reader.GetInt64(1)); + } + + private async Task> AuditRowsAsync(GlobalIdentitySubject? subject = null) + { + var selected = subject ?? Subject; + await using var connection = await OpenConnectionAsync(_database.MigrationConnectionString); + await using var transaction = await AnnounceEvidenceAsync(connection, selected); + await using var command = new NpgsqlCommand("SELECT outcome, metadata::text, " + + "coalesce(before_state::text,'') || coalesce(after_state::text,'') || coalesce(changes::text,'') " + + "FROM public.audit_log WHERE operation='identity.user.create' " + + "AND metadata->>'identity_authority_id'=@authority AND metadata->>'identity_subject_key'=@key ORDER BY timestamp", connection, transaction); + command.Parameters.AddWithValue("authority", selected.AuthorityId.Value.ToString("D")); + command.Parameters.AddWithValue("key", selected.SubjectKey.Hex); + await using var reader = await command.ExecuteReaderAsync(); + var rows = new List(); + while (await reader.ReadAsync()) rows.Add(new(reader.GetString(0), reader.GetString(1), reader.GetString(2))); + return rows; + } + + private static async Task AnnounceEvidenceAsync(NpgsqlConnection connection, GlobalIdentitySubject subject) + { + var transaction = await connection.BeginTransactionAsync(); + await using var command = new NpgsqlCommand("SELECT set_config('app.identity_authority_id', @authority, true), " + + "set_config('app.identity_subject_key', @subject, true)", connection, transaction); + command.Parameters.AddWithValue("authority", subject.AuthorityId.Value.ToString("D")); + command.Parameters.AddWithValue("subject", subject.SubjectKey.Hex); + await command.ExecuteNonQueryAsync(); + return transaction; + } + + private sealed record AuditRow(string Outcome, string Metadata, string Snapshots); + + private sealed class FixtureAdmission(GlobalIdentitySubject subject, UserId actor) : ISeedIdentityFoundationAdmission + { + public ValueTask AllowsAsync(GlobalIdentitySubject candidate, UserId declaredActor, + CancellationToken cancellationToken = default) => ValueTask.FromResult(declaredActor == actor + && candidate.AuthorityId == subject.AuthorityId + && candidate.SubjectKey.Equals(subject.SubjectKey) + && string.Equals(candidate.Issuer, subject.Issuer, StringComparison.Ordinal) + && string.Equals(candidate.Subject, subject.Subject, StringComparison.Ordinal)); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.AuditInsertion.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.AuditInsertion.cs new file mode 100644 index 000000000..3ee9cb454 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.AuditInsertion.cs @@ -0,0 +1,160 @@ +using System.Text.Json; +using FluentAssertions; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using Npgsql; +using NpgsqlTypes; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class GlobalIdentitySchemaTests +{ + [Theory] + [InlineData("absent-scope")] + [InlineData("source")] + [InlineData("bootstrap-actor")] + [InlineData("seed-actor")] + [InlineData("extra-metadata")] + [InlineData("authority")] + [InlineData("subject")] + [InlineData("target")] + [InlineData("entity-type")] + [InlineData("tenant")] + [InlineData("organization")] + public async Task Global_audit_INSERT_refuses_malformed_attribution_and_a_valid_app_twin_commits(string fault) + { + var subject = NewSubject(); + var clean = GlobalAuditCandidate.Create(subject); + var dirty = clean with { Id = Guid.CreateVersion7() }; + var metadata = JsonSerializer.Deserialize>(dirty.Metadata)!; + switch (fault) + { + case "source": metadata["identity_source"] = "unregistered-source"; break; + case "bootstrap-actor": dirty = dirty with { Actor = UserId.SystemActor.Value }; break; + case "seed-actor": metadata["identity_source"] = "identity-seed-adoption"; break; + case "extra-metadata": metadata["extra"] = "unregistered-value"; break; + case "authority": metadata["identity_authority_id"] = Guid.NewGuid().ToString("D"); break; + case "subject": metadata["identity_subject_key"] = new string('0', 64); break; + case "target": dirty = dirty with { Target = Guid.NewGuid().ToString("D") }; break; + case "entity-type": dirty = dirty with { EntityType = "Membership" }; break; + case "tenant": dirty = dirty with { Tenant = Guid.CreateVersion7() }; break; + case "organization": dirty = dirty with { Organization = Guid.CreateVersion7() }; break; + case "absent-scope": break; + default: throw new ArgumentOutOfRangeException(nameof(fault)); + } + dirty = dirty with { Metadata = JsonSerializer.Serialize(metadata) }; + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using (var transaction = await app.BeginTransactionAsync()) + { + if (fault == "absent-scope") await ClearAsync(app, transaction); + else await AnnounceAsync(app, transaction, subject); + var insert = () => InsertGlobalAuditCandidateAsync(app, transaction, dirty); + (await insert.Should().ThrowAsync()).Which.SqlState.Should().Be("23514", + "the immediate attribution guard rejects the malformed row before deferred evidence"); + await transaction.RollbackAsync(); + } + await using (var transaction = await app.BeginTransactionAsync()) + { + await AnnounceAsync(app, transaction, subject); + await InsertGlobalAuditCandidateAsync(app, transaction, clean); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await transaction.CommitAsync(); + } + await AssertGlobalAuditCountAsync(fixture.Postgres.PlatformConnectionString, dirty.Id, 0); + await AssertGlobalAuditCountAsync(fixture.Postgres.PlatformConnectionString, clean.Id, 1); + } + + [Theory] + [InlineData("migration")] + [InlineData("platform")] + public async Task Global_creation_audit_cannot_be_inserted_through_owner_or_platform_credentials(string role) + { + var subject = NewSubject(); + var candidate = GlobalAuditCandidate.Create(subject); + var connectionString = role == "migration" ? fixture.Postgres.MigrationConnectionString : fixture.Postgres.PlatformConnectionString; + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); + await using var transaction = await connection.BeginTransactionAsync(); + await AnnounceAsync(connection, transaction, subject); + var insert = () => InsertGlobalAuditCandidateAsync(connection, transaction, candidate); + (await insert.Should().ThrowAsync()).Which.SqlState.Should().Be("23514"); + await transaction.RollbackAsync(); + await AssertGlobalAuditCountAsync(fixture.Postgres.PlatformConnectionString, candidate.Id, 0); + } + + [Fact] + public async Task Global_audit_WITH_CHECK_independently_refuses_missing_subject_and_detects_a_widened_policy() + { + await using var database = await DisposableSchemaDatabase.CreateAsync(fixture.Postgres); + var subject = NewSubject(); + var candidate = GlobalAuditCandidate.Create(subject); + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString); + // Both twins remove the earlier/late guards so the policy alone must + // reject a valid-shaped row with no announced global authority. + await ExecuteAsync(owner, null, """ + ALTER TABLE public.audit_log DISABLE TRIGGER tg_audit_log_identity_insert; + ALTER TABLE public.audit_log DISABLE TRIGGER tg_audit_log_identity_creation; + """); + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using (var clean = await app.BeginTransactionAsync()) + { + await ClearAsync(app, clean); + var insert = () => InsertGlobalAuditCandidateAsync(app, clean, candidate); + (await insert.Should().ThrowAsync()).Which.SqlState.Should().Be("42501"); + await clean.RollbackAsync(); + } + await AssertGlobalAuditCountAsync(database.PlatformConnectionString, candidate.Id, 0); + await ExecuteAsync(owner, null, "ALTER POLICY audit_log_isolation ON public.audit_log WITH CHECK (true)"); + await using (var dirty = await app.BeginTransactionAsync()) + { + await ClearAsync(app, dirty); + await InsertGlobalAuditCandidateAsync(app, dirty, candidate); + await dirty.CommitAsync(); + } + await AssertGlobalAuditCountAsync(database.PlatformConnectionString, candidate.Id, 1); + } + + private static async Task InsertGlobalAuditCandidateAsync(NpgsqlConnection connection, + NpgsqlTransaction transaction, GlobalAuditCandidate candidate) + { + 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,metadata) + VALUES(@id,@at,@tenant,@organization,@actor,'identity','identity.user.create', + 'SecurityEvent','Must',@entity_type,@target,'failed',@metadata::jsonb) + """, connection, transaction); + command.Parameters.AddWithValue("id", candidate.Id); + command.Parameters.AddWithValue("at", candidate.At); + command.Parameters.AddWithValue("tenant", candidate.Tenant); + command.Parameters.AddWithValue("organization", NpgsqlDbType.Uuid, (object?)candidate.Organization ?? DBNull.Value); + command.Parameters.AddWithValue("actor", NpgsqlDbType.Uuid, (object?)candidate.Actor ?? DBNull.Value); + command.Parameters.AddWithValue("entity_type", candidate.EntityType); + command.Parameters.AddWithValue("target", candidate.Target); + command.Parameters.AddWithValue("metadata", candidate.Metadata); + await command.ExecuteNonQueryAsync(); + } + + private static async Task AssertGlobalAuditCountAsync(string connectionString, Guid id, long expected) + { + await using var reader = (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); + await using var command = new NpgsqlCommand("SELECT count(*) FROM public.audit_log WHERE id=@id", reader); + command.Parameters.AddWithValue("id", id); + ((long)(await command.ExecuteScalarAsync())!).Should().Be(expected); + } + + private sealed record GlobalAuditCandidate(Guid Id, DateTimeOffset At, Guid Tenant, Guid? Organization, + Guid? Actor, string EntityType, string Target, string Metadata) + { + public static GlobalAuditCandidate Create(GlobalIdentitySubject subject) => new(Guid.CreateVersion7(), + GlobalIdentityCreationReference.NormalizeTimestamp(DateTimeOffset.UtcNow), TenantId.PlatformSentinel.Value, + null, null, "User", Guid.CreateVersion7().ToString("D"), JsonSerializer.Serialize(new + { + identity_authority_id = subject.AuthorityId.Value.ToString("D"), + identity_subject_key = subject.SubjectKey.Hex, + identity_source = "identity-bootstrap", + })); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs new file mode 100644 index 000000000..a816eb8c5 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.Controls.cs @@ -0,0 +1,353 @@ +using System.Text.RegularExpressions; +using FluentAssertions; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Migrations.Operations; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class GlobalIdentitySchemaTests +{ + internal static IReadOnlyDictionary WithCheckProofs { get; } = new Dictionary(StringComparer.Ordinal) + { + ["users"] = nameof(Global_User_INSERT_refuses_wrong_or_absent_subject_scope), + ["identity_authority"] = nameof(Authority_anchor_writes_require_the_deployment_owner_and_singleton_installation), + }; + + [Fact] + public async Task Global_User_INSERT_refuses_wrong_or_absent_subject_scope() + { + await using var database = await DisposableSchemaDatabase.CreateAsync(fixture.Postgres); + await InstallAuthorityAsync(database.MigrationConnectionString); + var own = NewSubject(); + await InsertPairAsync(database.AppConnectionString, own); + foreach (var missing in new[] { false, true }) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + (await ScalarAsync(app, transaction, """ + SELECT bool_and(has_column_privilege(current_user,'public.users',column_name,'INSERT')) + FROM unnest(ARRAY['id','authority_id','subject_key','provider_subject','status','creation_audit_id', + 'creation_audit_timestamp','created_at','created_by','row_version']) AS column_name + """)).Should().BeTrue(); + if (missing) await ClearAsync(app, transaction); + else await AnnounceAsync(app, transaction, own); + var insert = () => InsertUserAsync(app, transaction, NewSubject(), Guid.CreateVersion7(), Guid.CreateVersion7(), DateTimeOffset.UtcNow); + (await insert.Should().ThrowAsync()).Which.SqlState.Should().Be("42501", + "the initial row must fail self WITH CHECK before any deferred creation witness can run"); + await transaction.RollbackAsync(); + } + await using var read = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await using var scope = await read.BeginTransactionAsync(); + await AnnounceAsync(read, scope, own); + (await ScalarAsync(read, scope, "SELECT count(*) FROM public.users")).Should().Be(1); + } + + [Fact] + public async Task Authority_anchor_writes_require_the_deployment_owner_and_singleton_installation() + { + await using var database = await DisposableSchemaDatabase.CreateAsync(fixture.Postgres); + var appInstall = () => InstallAuthorityAsync(database.AppConnectionString); + (await appInstall.Should().ThrowAsync()).Which.SqlState.Should().Be("42501"); + await using (var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString)) + await ExecuteAsync(owner, null, "GRANT INSERT ON public.identity_authority TO learnstack_app"); + await using (var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString)) + (await ScalarAsync(app, null, "SELECT has_table_privilege(current_user,'public.identity_authority','INSERT')")).Should().BeTrue(); + // The test-only grant is committed on this isolated database. A valid + // first singleton row must now be refused by WITH CHECK itself. + (await appInstall.Should().ThrowAsync()).Which.SqlState.Should().Be("42501"); + await InstallAuthorityAsync(database.MigrationConnectionString); + await using (var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString)) + { + (await ScalarAsync(app, null, "SELECT count(*) FROM public.identity_authority")).Should().Be(1); + foreach (var statement in new[] { "UPDATE public.identity_authority SET issuer=issuer", "DELETE FROM public.identity_authority", "TRUNCATE public.identity_authority" }) + { + var mutation = () => ExecuteAsync(app, null, statement); + (await mutation.Should().ThrowAsync()).Which.SqlState.Should().Be("42501"); + } + } + } + + [Fact] + public async Task Applied_function_bodies_signatures_privileges_and_trigger_callers_match_the_compiled_migration() + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.MigrationConnectionString); + (await FunctionViolationsAsync(owner)).Should().BeEmpty(); + } + + [Theory] + [InlineData("body", "fn_identity_audit_evidence:body")] + [InlineData("privilege", "fn_identity_audit_evidence:public-execute")] + [InlineData("caller", "fn_identity_user_creation_audit_guard:trigger-callers")] + [InlineData("extra-definer", "public:definer-census")] + public async Task Applied_function_inspector_rejects_committed_widening_and_a_clean_twin_passes( + string fault, string expectedViolation) + { + await using var clean = await DisposableSchemaDatabase.CreateAsync(fixture.Postgres); + await using var dirty = await DisposableSchemaDatabase.CreateAsync(fixture.Postgres); + await using (var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(dirty.MigrationConnectionString)) + { + (await FunctionViolationsAsync(owner)).Should().BeEmpty(); + var definition = CompiledFunctions().Single(function => function.Name == "fn_identity_audit_evidence"); + var mutation = fault switch + { + "body" => definition.Definition.Replace("CREATE FUNCTION", "CREATE OR REPLACE FUNCTION", StringComparison.Ordinal) + .Replace(definition.Body, "\nBEGIN RETURN true; END\n", StringComparison.Ordinal), + "privilege" => "GRANT EXECUTE ON FUNCTION public.fn_identity_audit_evidence(uuid,timestamptz,uuid,bytea,uuid,text,text) TO PUBLIC", + "caller" => "DROP TRIGGER tg_users_creation_audit ON public.users", + "extra-definer" => """ + CREATE FUNCTION public.fn_unrelated_definer_probe() RETURNS boolean + LANGUAGE sql SECURITY DEFINER SET search_path=pg_catalog AS $$ SELECT true $$; + REVOKE ALL ON FUNCTION public.fn_unrelated_definer_probe() FROM PUBLIC; + """, + _ => throw new InvalidOperationException("Unknown planted function fault."), + }; + // No surrounding transaction: the fault commits before independent connections inspect it. + await ExecuteAsync(owner, null, mutation); + } + + await using (var observer = (NpgsqlConnection)await PostgresFixture.OpenAsync(dirty.MigrationConnectionString)) + (await FunctionViolationsAsync(observer)).Should().Contain(expectedViolation); + await using (var observer = (NpgsqlConnection)await PostgresFixture.OpenAsync(clean.MigrationConnectionString)) + (await FunctionViolationsAsync(observer)).Should().BeEmpty(); + + if (fault == "body") + { + var subject = NewSubject(); + (await MissingEvidenceAsync(clean.AppConnectionString, subject)).Should().BeFalse(); + (await MissingEvidenceAsync(dirty.AppConnectionString, subject)).Should().BeTrue( + "the committed replacement really widens the app-callable evidence result"); + } + if (fault == "caller") + { + await InstallAuthorityAsync(clean.MigrationConnectionString); + await InstallAuthorityAsync(dirty.MigrationConnectionString); + var orphan = () => InsertOrphanAsync(clean.AppConnectionString, NewSubject()); + (await orphan.Should().ThrowAsync()).Which.SqlState.Should().Be("23514"); + await InsertOrphanAsync(dirty.AppConnectionString, NewSubject()); + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Independent_app_probe_detects_a_committed_self_RLS_widening(bool widened) + { + await using var database = await DisposableSchemaDatabase.CreateAsync(fixture.Postgres); + await InstallAuthorityAsync(database.MigrationConnectionString); + var own = NewSubject(); + var foreign = NewSubject(); + await InsertPairAsync(database.AppConnectionString, own); + var foreignPair = await InsertPairAsync(database.AppConnectionString, foreign); + if (widened) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString); + await ExecuteAsync(owner, null, "ALTER POLICY users_isolation ON public.users USING (true)"); + } + + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await AnnounceAsync(app, transaction, own); + // Raw SQL deliberately omits EF's independent filter: it must observe the RLS fault. + await using var read = new NpgsqlCommand("SELECT count(*) FROM public.users WHERE id=@foreign", app, transaction); + read.Parameters.AddWithValue("foreign", foreignPair.Target); + ((long)(await read.ExecuteScalarAsync())!).Should().Be(widened ? 1 : 0); + (await ScalarAsync(app, transaction, "SELECT count(*) FROM public.users")).Should().Be(widened ? 2 : 1, + "the clean twin must see its own row, so an empty table or missing SELECT grant cannot mask the boundary"); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Owner_DELETE_probe_detects_guard_removal_while_app_delete_stays_denied(bool removed) + { + await using var database = await DisposableSchemaDatabase.CreateAsync(fixture.Postgres); + await InstallAuthorityAsync(database.MigrationConnectionString); + var subject = NewSubject(); + var pair = await InsertPairAsync(database.AppConnectionString, subject); + if (removed) + { + await using var setup = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString); + await ExecuteAsync(setup, null, "DROP TRIGGER tg_users_no_delete ON public.users"); + } + + await using (var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString)) + (await ScalarAsync(app, null, "SELECT has_table_privilege(current_user,'public.users','DELETE')")).Should().BeFalse(); + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString); + (await ScalarAsync(owner, null, "SELECT count(*) FROM public.users")).Should().Be(1, + "the owner arm must expose an actual target before the mutation probe"); + await using var delete = new NpgsqlCommand("DELETE FROM public.users WHERE id=@target", owner); + delete.Parameters.AddWithValue("target", pair.Target); + if (removed) + { + (await delete.ExecuteNonQueryAsync()).Should().Be(1); + (await ScalarAsync(owner, null, "SELECT count(*) FROM public.users")).Should().Be(0); + } + else + { + var mutate = () => delete.ExecuteNonQueryAsync(); + (await mutate.Should().ThrowAsync()).Which.SqlState.Should().Be("23514"); + (await ScalarAsync(owner, null, "SELECT count(*) FROM public.users")).Should().Be(1); + } + } + + private static async Task> FunctionViolationsAsync(NpgsqlConnection owner) + { + var expected = CompiledFunctions(); + var issues = new List(); + var actualDefiners = 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); + if (!actualDefiners.SequenceEqual(expected.Where(function => function.Definer).Select(function => function.Name).Order(StringComparer.Ordinal))) + issues.Add("public:definer-census"); + + foreach (var function in expected) + { + await using var command = new NpgsqlCommand(""" + SELECT p.prosrc,pg_get_function_result(p.oid),p.prosecdef,p.proretset,l.lanname,r.rolname,r.rolbypassrls, + p.provolatile::text,COALESCE(p.proconfig,ARRAY[]::text[]),pg_get_function_identity_arguments(p.oid), + p.pronargdefaults,has_function_privilege('learnstack_app',p.oid,'EXECUTE'), + EXISTS(SELECT 1 FROM aclexplode(COALESCE(p.proacl,acldefault('f',p.proowner))) a WHERE a.grantee=0 AND a.privilege_type='EXECUTE'), + ARRAY(SELECT (CASE WHEN a.grantee=0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee)::text END) + || CASE WHEN a.is_grantable THEN ':grant-option' ELSE '' END + FROM aclexplode(COALESCE(p.proacl,acldefault('f',p.proowner))) a + WHERE a.grantee<>p.proowner AND a.privilege_type='EXECUTE' ORDER BY a.grantee), + p.proisstrict,p.proparallel::text,p.proleakproof + FROM pg_proc p JOIN pg_roles r ON r.oid=p.proowner JOIN pg_language l ON l.oid=p.prolang + WHERE p.oid=to_regprocedure(@signature) + """, owner); + command.Parameters.AddWithValue("signature", function.Signature); + await using (var reader = await command.ExecuteReaderAsync()) + { + if (!await reader.ReadAsync()) { issues.Add(function.Name + ":missing-signature"); continue; } + if (reader.GetString(0).Trim() != function.Body.Trim()) issues.Add(function.Name + ":body"); + if (reader.GetString(1) != function.ReturnType || reader.GetBoolean(3)) issues.Add(function.Name + ":return-type"); + if (reader.GetBoolean(2) != function.Definer || reader.GetString(4) != function.Language + || reader.GetString(5) != "learnstack_migration" || reader.GetBoolean(6)) issues.Add(function.Name + ":execution-owner"); + if (reader.GetString(7) != function.Volatility || !reader.GetFieldValue(8).SequenceEqual(["search_path=pg_catalog"])) + issues.Add(function.Name + ":execution-settings"); + 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" } : []; + if (!reader.GetFieldValue(13).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"); + } + var actualCallers = new List(); + await using var triggers = new NpgsqlCommand(""" + SELECT t.tgname,n.nspname||'.'||c.relname,t.tgtype::integer,t.tgdeferrable,t.tginitdeferred,t.tgenabled::text + FROM pg_trigger t JOIN pg_class c ON c.oid=t.tgrelid JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE t.tgfoid=to_regprocedure(@signature) AND NOT t.tgisinternal ORDER BY t.tgname + """, owner); + triggers.Parameters.AddWithValue("signature", function.Signature); + await using (var reader = await triggers.ExecuteReaderAsync()) + while (await reader.ReadAsync()) + actualCallers.Add(new(reader.GetString(0), reader.GetString(1), reader.GetInt32(2), + reader.GetBoolean(3), reader.GetBoolean(4), reader.GetString(5))); + if (!actualCallers.SequenceEqual(function.Triggers)) issues.Add(function.Name + ":trigger-callers"); + } + return issues; + } + + private static CanonicalFunction[] CompiledFunctions() + { + // Read every compiled Up operation in the same order as the EF migrator, + // including central installers and later body-only replacements. + using var context = new IdentityDbContext(new DbContextOptionsBuilder() + .UseNpgsql("Host=model-only;Database=model-only;Username=model-only").Options, + StaticTenantContextAccessor.Unresolved, EmptyIdentityScope.Instance); + var assembly = context.GetService(); + var migrationSql = assembly.Migrations.OrderBy(pair => pair.Key, StringComparer.Ordinal) + .Select(pair => string.Join("\n", assembly.CreateMigration(pair.Value, context.Database.ProviderName!).UpOperations + .OfType().Select(operation => operation.Sql))).ToArray(); + migrationSql.Should().NotBeEmpty("the actual Identity migration assembly is the function census source"); + var sql = string.Join("\n", migrationSql); + var functions = EffectiveFunctionDeclarations(sql).Select(match => + { + var name = match.Groups["name"].Value.ToLowerInvariant(); + var parameters = FunctionParameters(match); + var types = parameters.Select(parameter => parameter[(parameter.IndexOf(' ') + 1)..]).ToArray(); + var attributes = Regex.Replace(match.Groups["attributes"].Value, @"\s+", " ").ToUpperInvariant(); + var triggers = TriggerDeclaration().Matches(sql).Where(trigger => trigger.Groups["function"].Value == name) + .Select(trigger => new TriggerContract(trigger.Groups["name"].Value, "public." + trigger.Groups["table"].Value, + (trigger.Groups["attributes"].Value.Contains("FOR EACH ROW", StringComparison.Ordinal) ? 1 : 0) + | (trigger.Groups["timing"].Value == "BEFORE" ? 2 : 0) + | (trigger.Groups["events"].Value.Split(" OR ", StringSplitOptions.TrimEntries).Aggregate(0, (mask, command) => mask | (command switch { "INSERT" => 4, "DELETE" => 8, "UPDATE" => 16, "TRUNCATE" => 32, _ => 0 }))), + trigger.Groups["attributes"].Value.Contains("DEFERRABLE", StringComparison.Ordinal), + trigger.Groups["attributes"].Value.Contains("INITIALLY DEFERRED", StringComparison.Ordinal), "O")) + .OrderBy(trigger => trigger.Name, StringComparer.Ordinal).ToArray(); + return new CanonicalFunction(name, "public." + name + "(" + string.Join(',', types) + ")", + string.Join(", ", parameters), + match.Groups["returns"].Value.ToLowerInvariant(), attributes.Contains("SECURITY DEFINER", StringComparison.Ordinal), + sql.Contains("GRANT EXECUTE ON FUNCTION public." + name + "(", StringComparison.Ordinal), + match.Groups["body"].Value, match.Value, triggers, + FunctionLanguage().Match(attributes).Groups[1].Value.ToLowerInvariant(), + attributes.Contains("IMMUTABLE", StringComparison.Ordinal) ? "i" + : attributes.Contains("STABLE", StringComparison.Ordinal) ? "s" : "v", + attributes.Contains("STRICT", StringComparison.Ordinal)); + }).OrderBy(function => function.Name, StringComparer.Ordinal).ToArray(); + functions.Should().HaveCount(12, "all applied Identity migrations retain the complete global/contextual function set"); + functions.Count(function => function.Definer).Should().Be(5); + functions.SelectMany(function => function.Triggers).Should().HaveCount(18); + 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"); + foreach (var function in functions) + { + var forbidden = globalNames.Contains(function.Name) ? ForbiddenFunctionBody() : ContextualForbiddenFunctionBody(); + forbidden.IsMatch(function.Body).Should().BeFalse( + "the canonical body admits no dynamic SQL, authority setters, or row-returning reader"); + } + return functions; + } + + private static async Task InstallAuthorityAsync(string connectionString) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); + await using var insert = new NpgsqlCommand("INSERT INTO public.identity_authority(id,authority_id,issuer) VALUES(1,@authority,@issuer)", owner); + insert.Parameters.AddWithValue("authority", GlobalIdentitySchemaFixture.Authority.Value); + insert.Parameters.AddWithValue("issuer", GlobalIdentitySchemaFixture.Issuer); + await insert.ExecuteNonQueryAsync(); + } + + private static async Task MissingEvidenceAsync(string connectionString, GlobalIdentitySubject subject) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); + await using var transaction = await app.BeginTransactionAsync(); + await AnnounceAsync(app, transaction, subject); + return await EvidenceAsync(app, transaction, subject, Guid.CreateVersion7(), Guid.CreateVersion7(), + DateTimeOffset.UtcNow, "identity-bootstrap", "success"); + } + + private static async Task InsertOrphanAsync(string connectionString, GlobalIdentitySubject subject) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); + await using var transaction = await app.BeginTransactionAsync(); + await AnnounceAsync(app, transaction, subject); + await InsertUserAsync(app, transaction, subject, Guid.CreateVersion7(), Guid.CreateVersion7(), DateTimeOffset.UtcNow); + await transaction.CommitAsync(); + } + + private sealed record CanonicalFunction(string Name, string Signature, string IdentityArguments, string ReturnType, + bool Definer, bool AppCallable, string Body, string Definition, TriggerContract[] Triggers, string Language, string Volatility, bool Strict); + private sealed record TriggerContract(string Name, string Table, int Type, bool Deferrable, bool InitiallyDeferred, string Enabled); + + [GeneratedRegex(@"\bCREATE\s+(?OR\s+REPLACE\s+)?FUNCTION\s+public\.(?[a-z0-9_]+)\s*\((?[^)]*)\)\s+RETURNS\s+(?[a-z]+)\s+(?.*?)\bAS\s+(?\$[a-z0-9_]*\$)(?.*?)\k\s*;", RegexOptions.IgnoreCase | RegexOptions.Singleline)] + private static partial Regex FunctionDeclaration(); + [GeneratedRegex(@"LANGUAGE\s+(\w+)", RegexOptions.IgnoreCase)] + private static partial Regex FunctionLanguage(); + [GeneratedRegex(@"CREATE (?CONSTRAINT )?TRIGGER (?\w+)\s+(?BEFORE|AFTER)\s+(?(?:INSERT|UPDATE|DELETE|TRUNCATE)(?:\s+OR\s+(?:INSERT|UPDATE|DELETE|TRUNCATE))*) ON public\.(?\w+)(?.*?)EXECUTE FUNCTION public\.(?\w+)\(\);", RegexOptions.IgnoreCase | RegexOptions.Singleline)] + private static partial Regex TriggerDeclaration(); + [GeneratedRegex(@"\bEXECUTE\b|\bset_config\s*\(|\bRETURN\s+QUERY\b|\bSELECT\s+(?!1\b)", RegexOptions.IgnoreCase)] + private static partial Regex ForbiddenFunctionBody(); + [GeneratedRegex(@"\bEXECUTE\b|\bset_config\s*\(|\bRETURN\s+QUERY\b|\bpg_(?:try_)?advisory_(?:xact_)?lock(?:_shared)?\s*\(", RegexOptions.IgnoreCase)] + private static partial Regex ContextualForbiddenFunctionBody(); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.FunctionDeclarations.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.FunctionDeclarations.cs new file mode 100644 index 000000000..79a8b3819 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.FunctionDeclarations.cs @@ -0,0 +1,116 @@ +using System.Text.RegularExpressions; +using FluentAssertions; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class GlobalIdentitySchemaTests +{ + // Deliberately bounded to the installed named-input functions. Unsupported + // declarations fail instead of vanishing from the effective function census. + private static Match[] EffectiveFunctionDeclarations(string sql) + { + var declarations = FunctionDeclaration().Matches(sql).ToArray(); + if (FunctionMutationStart().Matches(sql).Any(start => !declarations.Any(declaration => declaration.Index == start.Index))) + throw new FormatException("Unsupported function declaration or removal."); + + var effective = new Dictionary(StringComparer.Ordinal); + foreach (var declaration in declarations) + { + var parameters = FunctionParameters(declaration); + var signature = declaration.Groups["name"].Value.ToLowerInvariant() + "(" + + string.Join(',', parameters.Select(parameter => parameter[(parameter.IndexOf(' ') + 1)..])) + ")"; + var exists = effective.TryGetValue(signature, out var previous); + if (declaration.Groups["replace"].Success) + { + if (!exists) + throw new FormatException("Replacement has no earlier function declaration."); + if (!parameters.SequenceEqual(FunctionParameters(previous!)) + || !string.Equals(declaration.Groups["returns"].Value, previous!.Groups["returns"].Value, StringComparison.OrdinalIgnoreCase)) + throw new FormatException("Replacement changes the function arguments or return type."); + } + else if (exists) + { + throw new FormatException("Duplicate CREATE FUNCTION declaration."); + } + effective[signature] = declaration; + } + return effective.Values.ToArray(); + } + + private static string[] FunctionParameters(Match declaration) + { + var parameters = declaration.Groups["parameters"].Value.Trim(); + if (parameters.Length == 0) return []; + return parameters.Split(',').Select(parameter => + { + var normalized = Regex.Replace(parameter.Trim(), @"\s+", " ").ToLowerInvariant(); + if (!FunctionParameter().IsMatch(normalized)) + throw new FormatException("Unsupported function parameter declaration."); + return normalized.Replace(" timestamptz", " timestamp with time zone", StringComparison.Ordinal); + }).ToArray(); + } + + [Fact] + public void Compiled_function_reader_uses_the_last_replacement_of_the_same_normalized_signature() + { + const string original = """ + CREATE FUNCTION public.fn_replacement_probe(at timestamptz) RETURNS boolean + LANGUAGE sql SECURITY INVOKER SET search_path=pg_catalog AS $$ SELECT false $$; + """; + const string first = """ + CREATE OR REPLACE FUNCTION public.fn_replacement_probe(at timestamp with time zone) RETURNS boolean + LANGUAGE sql SECURITY INVOKER SET search_path=pg_catalog AS $$ SELECT true $$; + """; + const string last = """ + CREATE OR REPLACE FUNCTION PUBLIC.FN_REPLACEMENT_PROBE( at TIMESTAMPTZ ) RETURNS boolean + LANGUAGE sql SECURITY INVOKER SET search_path=pg_catalog AS $$ SELECT at IS NOT NULL $$; + """; + + EffectiveFunctionDeclarations(original).Single().Groups["body"].Value.Trim().Should().Be("SELECT false"); + EffectiveFunctionDeclarations(original + first).Single().Groups["body"].Value.Trim().Should().Be("SELECT true"); + EffectiveFunctionDeclarations(original + first + last).Single().Groups["body"].Value.Trim().Should().Be("SELECT at IS NOT NULL"); + EffectiveFunctionDeclarations(original + last + first).Single().Groups["body"].Value.Trim().Should().Be("SELECT true", + "migration order, not declaration spelling or the first match, determines the effective body"); + } + + [Theory] + [InlineData("duplicate-create", "Duplicate CREATE FUNCTION declaration.")] + [InlineData("unknown-replacement", "Replacement has no earlier function declaration.")] + [InlineData("changed-input-type", "Replacement has no earlier function declaration.")] + [InlineData("changed-input-name", "Replacement changes the function arguments or return type.")] + [InlineData("changed-return-type", "Replacement changes the function arguments or return type.")] + [InlineData("unqualified-function", "Unsupported function declaration or removal.")] + [InlineData("default-argument", "Unsupported function parameter declaration.")] + [InlineData("drop-function", "Unsupported function declaration or removal.")] + public void Compiled_function_reader_rejects_unsupported_replacements_and_a_clean_twin_passes(string fault, string expected) + { + const string original = """ + CREATE FUNCTION public.fn_replacement_probe(target uuid) RETURNS boolean + LANGUAGE sql SECURITY INVOKER SET search_path=pg_catalog AS $$ SELECT false $$; + """; + var replacement = original.Replace("CREATE FUNCTION", "CREATE OR REPLACE FUNCTION", StringComparison.Ordinal) + .Replace("SELECT false", "SELECT true", StringComparison.Ordinal); + var mutation = fault switch + { + "duplicate-create" => original, + "unknown-replacement" => replacement.Replace("fn_replacement_probe", "fn_unknown_probe", StringComparison.Ordinal), + "changed-input-type" => replacement.Replace("target uuid", "target text", StringComparison.Ordinal), + "changed-input-name" => replacement.Replace("target uuid", "other uuid", StringComparison.Ordinal), + "changed-return-type" => replacement.Replace("RETURNS boolean", "RETURNS bigint", StringComparison.Ordinal), + "unqualified-function" => replacement.Replace("public.", "", StringComparison.Ordinal), + "default-argument" => replacement.Replace("target uuid", "target uuid DEFAULT NULL", StringComparison.Ordinal), + "drop-function" => "DROP FUNCTION public.fn_replacement_probe(uuid);", + _ => throw new InvalidOperationException("Unknown planted function declaration fault."), + }; + var parse = () => EffectiveFunctionDeclarations(original + mutation); + parse.Should().Throw().WithMessage(expected); + EffectiveFunctionDeclarations(original + replacement).Single().Groups["body"].Value.Trim().Should().Be("SELECT true"); + } + + [GeneratedRegex(@"\b(?:CREATE\s+(?:OR\s+REPLACE\s+)?(?:FUNCTION|PROCEDURE)|DROP\s+(?:FUNCTION|PROCEDURE))\b", RegexOptions.IgnoreCase)] + private static partial Regex FunctionMutationStart(); + + [GeneratedRegex(@"\A[a-z_][a-z0-9_]* (?:uuid|bytea|text|boolean|bigint|integer|timestamptz|timestamp with time zone)\z", RegexOptions.CultureInvariant)] + private static partial Regex FunctionParameter(); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.cs new file mode 100644 index 000000000..f65ec155b --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentitySchemaTests.cs @@ -0,0 +1,367 @@ +using System.Text.Json; +using FluentAssertions; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.EntityFrameworkCore; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// Actual app-role isolation and the three installed global witness contracts. +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed partial class GlobalIdentitySchemaTests(GlobalIdentitySchemaFixture fixture) + : IClassFixture +{ + [Fact] + public async Task Global_Identity_Storage_Is_Subject_Confined() + { + var first = NewSubject(); + var second = NewSubject(); + await InsertPairAsync(first); + await InsertPairAsync(second); + await using var connection = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.AppConnectionString); + await using var transaction = await connection.BeginTransactionAsync(); + await AnnounceAsync(connection, transaction, first); + (await ScalarAsync(connection, transaction, "SELECT count(*) FROM public.users")).Should().Be(1); + + var accessor = new TestScope { Current = new(1, TestSource.Lookup(first)) }; + await using var context = new IdentityDbContext(new DbContextOptionsBuilder() + .UseNpgsql(connection).Options, StaticTenantContextAccessor.Unresolved, accessor); + await context.Database.UseTransactionAsync(transaction); + (await context.Users.AsNoTracking().SingleAsync()).ProviderSubject.Should().Be(first.Subject); + await AnnounceAsync(connection, transaction, second); + (await context.Users.AsNoTracking().CountAsync()).Should().Be(0, + "the independently parameterized EF filter still asks for the first subject"); + accessor.Current = new(2, TestSource.Lookup(second)); + (await context.Users.AsNoTracking().SingleAsync()).ProviderSubject.Should().Be(second.Subject); + accessor.Current = null; + (await context.Users.AsNoTracking().CountAsync()).Should().Be(0); + await ClearAsync(connection, transaction); + (await ScalarAsync(connection, transaction, "SELECT count(*) FROM public.users")).Should().Be(0); + await ExecuteAsync(connection, transaction, """ + SELECT set_config('app.identity_authority_id','not-a-uuid',true), + set_config('app.identity_subject_key','not-a-digest',true) + """); + (await ScalarAsync(connection, transaction, "SELECT count(*) FROM public.users")).Should().Be(0, + "malformed identity settings refuse visibility without parsing caller-controlled values"); + await transaction.RollbackAsync(); + await using var reused = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.AppConnectionString); + (await ScalarAsync(reused, null, "SELECT count(*) FROM public.users")).Should().Be(0); + } + + [Fact] + public async Task Applied_census_has_fifty_five_tables_and_exactly_five_Identity_definers() + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.MigrationConnectionString); + await SchemaTableClasses.AssertCompleteAsync(owner); + (await SchemaTableClasses.ReadAsync(owner)).Should().HaveCount(55); + 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); + names.Should().Equal("fn_identity_admin_admission_state", "fn_identity_audit_creation_guard", "fn_identity_audit_evidence", + "fn_identity_membership_admission_guard", "fn_identity_user_creation_audit_guard"); + (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 + WHERE n.nspname='public' AND p.prosecdef + 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(5); + (await ScalarAsync(owner, null, """ + SELECT count(*) FROM pg_class WHERE oid IN ('public.users'::regclass,'public.identity_authority'::regclass) + AND relrowsecurity AND relforcerowsecurity + """)).Should().Be(2); + } + + [Fact] + public async Task Global_grants_expose_only_self_select_initial_insert_and_exact_evidence() + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.AppConnectionString); + (await ScalarAsync(app, null, "SELECT has_table_privilege(current_user,'public.users','SELECT')")).Should().BeTrue(); + foreach (var privilege in new[] { "UPDATE", "DELETE", "TRUNCATE" }) + (await ScalarAsync(app, null, $"SELECT has_table_privilege(current_user,'public.users','{privilege}')")).Should().BeFalse(); + foreach (var column in new[] { "updated_at", "updated_by", "deleted_at", "deleted_by" }) + (await ScalarAsync(app, null, $"SELECT has_column_privilege(current_user,'public.users','{column}','INSERT')")).Should().BeFalse(); + (await ScalarAsync(app, null, "SELECT count(*) FROM public.identity_authority")).Should().Be(1); + foreach (var privilege in new[] { "INSERT", "UPDATE", "DELETE", "TRUNCATE" }) + (await ScalarAsync(app, null, $"SELECT has_table_privilege(current_user,'public.identity_authority','{privilege}')")).Should().BeFalse(); + (await ScalarAsync(app, null, "SELECT has_function_privilege(current_user,'public.fn_identity_audit_evidence(uuid,timestamptz,uuid,bytea,uuid,text,text)','EXECUTE')")).Should().BeTrue(); + foreach (var function in new[] { "fn_identity_user_creation_audit_guard", "fn_identity_audit_creation_guard" }) + (await ScalarAsync(app, null, $"SELECT has_function_privilege(current_user,'public.{function}()','EXECUTE')")).Should().BeFalse(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Reciprocal_creation_requires_both_exact_success_witnesses(bool auditOnly) + { + var subject = NewSubject(); + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await AnnounceAsync(app, transaction, subject); + var target = Guid.CreateVersion7(); + var audit = Guid.CreateVersion7(); + var at = GlobalIdentityCreationReference.NormalizeTimestamp(DateTimeOffset.UtcNow); + if (auditOnly) await InsertAuditAsync(app, transaction, subject, target, audit, at, "success"); + else await InsertUserAsync(app, transaction, subject, target, audit, at); + var preflight = () => ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + (await preflight.Should().ThrowAsync()).Which.SqlState.Should().Be("23514"); + await transaction.RollbackAsync(); + await AnnounceInFreshReadAsync(subject, 0); + } + + [Fact] + public async Task Evidence_requires_exact_key_subject_target_source_outcome_and_success_relation() + { + var subject = NewSubject(); + var pair = await InsertPairAsync(subject); + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await AnnounceAsync(app, transaction, subject); + (await EvidenceAsync(app, transaction, subject, pair.Target, pair.Audit, pair.At, "identity-bootstrap", "success")).Should().BeTrue(); + (await ScalarAsync(app, transaction, "SELECT count(*) FROM public.audit_log WHERE operation='identity.user.create'")).Should().Be(0, + "global self identity does not grant direct global audit visibility"); + (await EvidenceAsync(app, transaction, subject, pair.Target, pair.Audit, pair.At.AddTicks(10), "identity-bootstrap", "success")).Should().BeFalse(); + (await EvidenceAsync(app, transaction, subject, Guid.CreateVersion7(), pair.Audit, pair.At, "identity-bootstrap", "success")).Should().BeFalse(); + (await EvidenceAsync(app, transaction, subject, pair.Target, pair.Audit, pair.At, "identity-seed-adoption", "success")).Should().BeFalse(); + (await EvidenceAsync(app, transaction, subject, pair.Target, pair.Audit, pair.At, "identity-bootstrap", "failed")).Should().BeFalse(); + await AnnounceAsync(app, transaction, NewSubject()); + (await EvidenceAsync(app, transaction, subject, pair.Target, pair.Audit, pair.At, "identity-bootstrap", "success")).Should().BeFalse(); + } + + [Theory] + [InlineData("failed")] + [InlineData("indeterminate")] + public async Task Non_success_evidence_needs_no_User_and_cannot_satisfy_success(string outcome) + { + var subject = NewSubject(); + var target = Guid.CreateVersion7(); + var audit = Guid.CreateVersion7(); + var at = GlobalIdentityCreationReference.NormalizeTimestamp(DateTimeOffset.UtcNow); + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.AppConnectionString); + await using (var write = await app.BeginTransactionAsync()) + { + await AnnounceAsync(app, write, subject); + await InsertAuditAsync(app, write, subject, target, audit, at, outcome); + await write.CommitAsync(); + } + await using var read = await app.BeginTransactionAsync(); + await AnnounceAsync(app, read, subject); + (await EvidenceAsync(app, read, subject, target, audit, at, "identity-bootstrap", outcome)).Should().BeTrue(); + (await EvidenceAsync(app, read, subject, target, audit, at, "identity-bootstrap", "success")).Should().BeFalse(); + } + + [Theory] + [InlineData("DELETE FROM public.users")] + [InlineData("TRUNCATE public.users, public.memberships, public.membership_profiles, public.membership_role_assignments")] + [InlineData("UPDATE public.users SET status='Closing'")] + public async Task Owner_execution_cannot_remove_or_mutate_the_permanent_binding(string sql) + { + await InsertPairAsync(NewSubject()); + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.MigrationConnectionString); + await using var transaction = await owner.BeginTransactionAsync(); + var mutate = () => ExecuteAsync(owner, transaction, sql); + (await mutate.Should().ThrowAsync()).Which.SqlState.Should().Be("23514"); + } + + [Fact] + public async Task Database_digest_matches_the_network_order_unicode_subject_encoding() + { + var subject = NewSubject("İ-opaque-\U0001f512-"); + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.MigrationConnectionString); + await using var command = new NpgsqlCommand(""" + SELECT encode(sha256(int4send(octet_length(convert_to('learnstack.identity.subject.v1','UTF8'))) + ||convert_to('learnstack.identity.subject.v1','UTF8')||int4send(16)||uuid_send(@authority) + ||int4send(octet_length(convert_to(@subject,'UTF8')))||convert_to(@subject,'UTF8')),'hex') + """, owner); + command.Parameters.AddWithValue("authority", subject.AuthorityId.Value); + command.Parameters.AddWithValue("subject", subject.Subject); + ((string)(await command.ExecuteScalarAsync())!).Should().Be(subject.SubjectKey.Hex); + } + + [Fact] + public async Task Applied_subject_lifecycle_CHECK_allows_nullable_Closing_and_bounds_retained_subjects() + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.MigrationConnectionString); + await using var read = new NpgsqlCommand(""" + SELECT pg_get_expr(conbin,conrelid) FROM pg_constraint + WHERE conrelid='public.users'::regclass AND conname='ck_users_subject_lifecycle' + """, owner); + var expression = (string)(await read.ExecuteScalarAsync())!; + expression.Should().NotBeNullOrWhiteSpace(); + var cases = new (string Status, string? Subject, bool Accepted)[] + { + ("Active", null, false), ("Active", "", false), ("Active", "opaque", true), + ("Active", new string('x', 255), true), ("Active", new string('x', 256), false), + ("Closing", null, true), ("Closing", "", false), ("Closing", "opaque", true), + ("Closing", new string('x', 255), true), ("Closing", new string('x', 256), false), + ("Closed", null, true), ("Closed", "", false), ("Closed", "opaque", false), + ("Closed", new string('x', 255), false), ("Closed", new string('x', 256), false), + }; + foreach (var (status, subject, accepted) in cases) + { + // Evaluate the applied CHECK over parameterized values using PostgreSQL's + // CHECK semantics (NULL passes), without invoking a lifecycle writer. + await using var evaluate = new NpgsqlCommand($""" + SELECT ({expression}) IS NOT FALSE + FROM (VALUES (@status::text,@subject::text)) AS candidate(status,provider_subject) + """, owner); + evaluate.Parameters.AddWithValue("status", status); + evaluate.Parameters.AddWithValue("subject", NpgsqlTypes.NpgsqlDbType.Text, (object?)subject ?? DBNull.Value); + ((bool)(await evaluate.ExecuteScalarAsync())!).Should().Be(accepted, + $"{status} with subject length {subject?.Length.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "NULL"} must follow its retained-subject contract"); + } + } + + private static GlobalIdentitySubject NewSubject(string prefix = "opaque-") => + new(GlobalIdentitySchemaFixture.Authority, GlobalIdentitySchemaFixture.Issuer, prefix + Guid.NewGuid().ToString("N")); + + private Task<(Guid Target, Guid Audit, DateTimeOffset At)> InsertPairAsync(GlobalIdentitySubject subject) => + InsertPairAsync(fixture.Postgres.AppConnectionString, subject); + + private static async Task<(Guid Target, Guid Audit, DateTimeOffset At)> InsertPairAsync( + string connectionString, GlobalIdentitySubject subject) + { + var target = Guid.CreateVersion7(); + var audit = Guid.CreateVersion7(); + var at = GlobalIdentityCreationReference.NormalizeTimestamp(DateTimeOffset.UtcNow); + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); + await using var transaction = await app.BeginTransactionAsync(); + await AnnounceAsync(app, transaction, subject); + await InsertUserAsync(app, transaction, subject, target, audit, at); + await InsertAuditAsync(app, transaction, subject, target, audit, at, "success"); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await transaction.CommitAsync(); + return (target, audit, at); + } + + private async Task AnnounceInFreshReadAsync(GlobalIdentitySubject subject, long expected) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await AnnounceAsync(app, transaction, subject); + (await ScalarAsync(app, transaction, "SELECT count(*) FROM public.users")).Should().Be(expected); + } + + private static async Task InsertUserAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, + GlobalIdentitySubject subject, Guid target, Guid audit, DateTimeOffset at) + { + await using var command = new NpgsqlCommand(""" + INSERT INTO public.users(id,authority_id,subject_key,provider_subject,status,creation_audit_id, + creation_audit_timestamp,created_at,created_by,row_version) + VALUES(@target,@authority,@key,@subject,'Active',@audit,@at,@at,@actor,0) + """, connection, transaction); + command.Parameters.AddWithValue("target", target); + command.Parameters.AddWithValue("authority", subject.AuthorityId.Value); + command.Parameters.AddWithValue("key", subject.SubjectKey.ToByteArray()); + command.Parameters.AddWithValue("subject", subject.Subject); + command.Parameters.AddWithValue("audit", audit); + command.Parameters.AddWithValue("at", at); + command.Parameters.AddWithValue("actor", UserId.SystemActor.Value); + await command.ExecuteNonQueryAsync(); + } + + private static async Task InsertAuditAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, + GlobalIdentitySubject subject, Guid target, Guid audit, DateTimeOffset at, string outcome) + { + 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,metadata) + VALUES(@audit,@at,@sentinel,NULL,NULL,'identity','identity.user.create','SecurityEvent','Must','User',@target,@outcome,@metadata::jsonb) + """, connection, transaction); + command.Parameters.AddWithValue("audit", audit); + command.Parameters.AddWithValue("at", at); + command.Parameters.AddWithValue("sentinel", TenantId.PlatformSentinel.Value); + command.Parameters.AddWithValue("target", target.ToString("D")); + command.Parameters.AddWithValue("outcome", outcome); + 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(); + } + + internal static async Task AnnounceAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, + GlobalIdentitySubject subject) + { + await ClearAsync(connection, transaction); + await using var command = new NpgsqlCommand(""" + SELECT set_config('app.identity_authority_id',@authority,true),set_config('app.identity_subject_key',@key,true) + """, connection, transaction); + command.Parameters.AddWithValue("authority", subject.AuthorityId.Value.ToString("D")); + command.Parameters.AddWithValue("key", subject.SubjectKey.Hex); + await command.ExecuteNonQueryAsync(); + } + + private static Task ClearAsync(NpgsqlConnection connection, NpgsqlTransaction transaction) => ExecuteAsync(connection, transaction, """ + SELECT set_config('app.tenant_id','',true),set_config('app.organization_id','',true),set_config('app.scope','',true), + set_config('app.resolving_host','',true),set_config('app.identity_authority_id','',true), + set_config('app.identity_subject_key','',true) + """); + + private static async Task EvidenceAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, + GlobalIdentitySubject subject, Guid target, Guid audit, DateTimeOffset at, string source, string outcome) + { + await using var command = new NpgsqlCommand("SELECT public.fn_identity_audit_evidence(@audit,@at,@authority,@key,@target,@source,@outcome)", connection, transaction); + command.Parameters.AddWithValue("audit", audit); + command.Parameters.AddWithValue("at", at); + command.Parameters.AddWithValue("authority", subject.AuthorityId.Value); + command.Parameters.AddWithValue("key", subject.SubjectKey.ToByteArray()); + command.Parameters.AddWithValue("target", target); + command.Parameters.AddWithValue("source", source); + command.Parameters.AddWithValue("outcome", outcome); + return (bool)(await command.ExecuteScalarAsync())!; + } + + private static async Task ExecuteAsync(NpgsqlConnection connection, NpgsqlTransaction? transaction, string sql) + { + await using var command = new NpgsqlCommand(sql, connection, transaction); + await command.ExecuteNonQueryAsync(); + } + + private static async Task ScalarAsync(NpgsqlConnection connection, NpgsqlTransaction? transaction, string sql) + { + await using var command = new NpgsqlCommand(sql, connection, transaction); + return (T)(await command.ExecuteScalarAsync())!; + } + + private sealed class TestScope : IGlobalIdentityScopeAccessor + { + public GlobalIdentityContextAnnouncement? Current { get; set; } + } + + private sealed class TestSource : GlobalIdentityOwnerDescriptor.MintingSource + { + public static GlobalIdentityOwnerDescriptor Lookup(GlobalIdentitySubject subject) => + ForLookup(subject, typeof(IdentityDbContext), typeof(User)); + } +} + +public sealed class GlobalIdentitySchemaFixture : IAsyncLifetime +{ + public static IdentityAuthorityId Authority { get; } = IdentityAuthorityId.From(Guid.Parse("a91a3552-0000-4000-8000-000000000001")); + public const string Issuer = "https://identity-schema.invalid/realms/learnstack"; + public PostgresFixture Postgres { get; } = new(); + + public async Task InitializeAsync() + { + await Postgres.InitializeAsync(); + await MigrationChains.ApplyAllAsync(Postgres.MigrationConnectionString); + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(Postgres.MigrationConnectionString); + await using var command = new NpgsqlCommand("INSERT INTO public.identity_authority(id,authority_id,issuer) VALUES(1,@authority,@issuer)", owner); + command.Parameters.AddWithValue("authority", Authority.Value); + command.Parameters.AddWithValue("issuer", Issuer); + await command.ExecuteNonQueryAsync(); + } + + public Task DisposeAsync() => Postgres.DisposeAsync(); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityUnitOfWorkTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityUnitOfWorkTests.cs new file mode 100644 index 000000000..29dae3ef2 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/GlobalIdentityUnitOfWorkTests.cs @@ -0,0 +1,178 @@ +using System.Data.Common; +using FluentAssertions; +using LearnStack.Infrastructure.Persistence; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Errors; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed class GlobalIdentityUnitOfWorkTests(SchemaFixture schema) +{ + private static readonly GlobalIdentitySubject Subject = new( + IdentityAuthorityId.From(Guid.Parse("019a1929-5450-7bbb-8df1-516e8e002501")), + "https://identity.example/realms/learnstack", "unit-owner-proof-subject"); + + [Fact] + public async Task Read_only_global_owner_announces_only_self_authority_and_clears_unrelated_session_values() + { + await using var source = ApplicationDataSource.Build(schema.Postgres.AppConnectionString); + await using var unit = Unit(source); + foreach (var name in new[] { "app.tenant_id", "app.organization_id", "app.scope", "app.resolving_host" }) + await ScalarAsync(unit, "SELECT set_config(@name, 'stale-session-value', false)", ("name", name)); + var descriptor = ProofMint.Lookup(Subject); + await using var frame = await unit.BeginGlobalIdentityTransactionAsync(descriptor, TransactionMode.ReadOnly); + frame.IsOwner.Should().BeTrue(); + (await ScalarAsync(unit, "SHOW transaction_isolation")).Should().Be("read committed"); + (await ScalarAsync(unit, "SHOW transaction_read_only")).Should().Be("on"); + foreach (var name in new[] { "app.tenant_id", "app.organization_id", "app.scope", "app.resolving_host" }) + (await ScalarAsync(unit, "SELECT current_setting(@name, true)", ("name", name))).Should().BeEmpty(); + (await ScalarAsync(unit, "SELECT current_setting('app.identity_authority_id', true)")) + .Should().Be(Subject.AuthorityId.Value.ToString("D")); + (await ScalarAsync(unit, "SELECT current_setting('app.identity_subject_key', true)")) + .Should().Be(Subject.SubjectKey.Hex); + unit.IsTenantContextIssuedOn(unit.Transaction).Should().BeFalse(); + unit.GetTenantContextAnnouncement(unit.Transaction).Should().BeNull(); + unit.GetGlobalIdentityAnnouncement(unit.Transaction)!.Descriptor.Should().BeSameAs(descriptor); + await frame.CompleteAsync(); + unit.IsGlobalIdentityTransaction.Should().BeFalse(); + unit.GetGlobalIdentityAnnouncement(unit.Transaction).Should().BeNull(); + } + + [Fact] + public async Task Only_the_exact_enrolled_context_can_issue_commands_and_validation_seals_it_before_commit() + { + await using var source = ApplicationDataSource.Build(schema.Postgres.AppConnectionString); + await using var unit = Unit(source); + var descriptor = ProofMint.Creation(Subject); + await using var frame = await unit.BeginGlobalIdentityTransactionAsync(descriptor, TransactionMode.ReadWrite); + await using var context = Context(unit); + var beforeLock = () => unit.EnrollGlobalIdentityContext(context, descriptor); + beforeLock.Should().Throw(); + await unit.AcquireGlobalIdentitySubjectLockAsync(descriptor); + unit.EnrollGlobalIdentityContext(context, descriptor); + await using var foreign = Context(unit); + var replace = () => unit.EnrollGlobalIdentityContext(foreign, descriptor); + replace.Should().Throw(); + (await context.Database.SqlQueryRaw("SELECT 1 AS \"Value\"").SingleAsync()).Should().Be(1); + await FluentActions.Awaiting(() => foreign.Database.SqlQueryRaw("SELECT 1 AS \"Value\"").SingleAsync()) + .Should().ThrowAsync() + .WithMessage("The command does not belong to the enrolled global identity context."); + await unit.ValidateGlobalIdentityConstraintsAsync(descriptor); + unit.IsGlobalIdentityContextEnrolled(context, unit.Transaction).Should().BeFalse(); + await FluentActions.Awaiting(() => context.Database.SqlQueryRaw("SELECT 1 AS \"Value\"").SingleAsync()) + .Should().ThrowAsync() + .WithMessage("The command does not belong to the enrolled global identity context."); + await frame.CompleteAsync(); + unit.IsRollbackOnly.Should().BeFalse(); + } + + [Theory] + [InlineData("begin")] + [InlineData("tenant")] + [InlineData("provision")] + public async Task Ordinary_entries_cannot_join_or_retarget_a_global_owner(string entry) + { + await using var source = ApplicationDataSource.Build(schema.Postgres.AppConnectionString); + await using var unit = Unit(source); + await using var frame = await unit.BeginGlobalIdentityTransactionAsync(ProofMint.Creation(Subject), TransactionMode.ReadWrite); + Func invalid = entry switch + { + "tenant" => () => unit.SetTenantContextAsync(UnresolvedTenantContext.Instance), + "provision" => () => unit.SetProvisioningTenantContextAsync(TenantId.From(SchemaFixture.TenantA)), + _ => async () => { await unit.BeginTransactionAsync(); } + , + }; + await invalid.Should().ThrowAsync(); + unit.IsRollbackOnly.Should().BeTrue(); + unit.IsTenantContextIssuedOn(unit.Transaction).Should().BeFalse(); + } + + [Fact] + public async Task Global_entry_cannot_join_an_ordinary_transaction() + { + await using var source = ApplicationDataSource.Build(schema.Postgres.AppConnectionString); + await using var unit = Unit(source); + await using var frame = await unit.BeginTransactionAsync(); + await unit.SetProvisioningTenantContextAsync(TenantId.From(SchemaFixture.TenantA)); + await FluentActions.Awaiting(() => unit.BeginGlobalIdentityTransactionAsync(ProofMint.Lookup(Subject), TransactionMode.ReadOnly)) + .Should().ThrowAsync(); + unit.IsRollbackOnly.Should().BeTrue(); + unit.GetGlobalIdentityAnnouncement(unit.Transaction).Should().BeNull(); + } + + [Fact] + public async Task A_creation_owner_without_final_constraint_validation_rolls_back_before_physical_commit() + { + await using var source = ApplicationDataSource.Build(schema.Postgres.AppConnectionString); + await using var unit = Unit(source); + await using var frame = await unit.BeginGlobalIdentityTransactionAsync(ProofMint.Creation(Subject), TransactionMode.ReadWrite); + await FluentActions.Awaiting(() => frame.CompleteAsync()).Should().ThrowAsync(); + unit.HasActiveTransaction.Should().BeFalse(); + unit.IsRollbackOnly.Should().BeTrue(); + unit.GetGlobalIdentityAnnouncement(unit.Transaction).Should().BeNull(); + } + + [Fact] + public async Task A_later_generation_has_no_stale_global_enrollment_or_identity_session_authority() + { + await using var source = ApplicationDataSource.Build(schema.Postgres.AppConnectionString); + await using var unit = Unit(source); + var first = await unit.BeginGlobalIdentityTransactionAsync(ProofMint.Lookup(Subject), TransactionMode.ReadOnly); + var old = unit.GetGlobalIdentityAnnouncement(unit.Transaction)!; + var oldTransaction = unit.Transaction; + await using var context = Context(unit); + unit.EnrollGlobalIdentityContext(context, old.Descriptor); + await first.CompleteAsync(); + await using var later = await unit.BeginTransactionAsync(); + await unit.SetProvisioningTenantContextAsync(TenantId.From(SchemaFixture.TenantA)); + unit.GetTenantContextAnnouncement(unit.Transaction)!.Generation.Should().BeGreaterThan(old.Generation); + unit.GetGlobalIdentityAnnouncement(oldTransaction).Should().BeNull(); + unit.IsGlobalIdentityContextEnrolled(context, unit.Transaction).Should().BeFalse(); + (await ScalarAsync(unit, "SELECT current_setting('app.identity_authority_id', true)")).Should().BeEmpty(); + (await ScalarAsync(unit, "SELECT current_setting('app.identity_subject_key', true)")).Should().BeEmpty(); + await first.DisposeAsync(); + unit.HasActiveTransaction.Should().BeTrue(); + } + + private static NpgsqlUnitOfWork Unit(NpgsqlDataSource source) => new(source, NullLogger.Instance); + + private static ProofContext Context(NpgsqlUnitOfWork unit) + { + var context = new ProofContext(new DbContextOptionsBuilder() + .UseNpgsql(unit.Connection).AddInterceptors(new TenantContextGuardInterceptor(unit)).Options); + context.Database.UseTransaction(unit.Transaction); + return context; + } + + private static async Task ScalarAsync(NpgsqlUnitOfWork unit, string sql, params (string Key, string Value)[] values) + { + await using var command = unit.Connection.CreateCommand(); + command.Transaction = unit.Transaction; + command.CommandText = sql; + foreach (var value in values) + { + var parameter = command.CreateParameter(); + parameter.ParameterName = value.Key; + parameter.Value = value.Value; + command.Parameters.Add(parameter); + } + return Convert.ToString(await command.ExecuteScalarAsync(), System.Globalization.CultureInfo.InvariantCulture)!; + } + + private sealed class ProofContext(DbContextOptions options) : DbContext(options); + private sealed class ProofEntity; + private sealed class ProofMint : GlobalIdentityOwnerDescriptor.MintingSource + { + public static GlobalIdentityOwnerDescriptor Lookup(GlobalIdentitySubject subject) => ForLookup(subject, typeof(ProofContext), typeof(ProofEntity)); + public static GlobalIdentityOwnerDescriptor Creation(GlobalIdentitySubject subject) => ForBootstrap(subject, typeof(ProofContext), typeof(ProofEntity)); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityCommandQualificationTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityCommandQualificationTests.cs new file mode 100644 index 000000000..6ffedc962 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityCommandQualificationTests.cs @@ -0,0 +1,449 @@ +using System.Diagnostics; +using System.Diagnostics.Metrics; +using System.Text; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.Tools.Seeder; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; +using Xunit; +using Xunit.Abstractions; + +namespace LearnStack.Tests.Integration.Database; + +/// Small local command-path observations, not production capacity or a historical baseline. +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed class IdentityCommandQualificationTests(SchemaFixture schema, ITestOutputHelper output) +{ + private const int PoolCapacity = 4; + private const int WriteBudgetMilliseconds = 500; + private static readonly IdentityAuthorityRegistration Authority = new( + IdentityAuthorityId.From(Guid.Parse("01930000-0000-7000-8000-000000009901")), + "https://command-qualification.invalid/realms/learnstack"); + + [Fact] + public async Task Actual_seed_commands_measure_local_observation_cost_and_pool_occupancy_with_a_real_membership_wait() + { + var counterfactual = await MeasureAsync(removeObservationCost: true); + var guarded = await MeasureAsync(removeObservationCost: false); + output.WriteLine(JsonSerializer.Serialize(new + { + CurrentCodeObservationCostCounterfactual = counterfactual, + ProductionGuards = guarded, + WarmP95DeltaMilliseconds = guarded.WarmP95Milliseconds - counterfactual.WarmP95Milliseconds, + SqlCommandCountDelta = guarded.Samples.Sum(sample => sample.SqlCommands) + - counterfactual.Samples.Sum(sample => sample.SqlCommands), + WriteBudgetMilliseconds, + ColdDefinition = "first_invocation_per_command_type_not_process_or_pool_cold", + WarmDefinition = "subsequent_invocations_per_command_type", + SqlCostDefinition = "client_command_spans_include_server_trigger_time_not_internal_statement_counts", + NoHistoricalBaselineClaim = true, + NoProductionCapacityClaim = true, + })); + } + + private async Task MeasureAsync(bool removeObservationCost) + { + await using var database = await DisposableSchemaDatabase.CreateAsync(schema.Postgres); + await using (var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString)) + await IdentityAuthorityDeploymentInstaller.InstallAsync(owner, Authority); + var original = await FunctionsAsync(database); + original.Definers.Length.Should().Be(5); + // This twin retains every current coordinator, transaction, lock acquisition, + // trigger and write. Only the heldness observation body changes. It is not a + // security qualification or a reconstruction of any previously shipped code. + try + { + if (removeObservationCost) + { + var replacement = original.Definition.Replace(original.Source, "SELECT TRUE;", StringComparison.Ordinal); + (replacement != original.Definition).Should().BeTrue(); + await DeploymentAsync(database, replacement); + var changed = await FunctionsAsync(database); + (changed.Source.Trim() == "SELECT TRUE;").Should().BeTrue("the counterfactual has the fixed body only"); + (changed.Metadata == original.Metadata).Should().BeTrue("only the observation body changes"); + changed.Definers.SequenceEqual(original.Definers, StringComparer.Ordinal).Should().BeTrue(); + } + var connectionString = new NpgsqlConnectionStringBuilder(database.AppConnectionString) + { + Pooling = true, + MaxPoolSize = PoolCapacity, + MinPoolSize = 0, + ApplicationName = "identity-command-qualification", + }.ConnectionString; + await using var source = ApplicationDataSource.Build(connectionString); + await new SeedRunner(context => SeedComposition.Build(source, context, NullLoggerFactory.Instance), + NullLogger.Instance).RunAsync(CancellationToken.None); + var witness = await WitnessAsync(); + var admission = new FixedSeedIdentityFoundationAdmission(witness); + // Npgsql's default pool name is its redacted connection string. Match it + // privately; neither this value nor any received raw tag is retained in output. + using var capture = new CommandCapture(source.ConnectionString); + using var logs = LoggerFactory.Create(builder => builder.AddProvider(capture)); + var runner = new SeedIdentityFoundationRunner(context => SeedComposition.Build(source, context, logs, + identityAuthority: Authority, seedAdmission: admission), admission); + await RunWithObservedWaitAsync(database, source, runner, capture); + capture.ObservePool(); + var samples = capture.Samples(); + samples.Length.Should().Be(24, "sixteen Role, four Membership and four profile acts really committed"); + samples.Count(sample => sample.Command == nameof(InitializeSeedRoleCommand)).Should().Be(16); + samples.Count(sample => sample.Command == nameof(CreateFirstSeedAdminMembershipCommand)).Should().Be(2); + samples.Count(sample => sample.Command == nameof(CreateSeedMembershipCommand)).Should().Be(2); + samples.Count(sample => sample.Command == nameof(SetSeedMembershipProfileCommand)).Should().Be(4); + samples.Count(sample => sample.Cold).Should().Be(4); + samples.Should().OnlyContain(sample => sample.ElapsedMilliseconds >= 0 && sample.SqlCommands > 0 + && double.IsFinite(sample.SqlMilliseconds) && sample.SqlMilliseconds >= 0); + capture.MaximumBusy.Should().BeInRange(2, PoolCapacity, + "the same measured pool held the blocker and the real waiting command"); + capture.FinalBusy.Should().Be(0, "all actual command and blocker leases returned after COMMIT"); + capture.PoolObservations.Should().BeGreaterThan(0); + capture.MaximumAcquiredUserWaitMilliseconds.Should().BeGreaterThan(0); + await AssertCommittedGraphsAsync(database); + var warmP95 = Percentile95(samples.Where(sample => !sample.Cold).Select(sample => (double)sample.ElapsedMilliseconds)); + return new(samples, samples.Count(sample => sample.Cold), samples.Count(sample => !sample.Cold), + warmP95, warmP95 < WriteBudgetMilliseconds, + Percentile95(samples.Where(sample => sample.Cold).Select(sample => (double)sample.ElapsedMilliseconds)), + Percentile95(samples.Select(sample => sample.SqlMilliseconds)), capture.MaximumBusy, + capture.FinalBusy, capture.PoolObservations, capture.MaximumAcquiredUserWaitMilliseconds, PoolCapacity); + } + finally + { + if (removeObservationCost) await DeploymentAsync(database, original.Definition); + var restored = await FunctionsAsync(database); + (restored.Definition == original.Definition && restored.Source == original.Source + && restored.Metadata == original.Metadata).Should().BeTrue("the exact observation function is restored"); + restored.Definers.SequenceEqual(original.Definers, StringComparer.Ordinal).Should().BeTrue( + "all five SECURITY DEFINER definitions, owners and ACLs remain exact"); + } + // await using drops each isolated database, including on failed qualification. + } + + private static async Task RunWithObservedWaitAsync(DisposableSchemaDatabase database, NpgsqlDataSource source, + SeedIdentityFoundationRunner runner, CommandCapture capture) + { + var first = SeedData.IdentityMemberships.First(member => member.IsFirstAdmin); + var key = IdentityAdvisoryLockKey.ForUser(first.Identity.UserId); + await using var blocker = await source.OpenConnectionAsync(); + await SchemaQueries.AssertApplicationRoleAsync(blocker); + await using var transaction = await blocker.BeginTransactionAsync(); + await IdentityMembershipFixture.ExecuteAsync(blocker, transaction, + "SELECT pg_catalog.pg_advisory_xact_lock(@key)", ("key", key)); + using var budget = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + using var activity = capture.Enter(); + var running = runner.RunAsync(budget.Token); + try + { + await using var observer = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await ObserveWaitAsync(observer, blocker.ProcessID, key, running, budget.Token); + // The delay follows an observed server wait; it does not stand in for proof + // that the actual coordinator's User acquisition reached PostgreSQL. + await Task.Delay(50, budget.Token); + } + finally + { + await transaction.CommitAsync(CancellationToken.None); + await running.WaitAsync(TimeSpan.FromSeconds(15)); + } + } + + private static async Task ObserveWaitAsync(NpgsqlConnection observer, int blocker, long key, + Task running, CancellationToken cancellationToken) + { + var deadline = Stopwatch.StartNew(); + while (deadline.Elapsed < TimeSpan.FromSeconds(15)) + { + if (running.IsCompleted) + { + await running; + throw new InvalidOperationException("The command completed before the required competing advisory wait."); + } + await using var command = new NpgsqlCommand(""" + SELECT EXISTS ( + SELECT 1 FROM pg_catalog.pg_locks held + JOIN pg_catalog.pg_stat_activity activity ON activity.pid=held.pid + WHERE held.pid<>@blocker AND held.locktype='advisory' AND NOT held.granted + AND held.database=(SELECT oid FROM pg_catalog.pg_database WHERE datname=current_database()) + AND held.objsubid=1 AND held.mode='ExclusiveLock' + AND ((held.classid::bigint << 32) | held.objid::bigint)=@key + AND activity.usename=current_user + AND activity.wait_event_type='Lock' AND activity.wait_event='advisory') + """, observer) { CommandTimeout = 5 }; + command.Parameters.AddWithValue("blocker", blocker); + command.Parameters.AddWithValue("key", key); + if (await command.ExecuteScalarAsync(cancellationToken) is true) return; + await Task.Delay(10, cancellationToken); + } + throw new InvalidOperationException("The actual command never entered the required PostgreSQL advisory wait."); + } + + private static async Task WitnessAsync() + { + var document = JsonSerializer.Serialize(new + { + version = 1, + issuer = Authority.Issuer, + users = SeedData.IdentityUsers.Select((person, index) => new + { actorId = person.UserId.Value, opaqueSub = $"qualification-provider-fact-{index}" }), + }); + await using var input = new MemoryStream(Encoding.UTF8.GetBytes(document)); + return await SeedProviderWitness.ReadAsync(input, Authority); + } + + private static async Task AssertCommittedGraphsAsync(DisposableSchemaDatabase database) + { + foreach (var tenant in SeedData.All) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using var transaction = await app.BeginTransactionAsync(); + await IdentityMembershipFixture.ScopeAsync(app, transaction, tenant.TenantId.Value); + (await IdentityMembershipFixture.ScalarAsync(app, transaction, + "SELECT count(*) FROM public.roles WHERE row_version=0")).Should().Be(8); + } + foreach (var member in SeedData.IdentityMemberships) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await IdentityMembershipFixture.ScopeAsync(app, transaction, member.Identity.Tenant.TenantId.Value, + member.OrganizationId?.Value); + (await IdentityMembershipFixture.ScalarAsync(app, transaction, """ + SELECT count(*) FROM public.memberships member + JOIN public.membership_profiles profile ON profile.tenant_id=member.tenant_id AND profile.membership_id=member.id + JOIN public.membership_role_assignments assignment ON assignment.tenant_id=member.tenant_id AND assignment.membership_id=member.id + WHERE member.id=@member AND member.user_id=@user AND member.row_version=1 AND member.status='Active' + AND member.deleted_at IS NULL AND assignment.role_id=@role + AND profile.display_name=@display AND profile.preferred_locale=@locale + """, ("member", member.MembershipId), ("user", member.Identity.UserId.Value), + ("role", member.Role.RoleId), ("display", member.DisplayName), ("locale", member.PreferredLocale))).Should().Be(1); + } + await using var audit = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.PlatformConnectionString); + (await IdentityMembershipFixture.ScalarAsync(audit, null, """ + SELECT count(*) FROM public.audit_log WHERE module='identity' AND operation<>'identity.user.create' AND outcome='success' + """)).Should().Be(24, "each observed contextual command has a durable central MUST row"); + } + + private static async Task FunctionsAsync(DisposableSchemaDatabase database) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString); + await using var command = new NpgsqlCommand(""" + SELECT pg_get_functiondef(oid),prosrc, + json_build_array(proowner,prolang,provolatile,proisstrict,prosecdef,proconfig,proacl)::text + FROM pg_catalog.pg_proc WHERE oid='public.fn_identity_lock_held(text,uuid,boolean)'::regprocedure + """, owner); + string definition, source, metadata; + await using (var row = await command.ExecuteReaderAsync()) + { + (await row.ReadAsync()).Should().BeTrue(); + definition = row.GetString(0); source = row.GetString(1); metadata = row.GetString(2); + } + command.CommandText = """ + SELECT pg_get_functiondef(proc.oid),json_build_array(proc.proowner,proc.proacl)::text + FROM pg_catalog.pg_proc proc JOIN pg_catalog.pg_namespace ns ON ns.oid=proc.pronamespace + WHERE ns.nspname='public' AND proc.proname LIKE 'fn_identity_%' AND proc.prosecdef + ORDER BY proc.proname,pg_get_function_identity_arguments(proc.oid) + """; + var definers = new List(); + await using var rows = await command.ExecuteReaderAsync(); + while (await rows.ReadAsync()) definers.Add(rows.GetString(0) + rows.GetString(1)); + return new(definition, source, metadata, [.. definers]); + } + + private static async Task DeploymentAsync(DisposableSchemaDatabase database, string sql) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString); + await IdentityMembershipFixture.ExecuteAsync(owner, null, sql); + } + + private static double Percentile95(IEnumerable values) + { + var ordered = values.Order().ToArray(); + return ordered[(int)Math.Ceiling(ordered.Length * 0.95) - 1]; + } + + private sealed record FunctionSnapshot(string Definition, string Source, string Metadata, string[] Definers) + { + public override string ToString() => "Private identity function census"; + } + + private sealed record CommandSample(string Command, bool Cold, long ElapsedMilliseconds, + int SqlCommands, double SqlMilliseconds); + + private sealed record CommandReport(CommandSample[] Samples, int ColdSamples, int WarmSamples, double WarmP95Milliseconds, + bool WarmWithin500Milliseconds, double ColdP95Milliseconds, double SqlP95Milliseconds, + int MaximumBusyConnections, int FinalBusyConnections, int PoolObservations, + double MaximumAcquiredUserWaitMilliseconds, int PoolCapacity); + + /// Allowlisted numeric observations only; no formatter, scope, SQL text or raw tag capture. + private sealed class CommandCapture : ILoggerProvider + { + private const string RootProperty = "IdentityCommandQualificationCapture"; + private static readonly HashSet Commands = new(StringComparer.Ordinal) + { + nameof(InitializeSeedRoleCommand), nameof(CreateFirstSeedAdminMembershipCommand), + nameof(CreateSeedMembershipCommand), nameof(SetSeedMembershipProfileCommand), + }; + private readonly object _gate = new(); + private readonly string _poolName; + private readonly ActivityListener _activities = new(); + private readonly MeterListener _metrics = new(); + private readonly Dictionary _pending = []; + private readonly HashSet _seen = new(StringComparer.Ordinal); + private readonly List _samples = []; + private int _disposed; + + internal CommandCapture(string poolName) + { + _poolName = poolName; + _metrics.InstrumentPublished = (instrument, listener) => + { + if (instrument.Meter.Name == "Npgsql" && instrument.Name == "db.client.connection.count" + || instrument.Meter.Name == IdentityLockObservation.MeterName + && instrument.Name == "learnstack_identity_lock_wait_seconds") + listener.EnableMeasurementEvents(instrument); + }; + _metrics.SetMeasurementEventCallback((_, value, tags, _) => + { + string? pool = null, state = null; + foreach (var tag in tags) + { + if (tag.Key == "db.client.connection.pool.name") pool = tag.Value as string; + if (tag.Key == "db.client.connection.state") state = tag.Value as string; + } + if (pool != _poolName || state != "used") return; + lock (_gate) + { + PoolObservations++; + FinalBusy = value; + MaximumBusy = Math.Max(MaximumBusy, value); + } + }); + _metrics.SetMeasurementEventCallback((_, value, tags, _) => + { + if (!WithinRoot(Activity.Current)) return; + string? kind = null, outcome = null; + foreach (var tag in tags) + { + if (tag.Key == "lock_kind") kind = tag.Value as string; + if (tag.Key == "outcome") outcome = tag.Value as string; + } + if (kind == "user" && outcome == "acquired") + lock (_gate) MaximumAcquiredUserWaitMilliseconds = Math.Max(MaximumAcquiredUserWaitMilliseconds, value * 1000); + }); + _metrics.Start(); + _activities.ShouldListenTo = source => source.Name is "Npgsql" or "learnstack.mediatr"; + // Propagation-only sampling keeps Npgsql from materializing query/connection + // tags for this observer. Its duration and parent chain are sufficient. + _activities.Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.PropagationData; + _activities.ActivityStarted = Started; + _activities.ActivityStopped = Stopped; + ActivitySource.AddActivityListener(_activities); + } + + internal int MaximumBusy { get; private set; } + internal int FinalBusy { get; private set; } + internal int PoolObservations { get; private set; } + internal double MaximumAcquiredUserWaitMilliseconds { get; private set; } + internal Activity Enter() + { + var root = new Activity("identity.command.qualification"); + root.SetCustomProperty(RootProperty, this); + return root.Start(); + } + internal void ObservePool() => _metrics.RecordObservableInstruments(); + internal CommandSample[] Samples() { lock (_gate) return [.. _samples]; } + public ILogger CreateLogger(string categoryName) => new NumericCommandLogger(this, + categoryName.StartsWith("LearnStack.Application.Pipeline.LoggingBehavior", StringComparison.Ordinal)); + + private bool WithinRoot(Activity? activity) + { + for (var cursor = activity; cursor is not null; cursor = cursor.Parent) + if (ReferenceEquals(cursor.GetCustomProperty(RootProperty), this)) return true; + return false; + } + + private void Started(Activity activity) + { + if (!WithinRoot(activity)) return; + if (activity.Source.Name == "learnstack.mediatr") + { + var name = activity.OperationName; + if (!name.StartsWith("mediatr.", StringComparison.Ordinal) || !Commands.Contains(name[8..])) return; + lock (_gate) _pending.Add(activity.SpanId, new(name[8..])); + } + else if (activity.Source.Name == "Npgsql") + { + lock (_gate) + if (ParentCommand(activity) is { } command) command.SqlCommands++; + ObservePool(); + } + } + + private void Stopped(Activity activity) + { + if (!WithinRoot(activity)) return; + lock (_gate) + { + if (activity.Source.Name == "Npgsql" && ParentCommand(activity) is { } command) + command.SqlMilliseconds += activity.Duration.TotalMilliseconds; + if (activity.Source.Name == "learnstack.mediatr") _pending.Remove(activity.SpanId); + } + } + + private PendingCommand? ParentCommand(Activity activity) + { + for (var cursor = activity.Parent; cursor is not null; cursor = cursor.Parent) + if (_pending.TryGetValue(cursor.SpanId, out var command)) return command; + return null; + } + + private void Success(TState state) + { + if (!WithinRoot(Activity.Current) || state is not IEnumerable> fields) return; + string? name = null; + long? elapsed = null; + foreach (var field in fields) + { + if (field.Key == "RequestName") name = field.Value as string; + if (field.Key == "ElapsedMilliseconds" && field.Value is long value) elapsed = value; + } + if (name is null || elapsed is null || !Commands.Contains(name) || Activity.Current is not { } current) return; + lock (_gate) + { + if (!_pending.TryGetValue(current.SpanId, out var command) || command.Name != name) return; + _samples.Add(new(name, _seen.Add(name), elapsed.Value, command.SqlCommands, command.SqlMilliseconds)); + } + } + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + _activities.Dispose(); + _metrics.Dispose(); + } + + private sealed class PendingCommand(string name) + { + internal string Name { get; } = name; + internal int SqlCommands { get; set; } + internal double SqlMilliseconds { get; set; } + } + + private sealed class NumericCommandLogger(CommandCapture capture, bool approvedCategory) : ILogger + { + public bool IsEnabled(LogLevel logLevel) => approvedCategory && logLevel == LogLevel.Information; + public IDisposable? BeginScope(TState state) where TState : notnull => null; + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, + Func formatter) + { + if (IsEnabled(logLevel) && eventId.Id == 1) capture.Success(state); + } + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityDiagnosticSinkTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityDiagnosticSinkTests.cs new file mode 100644 index 000000000..03ef788af --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityDiagnosticSinkTests.cs @@ -0,0 +1,471 @@ +using System.Data.Common; +using System.Diagnostics; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Application.Pipeline; +using LearnStack.Modules.Identity.Application.Abstractions; +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Application.Seeding; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.Modules.Tenancy.Domain; +using LearnStack.Modules.Tenancy.Infrastructure.Persistence; +using LearnStack.Infrastructure.Persistence; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Time; +using LearnStack.Tools.Seeder; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; +using Microsoft.Extensions.Logging; +using Npgsql; +using Xunit; +using Xunit.Abstractions; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +[CollectionDefinition(Name, DisableParallelization = true)] +public sealed class IdentityDiagnosticSinkGroup : ICollectionFixture +{ + public const string Name = "Identity diagnostic sinks"; +} + +/// G19 value-bearing failures through actual storage and serialized output sinks. +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(IdentityDiagnosticSinkGroup.Name)] +public sealed class IdentityDiagnosticSinkTests(IdentityMembershipFixture fixture, ITestOutputHelper output) +{ + private const string Neutral = "identity-neutral-472bc"; + private const string Nested = "identity-nested-845ad"; + private const string Sensitive = "identity-sensitive-763ef"; + private static readonly string Payload = JsonSerializer.Serialize(new + { + value = Neutral, + items = new[] { new { value = Nested, token = Sensitive } }, + }); + private static readonly string[] Canaries = [Neutral, Nested, Sensitive]; + + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(true, true)] + public async Task Overlapping_compositions_protect_every_Identity_span_without_changing_actual_callers( + bool asynchronous, bool nestedInSiblingCommand) + { + const string siblingValue = "ordinary-sibling-provider-control-938c"; + const string callerDescription = "ordinary-caller-diagnostic-281d"; + using var sinks = new IdentityDiagnosticSinks(); + using var otherTracing = new IdentityDiagnosticSinks.TraceComposition(); + using var observed = new IdentityDiagnosticSinks.EfActivityObserver(); + using var callers = new ActivitySource("learnstack.identity.storage-qualification"); + using var caller = callers.StartActivity("overlapping-compositions-caller"); + caller.Should().NotBeNull(); + caller!.SetStatus(ActivityStatusCode.Error, callerDescription); + await using var identityConnection = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(identityConnection); + await using var identityTransaction = await identityConnection.BeginTransactionAsync(); + await SchemaQueries.SetTenantAsync(identityConnection, identityTransaction, SchemaFixture.TenantA); + var tenant = new StaticTenantContextAccessor(new SeedTenantContext(TenantId.From(SchemaFixture.TenantA), null)); + var witness = new ProviderFailureWitness(); + await using var identity = new IdentityDbContext(new DbContextOptionsBuilder() + .UseNpgsql(identityConnection).UseLoggerFactory(sinks.Loggers).AddInterceptors(witness).Options, + tenant, EmptyIdentityScope.Instance); + await identity.Database.UseTransactionAsync(identityTransaction); + var identityQuery = identity.Database.SqlQuery($"SELECT CAST({Payload} AS integer) AS \"Value\""); + PostgresException? identityFailure = null; + IdentityDiagnosticSinks.ExportedTrace[][] identityCompleted = []; + + void CaptureIdentityCompletion() + { + identityFailure.Should().NotBeNull(); + identityFailure!.SqlState.Should().Be("22P02"); + foreach (var canary in Canaries) identityFailure.MessageText.Should().Contain(canary); + witness.Failure.Should().BeSameAs(identityFailure); + witness.Commands.Should().Be(1, "one actual provider command generated all the nested spans"); + identityCompleted = [sinks.Traces.ToArray(), otherTracing.Traces.ToArray()]; + } + + void ReadIdentity() + { + identityFailure = Record.Exception(() => identityQuery.Single()) as PostgresException; + CaptureIdentityCompletion(); + } + + async Task ReadIdentityAsync() + { + identityFailure = await Record.ExceptionAsync(() => identityQuery.SingleAsync()) as PostgresException; + CaptureIdentityCompletion(); + } + + PostgresException? siblingFailure = null; + if (nestedInSiblingCommand) + { + // The actual sibling EF command remains current while the separate + // Identity connection fails. Completion snapshots distinguish the + // operations without using the runtime marker or its ancestry walk. + var nested = new NestedIdentityRead(ReadIdentity, ReadIdentityAsync); + await using var siblingConnection = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(siblingConnection); + await using var siblingTransaction = await siblingConnection.BeginTransactionAsync(); + await SchemaQueries.SetTenantAsync(siblingConnection, siblingTransaction, SchemaFixture.TenantA); + await using var sibling = new TenancyDbContext(new DbContextOptionsBuilder() + .UseNpgsql(siblingConnection).UseLoggerFactory(sinks.Loggers).AddInterceptors(nested).Options, tenant); + await sibling.Database.UseTransactionAsync(siblingTransaction); + var query = sibling.Database.SqlQuery($"SELECT CAST({siblingValue} AS integer) AS \"Value\""); + siblingFailure = (asynchronous + ? await Record.ExceptionAsync(() => query.SingleAsync()) + : Record.Exception(() => query.Single())) as PostgresException; + siblingFailure.Should().NotBeNull(); + siblingFailure!.MessageText.Should().Contain(siblingValue); + nested.Calls.Should().Be(1); + nested.Caller.Should().NotBeNull(); + nested.Caller!.Source.Name.Should().Be(IdentityDiagnosticSinks.EfSource); + nested.Caller.StatusDescription.Should().Be(siblingFailure.Message); + } + else if (asynchronous) await ReadIdentityAsync(); + else ReadIdentity(); + + Activity.Current.Should().BeSameAs(caller); + caller.Stop(); + caller.Status.Should().Be(ActivityStatusCode.Error); + caller.StatusDescription.Should().Be(callerDescription); + var completed = new[] { sinks.Traces, otherTracing.Traces }; + output.WriteLine(JsonSerializer.Serialize(new + { + asynchronous, + nestedInSiblingCommand, + ProviderCommandFailures = witness.Commands, + Compositions = completed.Select(traces => new + { + ErrorSpans = traces.Where(trace => trace.Source == IdentityDiagnosticSinks.EfSource + && trace.Status == ActivityStatusCode.Error).Select(trace => new { trace.Id, trace.ParentId, trace.Description }), + ContainsIdentityCanary = Canaries.Any(canary => traces.Any(trace => trace.Json.Contains(canary, StringComparison.Ordinal))), + }), + })); + for (var index = 0; index < completed.Length; index++) + { + observed.AssertCompleteCoverage(completed[index]); + IdentityDiagnosticSinks.AssertEfCallerAncestry(completed[index], caller); + var identityErrors = identityCompleted[index].Where(trace => trace.Source == IdentityDiagnosticSinks.EfSource + && trace.Status == ActivityStatusCode.Error).ToArray(); + identityErrors.Length.Should().BeGreaterThanOrEqualTo(2, "both actual compositions create a command span"); + identityErrors.Should().OnlyContain(trace => trace.Description == "Identity storage command failed."); + foreach (var canary in Canaries) + string.Join('\n', completed[index].Select(trace => trace.Json)).Should().NotContain(canary); + completed[index].Single(trace => trace.Id == caller.Id).Description.Should().Be(callerDescription); + if (nestedInSiblingCommand) + { + var siblingErrors = completed[index].Skip(identityCompleted[index].Length) + .Where(trace => trace.Source == IdentityDiagnosticSinks.EfSource && trace.Status == ActivityStatusCode.Error).ToArray(); + siblingErrors.Length.Should().BeGreaterThanOrEqualTo(2); + siblingErrors.Should().OnlyContain(trace => trace.Description == siblingFailure!.Message); + } + } + sinks.LogText.Should().Contain("IdentityStorageReadFailed"); + foreach (var canary in Canaries) sinks.LogText.Should().NotContain(canary); + } + + [Theory] + [InlineData(false, false)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(true, true)] + public async Task Actual_profile_provider_failure_reaches_source_and_never_reaches_serialized_diagnostic_sinks(bool deferred, bool transient) + { + var sqlState = transient ? PostgresErrorCodes.ObjectNotInPrerequisiteState : "P0399"; + using var sinks = new IdentityDiagnosticSinks(); + var witness = new ProviderFailureWitness(); + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.MigrationConnectionString); + // The owned database alone receives this trigger. PostgreSQL's MESSAGE is + // value-bearing even with Include Error Detail disabled (the shipped default). + await ExecuteAsync(owner, null, $""" + CREATE SEQUENCE public.identity_sink_source; + GRANT USAGE, SELECT ON public.identity_sink_source TO learnstack_app; + CREATE FUNCTION public.identity_sink_failure() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + IF NEW.display_name::jsonb->>'value'='{Neutral}' + AND NEW.display_name::jsonb->'items'->0->>'value'='{Nested}' + AND NEW.display_name::jsonb->'items'->0->>'token'='{Sensitive}' THEN + PERFORM nextval('public.identity_sink_source'); + END IF; + RAISE EXCEPTION USING ERRCODE='{sqlState}', MESSAGE=NEW.display_name; + END $$; + """); + await ExecuteAsync(owner, null, deferred ? """ + CREATE CONSTRAINT TRIGGER identity_sink_failure AFTER UPDATE ON public.membership_profiles + DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION public.identity_sink_failure(); + """ : """ + CREATE TRIGGER identity_sink_failure BEFORE UPDATE ON public.membership_profiles + FOR EACH ROW EXECUTE FUNCTION public.identity_sink_failure(); + """); + try + { + using var parentSource = new ActivitySource("learnstack.identity.storage-qualification"); + using var parent = parentSource.StartActivity("identity-storage-parent"); + parent.Should().NotBeNull(); + await using var source = ApplicationDataSource.Build(fixture.Postgres.AppConnectionString, sinks.Loggers); + await using var unit = new NpgsqlUnitOfWork(source, sinks.Loggers.CreateLogger()); + await using var frame = await unit.BeginTransactionAsync(); + var tenant = TenantId.From(SchemaFixture.TenantA); + await unit.SetProvisioningTenantContextAsync(tenant); + await new IdentityMutationLocks(unit).AcquireAsync(new([], tenant, IdentityTenantLockMode.Shared)); + var scope = new StaticTenantContextAccessor(new SeedTenantContext(tenant, null)); + await using var db = new IdentityDbContext(new DbContextOptionsBuilder() + .UseNpgsql(unit.Connection).UseLoggerFactory(sinks.Loggers).AddInterceptors(witness).Options, + scope, EmptyIdentityScope.Instance); + await db.Database.UseTransactionAsync(unit.Transaction); + var store = new MembershipWriteStore(db, new ContextualIdentityStorageControl(db, unit)); + var member = await store.FindAsync(MembershipId.From(LearnerMembershipA)); + member.Should().NotBeNull(); + member!.SetProfile(Payload, "en", DateTimeOffset.UtcNow, UserId.SystemActor).IsSuccess.Should().BeTrue(); + member.Profile.DisplayName.Should().Be(Payload, "the real tracked personal field carries all three values"); + var failure = await Record.ExceptionAsync(async () => + { + await store.UpdateAsync(member); + if (deferred) await store.ValidateGraphAsync(); + }); + failure.Should().NotBeNull(); + if (!deferred) + { + witness.Failure.Should().BeOfType(); + ((PostgresException)witness.Failure!).SqlState.Should().Be(sqlState); + witness.Failure!.Message.Should().Contain(Payload, "the real provider must receive and return the planted values"); + } + unit.IsRollbackOnly.Should().BeTrue(); + await frame.FailAsync(); + await using var observer = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(observer); + (await ScalarAsync(observer, null, "SELECT is_called FROM public.identity_sink_source")).Should().BeTrue( + "the provider itself confirms all three exact values reached its failing trigger, including the deferred path"); + + Activity.Current.Should().BeSameAs(parent, "stopping the actual EF span restores its existing caller context"); + sinks.AssertCompleteEfTraceCoverage(); + IdentityDiagnosticSinks.AssertEfCallerAncestry(sinks.Traces, parent!); + parent!.Stop(); + parent.Status.Should().Be(ActivityStatusCode.Unset); + await sinks.CaptureThroughL1Async(failure!); + var captured = await sinks.ReadAsync(); + output.WriteLine(JsonSerializer.Serialize(new + { + Deferred = deferred, + SourceReached = true, + EscapedType = failure!.GetType().Name, + LogContainsCanary = Canaries.Any(captured.Log.Contains), + LocalContainsCanary = Canaries.Any(captured.Local.Contains), + SentryContainsCanary = Canaries.Any(captured.Sentry.Contains), + ResponseContainsCanary = Canaries.Any(captured.Response.Contains), + TraceContainsCanary = Canaries.Any(captured.Trace.Contains), + ExportedSpans = sinks.Traces.Count, + ErrorSpans = sinks.Traces.Count(trace => trace.Status == System.Diagnostics.ActivityStatusCode.Error), + })); + captured.AssertPositiveControls(); + failure.Should().BeOfType(); + if (!deferred) captured.Log.Should().Contain("IdentityStorageSaveFailed").And.Contain("3191"); + var efErrors = sinks.Traces.Where(trace => trace.Source == "OpenTelemetry.Instrumentation.EntityFrameworkCore" + && trace.Status == System.Diagnostics.ActivityStatusCode.Error).ToArray(); + if (deferred) efErrors.Should().BeEmpty(); + else + { + witness.Commands.Should().Be(1); + efErrors.Should().NotBeEmpty().And.OnlyContain(trace => trace.Description == "Identity storage command failed."); + } + sinks.Traces.Where(trace => trace.Source == "learnstack.identity.sink-qualification") + .Should().HaveCount(2).And.OnlyContain(trace => trace.Status == System.Diagnostics.ActivityStatusCode.Error + && trace.Description == nameof(IdentityStorageProviderException)); + captured.AssertExcludes(Canaries); + failure.InnerException.Should().BeNull("the adapter must not retain an original provider payload"); + } + finally + { + await ExecuteAsync(owner, null, """ + DROP TRIGGER identity_sink_failure ON public.membership_profiles; + DROP FUNCTION public.identity_sink_failure(); + DROP SEQUENCE public.identity_sink_source; + """); + } + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Actual_global_binding_save_keeps_its_fixed_boundary_and_replaces_pre_adapter_EF_failure_output(bool transient) + { + var sqlState = transient ? PostgresErrorCodes.LockNotAvailable : "P0399"; + using var sinks = new IdentityDiagnosticSinks(); + var witness = new ProviderFailureWitness(); + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.MigrationConnectionString); + await ExecuteAsync(owner, null, """ + CREATE FUNCTION public.identity_binding_sink_failure() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN RAISE EXCEPTION USING ERRCODE='P0399', MESSAGE=NEW.provider_subject; END $$; + CREATE TRIGGER identity_binding_sink_failure BEFORE INSERT ON public.users + FOR EACH ROW EXECUTE FUNCTION public.identity_binding_sink_failure(); + """.Replace("P0399", sqlState, StringComparison.Ordinal)); + try + { + using var parentSource = new ActivitySource("learnstack.identity.storage-qualification"); + using var parent = parentSource.StartActivity("identity-storage-parent"); + parent.Should().NotBeNull(); + await using var source = ApplicationDataSource.Build(fixture.Postgres.AppConnectionString, sinks.Loggers); + await using var unit = new NpgsqlUnitOfWork(source, sinks.Loggers.CreateLogger()); + var subject = new GlobalIdentitySubject(Authority.AuthorityId, Authority.Issuer, Payload); + var descriptor = ProofOwner.Create(subject); + await using var frame = await unit.BeginGlobalIdentityTransactionAsync(descriptor, TransactionMode.ReadWrite); + await unit.AcquireGlobalIdentitySubjectLockAsync(descriptor); + await using var db = new IdentityDbContext(new DbContextOptionsBuilder() + .UseNpgsql(unit.Connection).UseLoggerFactory(sinks.Loggers).AddInterceptors(witness).Options, + StaticTenantContextAccessor.Unresolved, new GlobalIdentityScopeAccessor(unit)); + var store = new UserBindingStore(db, unit); + (await store.FindExactAsync(subject)).Should().BeNull(); + var creation = ProofCreation.Create(unit); + var user = User.Create(subject, creation, creation.Timestamp, UserId.SystemActor); + user.ProviderSubject.Should().Be(Payload); + var failure = await Record.ExceptionAsync(() => store.AddAsync(user)); + failure.Should().BeOfType(); + witness.Failure.Should().BeOfType(); + ((PostgresException)witness.Failure!).SqlState.Should().Be(sqlState); + witness.Failure!.Message.Should().Contain(Payload); + await frame.FailAsync(); + Activity.Current.Should().BeSameAs(parent, "stopping the actual EF span restores its existing caller context"); + sinks.AssertCompleteEfTraceCoverage(); + IdentityDiagnosticSinks.AssertEfCallerAncestry(sinks.Traces, parent!); + parent!.Stop(); + parent.Status.Should().Be(ActivityStatusCode.Unset); + await sinks.CaptureThroughL1Async(failure!); + var captured = await sinks.ReadAsync(); + captured.AssertPositiveControls(); + captured.Log.Should().Contain("IdentityStorageSaveFailed").And.Contain("3191"); + witness.Commands.Should().Be(1); + sinks.Traces.Where(trace => trace.Source == "OpenTelemetry.Instrumentation.EntityFrameworkCore" + && trace.Status == System.Diagnostics.ActivityStatusCode.Error) + .Should().NotBeEmpty().And.OnlyContain(trace => trace.Description == "Identity storage command failed."); + captured.AssertExcludes(Canaries); + failure!.InnerException.Should().BeNull(); + } + finally + { + await ExecuteAsync(owner, null, """ + DROP TRIGGER identity_binding_sink_failure ON public.users; + DROP FUNCTION public.identity_binding_sink_failure(); + """); + } + } + + [Fact] + public async Task Another_modules_EF_save_failure_event_remains_enabled() + { + using var sinks = new IdentityDiagnosticSinks(); + await using var source = ApplicationDataSource.Build(fixture.Postgres.AppConnectionString, sinks.Loggers); + await using var unit = new NpgsqlUnitOfWork(source, sinks.Loggers.CreateLogger()); + await using var frame = await unit.BeginTransactionAsync(); + var tenant = TenantId.From(SchemaFixture.TenantA); + await unit.SetProvisioningTenantContextAsync(tenant); + await using var db = new TenancyDbContext(new DbContextOptionsBuilder() + .UseNpgsql(unit.Connection).UseLoggerFactory(sinks.Loggers).Options, + new StaticTenantContextAccessor(new SeedTenantContext(tenant, null))); + await db.Database.UseTransactionAsync(unit.Transaction); + // An ordinary RLS refusal from a sibling module must still retain EF's + // own event. No personal canary is deliberately sent to that boundary. + db.Tenants.Add(Tenant.Create(TenantId.From(Guid.CreateVersion7()), "sink-control", "Sink control", + new SystemClock(), UserId.SystemActor)); + var save = () => db.SaveChangesAsync(); + var failure = (await save.Should().ThrowAsync()).Which; + failure.InnerException.Should().BeOfType(); + sinks.AssertCompleteEfTraceCoverage(); + sinks.Traces.Where(trace => trace.Source == "OpenTelemetry.Instrumentation.EntityFrameworkCore" + && trace.Status == System.Diagnostics.ActivityStatusCode.Error) + .Should().NotBeEmpty().And.OnlyContain(trace => trace.Description == failure.InnerException!.Message, + "the Identity boundary must leave the sibling module's actual error status description intact"); + sinks.LogText.Should().Contain("Microsoft.EntityFrameworkCore.Update.SaveChangesFailed") + .And.NotContain("IdentityStorageSaveFailed"); + await frame.FailAsync(); + } + + [Fact] + public async Task Actual_profile_validation_drops_attempted_values_and_emits_fixed_nonempty_response() + { + var request = new SetSeedMembershipProfileCommand(LearnerMembershipA, UserId.From(PersonA), + RoleId(SchemaFixture.TenantA, BuiltInRoleKey.Learner, PermissionScope.Tenant), PermissionScope.Tenant, + Payload + new string('x', MembershipProfile.MaximumDisplayNameLength), "en", 1, new string('a', 64)); + var validator = new SetSeedMembershipProfileCommandValidator(); + var source = await validator.ValidateAsync(request); + source.IsValid.Should().BeFalse(); + source.Errors.Should().Contain(failure => ReferenceEquals(failure.AttemptedValue, request), + "the real object-level rule receives the entire value-bearing Identity command"); + var raw = JsonSerializer.Serialize(source.Errors.Select(failure => failure.AttemptedValue)); + foreach (var canary in Canaries) raw.Should().Contain(canary); + var behavior = new ValidationBehavior>([validator]); + var result = await behavior.Handle(request, () => throw new InvalidOperationException("Invalid input reached handler."), CancellationToken.None); + result.IsFailure.Should().BeTrue(); + var diagnostics = JsonSerializer.Serialize(result.Error); + var response = JsonSerializer.Serialize(LearnStack.Api.Common.ProblemDetailsFactory.For(result.Error!)); + diagnostics.Should().Contain("lockey_validation_failed"); + response.Should().Contain("validation_failed").And.Contain("errors"); + foreach (var canary in Canaries) + { + diagnostics.Should().NotContain(canary); + response.Should().NotContain(canary); + } + } + + private sealed class ProofOwner : GlobalIdentityOwnerDescriptor.MintingSource + { + public static GlobalIdentityOwnerDescriptor Create(GlobalIdentitySubject subject) => + ForBootstrap(subject, typeof(IdentityDbContext), typeof(User)); + } + + private sealed class ProofCreation : GlobalIdentityCreationReference.MintingSource + { + public static GlobalIdentityCreationReference Create(NpgsqlUnitOfWork unit) => Mint(unit, + unit.GetGlobalIdentityAnnouncement(unit.Transaction)!, UserId.From(Guid.CreateVersion7()), + AuditEntryId.From(Guid.CreateVersion7()), DateTimeOffset.UtcNow); + } + + private sealed class ProviderFailureWitness : DbCommandInterceptor + { + public Exception? Failure { get; private set; } + public int Commands { get; private set; } + public override void CommandFailed(DbCommand command, CommandErrorEventData eventData) + { + Failure = eventData.Exception; + Commands++; + } + public override Task CommandFailedAsync(DbCommand command, CommandErrorEventData eventData, + CancellationToken cancellationToken = default) + { + CommandFailed(command, eventData); + return Task.CompletedTask; + } + } + + private sealed class NestedIdentityRead(Action read, Func readAsync) : DbCommandInterceptor + { + public int Calls { get; private set; } + public Activity? Caller { get; private set; } + public override InterceptionResult ReaderExecuting(DbCommand command, CommandEventData eventData, + InterceptionResult result) + { + Calls++; + Caller = Activity.Current; + read(); + Activity.Current.Should().BeSameAs(Caller); + return result; + } + + public override async ValueTask> ReaderExecutingAsync(DbCommand command, + CommandEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) + { + Calls++; + Caller = Activity.Current; + await readAsync(); + Activity.Current.Should().BeSameAs(Caller); + return result; + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityDiagnosticSinks.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityDiagnosticSinks.cs new file mode 100644 index 000000000..e949a39d4 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityDiagnosticSinks.cs @@ -0,0 +1,296 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Text.Json; +using System.Text; +using FluentAssertions; +using LearnStack.Api.Common; +using LearnStack.Api.Composition; +using LearnStack.Infrastructure.ErrorTracking; +using LearnStack.Infrastructure.Observability.Serilog; +using LearnStack.SharedKernel.Hosting; +using LearnStack.SharedKernel.Observability; +using LearnStack.SharedKernel.Secrets; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.Tools.Seeder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Hosting; +using OpenTelemetry; +using OpenTelemetry.Trace; +using Sentry; +using Sentry.Extensibility; +using Sentry.Protocol.Envelopes; +using Serilog; +using Serilog.Core; +using Serilog.Events; +using Serilog.Extensions.Logging; +using Serilog.Formatting.Json; + +namespace LearnStack.Tests.Integration.Database; + +/// Real SDK serialization; only delivery transport is replaced to prohibit external egress. +internal sealed class IdentityDiagnosticSinks : IDisposable +{ + private const string Marker = "identity-sink-positive-control"; + private const string Dsn = "https://public@identity-sinks.invalid/1"; + private readonly string _directory = Path.Combine(Path.GetTempPath(), "identity-sinks-" + Guid.NewGuid().ToString("N")); + private readonly JsonLogSink _log = new(); + private readonly EnvelopeTransport _transport = new(); + private readonly ServiceProvider _local; + private readonly ServiceProvider _sentry; + private readonly IDisposable _sdk; + private readonly Logger _logger; + private readonly List _responses = []; + private readonly List _correlations = []; + private readonly ActivitySource _activities = new("learnstack.identity.sink-qualification"); + private readonly EfActivityObserver _efActivities = new(); + private readonly TraceComposition _tracing; + + public IdentityDiagnosticSinks() + { + // Build the actual API tracing composition, then append a synchronous + // exporter. Serialize at Export time so a later mutation cannot hide a leak. + _tracing = new TraceComposition(); + _logger = new LoggerConfiguration().MinimumLevel.Debug() + .Enrich.With().WriteTo.Sink(_log).CreateLogger(); + Loggers = new SerilogLoggerFactory(_logger); + var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + { + ["ErrorTracking:LocalFile:Directory"] = _directory, + }).Build(); + _local = new ServiceCollection().AddSingleton(Loggers).AddLogging() + .AddLearnStackErrorTracking(new FixedSecret(), config, DeploymentMode.SelfHostedAirGapped).BuildServiceProvider(); + _sentry = new ServiceCollection().AddSingleton(Loggers).AddLogging() + .AddLearnStackErrorTracking(new FixedSecret(), config, DeploymentMode.SaaS).BuildServiceProvider(); + _sdk = SentrySdk.Init(options => + { + options.Dsn = Dsn; + options.Transport = _transport; + options.IsGlobalModeEnabled = true; + options.AutoSessionTracking = false; + options.DisableAppDomainUnhandledExceptionCapture(); + options.DisableUnobservedTaskExceptionCapture(); + options.DisableAppDomainProcessExitFlush(); + options.DisableDiagnosticSourceIntegration(); + }); + } + + public ILoggerFactory Loggers { get; } + public IReadOnlyList Traces => _tracing.Traces; + public string LogText => string.Join('\n', _log.Payloads); + public void AssertCompleteEfTraceCoverage() => _efActivities.AssertCompleteCoverage(Traces); + + public async Task CaptureThroughL1Async(Exception failure, int expectedStatus = 503) + { + foreach (var services in new[] { _local, _sentry }) + { + using var activity = _activities.StartActivity(Marker); + activity.Should().NotBeNull("the actual production source selection must observe the L1 caller span"); + _correlations.Add(activity!.Id!); + var context = new DefaultHttpContext { RequestServices = services, TraceIdentifier = Marker }; + context.Request.Path = "/__test/identity-diagnostic-sink"; + context.Request.Method = "POST"; + await using var response = new MemoryStream(); + context.Response.Body = response; + var handler = new LearnStackExceptionHandler(services.GetRequiredService(), + new StaticTenantContextAccessor(null), Loggers.CreateLogger()); + (await handler.TryHandleAsync(context, failure, CancellationToken.None)).Should().BeTrue(); + context.Response.StatusCode.Should().Be(expectedStatus); + _responses.Add(Encoding.UTF8.GetString(response.ToArray())); + } + await SentrySdk.FlushAsync(TimeSpan.FromSeconds(10)); + } + + public async Task ReadAsync() + { + var files = Directory.GetFiles(_directory, "*.json"); + files.Should().ContainSingle("the real air-gapped provider must persist its capture"); + _transport.Payloads.Should().ContainSingle("the real Sentry SDK must serialize and send its event"); + _tracing.Flush(); + Traces.Should().Contain(trace => trace.Source.StartsWith("OpenTelemetry.Instrumentation.EntityFrameworkCore", StringComparison.Ordinal), + "the actual production EF instrumentation must reach an actual OpenTelemetry exporter"); + return new(string.Join('\n', _log.Payloads), await File.ReadAllTextAsync(files.Single()), + _transport.Payloads.Single(), string.Join('\n', _responses), string.Join('\n', Traces.Select(trace => trace.Json)), + _correlations.ToArray()); + } + + public void Dispose() + { + _activities.Dispose(); + _tracing.Dispose(); + _efActivities.Dispose(); + _sdk.Dispose(); + _sentry.Dispose(); + _local.Dispose(); + Loggers.Dispose(); + _logger.Dispose(); + if (Directory.Exists(_directory)) Directory.Delete(_directory, recursive: true); + } + + internal sealed record CapturedSinks(string Log, string Local, string Sentry, string Response, string Trace, string[] Correlations) + { + public void AssertPositiveControls(string responseCode = "dependency_unavailable") + { + Log.Should().Contain("L1 exception handler captured"); + Log.Should().Contain("Microsoft.EntityFrameworkCore.Database.Command", + "ordinary real EF command logging remains active"); + Correlations.Should().HaveCount(2).And.OnlyContain(value => !string.IsNullOrWhiteSpace(value)); + Local.Should().Contain(Correlations[0]).And.Contain("exception"); + Sentry.Should().Contain(Correlations[1]).And.Contain("\"type\":\"event\"").And.Contain("exception"); + Response.Should().Contain(Correlations[0]).And.Contain(Correlations[1]).And.Contain(responseCode); + Trace.Should().Contain(Marker).And.Contain("exception"); + } + + public void AssertExcludes(IEnumerable canaries) + { + foreach (var canary in canaries) + { + Log.Should().NotContain(canary, "no value reaches actual serialized Serilog output"); + Local.Should().NotContain(canary, "no value reaches the actual local archive"); + Sentry.Should().NotContain(canary, "no value reaches the real SDK's serialized Sentry envelope"); + Response.Should().NotContain(canary, "no value reaches the actual L1 response bytes"); + Trace.Should().NotContain(canary, "no value reaches an exported span from the actual API instrumentation"); + } + } + } + + internal const string EfSource = "OpenTelemetry.Instrumentation.EntityFrameworkCore"; + + internal sealed record ExportedTrace(string Id, string? ParentId, string Source, + ActivityStatusCode Status, string? Description, string Json); + + /// A second real tracing composition without another global Sentry SDK. + internal sealed class TraceComposition : IDisposable + { + private readonly TraceExporter _exporter = new(); + private readonly IHost _host; + private readonly TracerProvider _provider; + + public TraceComposition() + { + var builder = WebApplication.CreateBuilder([]); + builder.Configuration.AddInMemoryCollection(new Dictionary + { + ["Telemetry:OtlpEndpoint"] = null, + }); + builder.AddLearnStackCrossCuttingFoundation(DeploymentMode.Development); + builder.Services.AddOpenTelemetry().WithTracing(tracing => + tracing.AddProcessor(new SimpleActivityExportProcessor(_exporter))); + _host = builder.Build(); + _provider = _host.Services.GetRequiredService(); + } + + public IReadOnlyList Traces => _exporter.Items.ToArray(); + public void Flush() => _provider.ForceFlush(); + public void Dispose() => _host.Dispose(); + } + + /// Observes actual span identities without creating another EF diagnostic subscriber. + internal sealed class EfActivityObserver : IDisposable + { + private readonly ConcurrentQueue _started = new(); + private readonly ConcurrentQueue _stopped = new(); + private readonly ActivityListener _listener; + + public EfActivityObserver() + { + _listener = new ActivityListener + { + ShouldListenTo = source => source.Name == EfSource, + Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllDataAndRecorded, + SampleUsingParentId = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllDataAndRecorded, + ActivityStarted = activity => _started.Enqueue(activity.Id!), + ActivityStopped = activity => _stopped.Enqueue(activity.Id!), + }; + ActivitySource.AddActivityListener(_listener); + } + + public void AssertCompleteCoverage(IEnumerable traces) => + AssertCompleteCoverage(traces.Where(trace => trace.Source == EfSource).Select(trace => trace.Id)); + + public void AssertCompleteCoverage(IEnumerable exportedIds) + { + var started = _started.ToArray(); + started.Should().NotBeEmpty().And.OnlyHaveUniqueItems(); + _stopped.ToArray().Should().BeEquivalentTo(started, + "every actual EF span must stop, including spans from overlapping compositions"); + exportedIds.Should().BeEquivalentTo(started, + "the exporter must serialize every actual EF span exactly once"); + } + + public void Dispose() => _listener.Dispose(); + } + + public static void AssertEfCallerAncestry(IReadOnlyList traces, Activity caller) + { + var byId = traces.ToDictionary(trace => trace.Id); + foreach (var trace in traces.Where(trace => trace.Source == EfSource)) + { + var parentId = trace.ParentId; + var visited = new HashSet(StringComparer.Ordinal); + while (parentId != caller.Id) + { + parentId.Should().NotBeNull("every actual EF span must descend from its caller"); + visited.Add(parentId!).Should().BeTrue("the exported parent chain must be acyclic"); + byId.Should().ContainKey(parentId!, "every intermediate parent must also be exported"); + parentId = byId[parentId!].ParentId; + } + } + } + + private sealed class TraceExporter : BaseExporter + { + public ConcurrentQueue Items { get; } = new(); + public override ExportResult Export(in Batch batch) + { + foreach (var activity in batch) + { + var json = JsonSerializer.Serialize(new + { + activity.DisplayName, + activity.Id, + activity.ParentId, + Source = activity.Source.Name, + Status = activity.Status.ToString(), + activity.StatusDescription, + Tags = activity.TagObjects.ToArray(), + Events = activity.Events.Select(item => new { item.Name, Tags = item.Tags.ToArray() }).ToArray(), + Links = activity.Links.Select(item => item.Tags?.ToArray()).ToArray(), + }); + Items.Enqueue(new(activity.Id!, activity.ParentId, activity.Source.Name, activity.Status, activity.StatusDescription, json)); + } + return ExportResult.Success; + } + } + + private sealed class FixedSecret : ISecretProvider + { + public string? GetSecret(string key) => key == "ErrorTracking:Sentry:Dsn" ? Dsn : null; + } + + private sealed class JsonLogSink : ILogEventSink + { + private readonly JsonFormatter _formatter = new(renderMessage: true); + public ConcurrentQueue Payloads { get; } = new(); + public void Emit(LogEvent logEvent) + { + using var writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); + _formatter.Format(logEvent, writer); + Payloads.Enqueue(writer.ToString()); + } + } + + private sealed class EnvelopeTransport : ITransport + { + public ConcurrentQueue Payloads { get; } = new(); + public async Task SendEnvelopeAsync(Envelope envelope, CancellationToken cancellationToken = default) + { + await using var stream = new MemoryStream(); + await envelope.SerializeAsync(stream, null, cancellationToken); + Payloads.Enqueue(Encoding.UTF8.GetString(stream.ToArray())); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipFixture.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipFixture.cs new file mode 100644 index 000000000..ce0aa5601 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipFixture.cs @@ -0,0 +1,176 @@ +using LearnStack.Modules.Identity.Domain; +using System.Text.Json; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; +using Npgsql; +using NpgsqlTypes; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// Populated application-role contextual graphs, independent of the four development personas. +public sealed class IdentityMembershipFixture : IAsyncLifetime +{ + public static readonly Guid AdminA = Guid.Parse("01930000-0000-7000-8000-00000000c101"); + public static readonly Guid PersonA = Guid.Parse("01930000-0000-7000-8000-00000000c102"); + public static readonly Guid AdminB = Guid.Parse("01930000-0000-7000-8000-00000000c201"); + public static readonly Guid PersonB = Guid.Parse("01930000-0000-7000-8000-00000000c202"); + public static readonly Guid AdminMembershipA = Guid.Parse("01930000-0000-7000-8000-00000000d101"); + public static readonly Guid LearnerMembershipA = Guid.Parse("01930000-0000-7000-8000-00000000d102"); + public static readonly Guid BranchMembershipA1 = Guid.Parse("01930000-0000-7000-8000-00000000d103"); + public static readonly Guid BranchMembershipA2 = Guid.Parse("01930000-0000-7000-8000-00000000d104"); + public static readonly Guid AdminMembershipB = Guid.Parse("01930000-0000-7000-8000-00000000d201"); + public static readonly Guid BranchMembershipB = Guid.Parse("01930000-0000-7000-8000-00000000d202"); + public static readonly IdentityAuthorityRegistration Authority = new( + IdentityAuthorityId.From(Guid.Parse("01930000-0000-7000-8000-00000000c000")), "https://membership-fixture.invalid/realms/learnstack"); + + public PostgresFixture Postgres { get; } = new(); + public async Task InitializeAsync() + { + await Postgres.InitializeAsync(); + await MigrationChains.ApplyAllAsync(Postgres.MigrationConnectionString); + await SeedSchemaAsync(Postgres.MigrationConnectionString, Postgres.AppConnectionString); + } + public Task DisposeAsync() => Postgres.DisposeAsync(); + + public static Guid RoleId(Guid tenant, BuiltInRoleKey key, PermissionScope scope) + { + var index = Array.FindIndex(IdentityFoundationManifest.Version1.Templates.ToArray(), template => template.BuiltInKey == key && template.Scope == scope); + if (index < 0) throw new ArgumentOutOfRangeException(nameof(key)); + return Guid.Parse($"01930000-0000-7000-8000-00000000e{(tenant == SchemaFixture.TenantA ? 1 : 2)}{index + 1:00}"); + } + + public static async Task SeedSchemaAsync(string ownerConnection, string appConnection) + { + await using (var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(ownerConnection)) + await IdentityAuthorityDeploymentInstaller.InstallAsync(owner, Authority); + foreach (var actor in new[] { AdminA, PersonA, AdminB, PersonB }) + await InsertUserAsync(appConnection, actor); + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(appConnection); + await SchemaQueries.AssertApplicationRoleAsync(app); + foreach (var tenant in new[] { SchemaFixture.TenantA, SchemaFixture.TenantB }) + foreach (var template in IdentityFoundationManifest.Version1.Templates) + { + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant); + await LockAsync(app, transaction, tenant, null, false); + var role = RoleId(tenant, template.BuiltInKey, template.Scope); + 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", role), ("tenant", tenant), ("key", template.BuiltInKey.ToString()), + ("scope", template.Scope.ToString()), ("actor", UserId.SystemActor.Value)); + foreach (var permission in template.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", tenant), ("role", role), ("scope", permission.Scope.ToString()), ("key", permission.Key)); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await transaction.CommitAsync(); + } + await CommitMemberAsync(app, SchemaFixture.TenantA, null, AdminMembershipA, AdminA, BuiltInRoleKey.TenantAdmin); + await CommitMemberAsync(app, SchemaFixture.TenantA, null, LearnerMembershipA, PersonA, BuiltInRoleKey.Learner); + await CommitMemberAsync(app, SchemaFixture.TenantA, SchemaFixture.OrgA1, BranchMembershipA1, PersonA, BuiltInRoleKey.Learner); + await CommitMemberAsync(app, SchemaFixture.TenantA, SchemaFixture.OrgA2, BranchMembershipA2, PersonA, BuiltInRoleKey.Learner); + await CommitMemberAsync(app, SchemaFixture.TenantB, null, AdminMembershipB, AdminB, BuiltInRoleKey.TenantAdmin); + await CommitMemberAsync(app, SchemaFixture.TenantB, SchemaFixture.OrgB1, BranchMembershipB, PersonB, BuiltInRoleKey.Learner); + } + + private static async Task CommitMemberAsync(NpgsqlConnection connection, Guid tenant, Guid? organization, + Guid member, Guid user, BuiltInRoleKey key) + { + await using var transaction = await connection.BeginTransactionAsync(); + await ScopeAsync(connection, transaction, tenant, organization); + await LockAsync(connection, transaction, tenant, user, key == BuiltInRoleKey.TenantAdmin); + await InsertMemberAsync(connection, transaction, tenant, organization, member, user, + RoleId(tenant, key, organization is null ? PermissionScope.Tenant : PermissionScope.Organization)); + await ExecuteAsync(connection, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await transaction.CommitAsync(); + } + + public static async Task InsertUserAsync(string appConnection, Guid user) + { + var subject = new GlobalIdentitySubject(Authority.AuthorityId, Authority.Issuer, "fixture-subject-" + user.ToString("N")); + var audit = Guid.CreateVersion7(); + var at = GlobalIdentityCreationReference.NormalizeTimestamp(DateTimeOffset.UtcNow); + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(appConnection); + await using var transaction = await app.BeginTransactionAsync(); + await GlobalIdentitySchemaTests.AnnounceAsync(app, transaction, subject); + await ExecuteAsync(app, transaction, """ + INSERT INTO public.users(id,authority_id,subject_key,provider_subject,status,creation_audit_id,creation_audit_timestamp,created_at,created_by,row_version) + VALUES(@user,@authority,@key,@subject,'Active',@audit,@at,@at,@actor,0); + 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(@audit,@at,@sentinel,NULL,NULL,'identity','identity.user.create','SecurityEvent','Must','User',@entity,'success',@metadata::jsonb); + SET CONSTRAINTS ALL IMMEDIATE; + """, ("user", user), ("authority", subject.AuthorityId.Value), ("key", subject.SubjectKey.ToByteArray()), + ("subject", subject.Subject), ("audit", audit), ("at", at), ("actor", UserId.SystemActor.Value), + ("sentinel", TenantId.PlatformSentinel.Value), ("entity", user.ToString("D")), + ("metadata", JsonSerializer.Serialize(new + { + identity_authority_id = subject.AuthorityId.Value.ToString("D"), + identity_subject_key = subject.SubjectKey.Hex, + identity_source = "identity-bootstrap" + }))); + await transaction.CommitAsync(); + } + + public static async Task InsertMemberAsync(NpgsqlConnection app, NpgsqlTransaction transaction, Guid tenant, + Guid? organization, Guid member, Guid user, Guid role, string? displayName = "profile-canary") + { + await ExecuteAsync(app, transaction, """ + INSERT INTO public.memberships(id,tenant_id,organization_id,user_id,status,created_at,created_by) + VALUES(@member,@tenant,@organization,@user,'Active',clock_timestamp(),@actor); + INSERT INTO public.membership_profiles(tenant_id,membership_id,organization_id,display_name,preferred_locale) + VALUES(@tenant,@member,@organization,@display,'en'); + INSERT INTO public.membership_role_assignments(tenant_id,membership_id,role_id,organization_id) + VALUES(@tenant,@member,@role,@organization); + """, ("member", member), ("tenant", tenant), ("organization", organization), ("user", user), + ("actor", UserId.SystemActor.Value), ("role", role), ("display", displayName)); + } + + public static Task ScopeAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, Guid tenant, Guid? organization = null) => + ExecuteAsync(connection, transaction, """ + SELECT set_config('app.tenant_id',@tenant,true),set_config('app.organization_id',@organization,true) + """, ("tenant", tenant.ToString("D")), ("organization", organization?.ToString("D") ?? string.Empty)); + + public static async Task LockAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, Guid tenant, Guid? user, bool exclusive) + { + if (user is { } actor) + await ExecuteAsync(connection, transaction, "SELECT pg_advisory_xact_lock(@key)", + ("key", IdentityAdvisoryLockKey.ForUser(UserId.From(actor)))); + await ExecuteAsync(connection, transaction, + exclusive ? "SELECT pg_advisory_xact_lock(@key)" : "SELECT pg_advisory_xact_lock_shared(@key)", + ("key", IdentityAdvisoryLockKey.ForTenant(TenantId.From(tenant)))); + } + + public static async Task ExecuteAsync(NpgsqlConnection connection, NpgsqlTransaction? transaction, string sql, + params (string Name, object? Value)[] values) + { + await using var command = new NpgsqlCommand(sql, connection, transaction); + AddParameters(command, values); + await command.ExecuteNonQueryAsync(); + } + + public static async Task ScalarAsync(NpgsqlConnection connection, NpgsqlTransaction? transaction, string sql, + params (string Name, object? Value)[] values) + { + await using var command = new NpgsqlCommand(sql, connection, transaction); + AddParameters(command, values); + return (T)(await command.ExecuteScalarAsync())!; + } + + private static void AddParameters(NpgsqlCommand command, (string Name, object? Value)[] values) + { + foreach (var (name, value) in values) + { + if (value is not null) command.Parameters.AddWithValue(name, value); + else command.Parameters.Add(new NpgsqlParameter(name, + name == "organization" ? NpgsqlDbType.Uuid : NpgsqlDbType.Text) + { Value = DBNull.Value }); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.AdminEligibility.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.AdminEligibility.cs new file mode 100644 index 000000000..55417f74b --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.AdminEligibility.cs @@ -0,0 +1,85 @@ +using FluentAssertions; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class IdentityMembershipTests +{ + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Last_administrator_guard_requires_global_eligibility_not_only_an_active_membership(bool eligible) + { + 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); + var original = await UserControlCensusAsync(owner); + var check = await ScalarAsync(owner, null, + "SELECT pg_get_expr(polwithcheck,polrelid) FROM pg_policy WHERE polrelid='public.users'::regclass AND polname='users_isolation'"); + try + { + if (!eligible) + { + // Fixture-confined closure; no production lifecycle grant or + // owner-function is added. Restore exact controls before the app act. + await using var close = await owner.BeginTransactionAsync(); + await ExecuteAsync(owner, close, $""" + SELECT pg_advisory_xact_lock(@user_key); + SELECT pg_advisory_xact_lock(@tenant_key); + ALTER TABLE public.users DISABLE TRIGGER tg_users_no_update; + ALTER POLICY users_isolation ON public.users WITH CHECK (({check}) OR + (current_user='learnstack_migration' AND id='{AdminA:D}'::uuid AND status='Closing' + AND deleted_at IS NULL AND deleted_by IS NULL)); + UPDATE public.users SET status='Closing' WHERE id='{AdminA:D}'::uuid; + ALTER POLICY users_isolation ON public.users WITH CHECK ({check}); + ALTER TABLE public.users ENABLE TRIGGER tg_users_no_update; + """, ("user_key", IdentityAdvisoryLockKey.ForUser(UserId.From(AdminA))), + ("tenant_key", IdentityAdvisoryLockKey.ForTenant(TenantId.From(SchemaFixture.TenantA)))); + await close.CommitAsync(); + } + (await UserControlCensusAsync(owner)).Should().Be(original); + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + await LockAsync(app, transaction, SchemaFixture.TenantA, null, false); + await ExecuteAsync(app, transaction, + "UPDATE public.membership_profiles SET display_name='eligibility-control' WHERE membership_id=@id", + ("id", LearnerMembershipA)); + var finish = () => ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + if (eligible) + { + await finish(); + await transaction.CommitAsync(); + } + else + { + (await finish.Should().ThrowAsync()).Which.SqlState.Should().Be("P0303"); + await transaction.RollbackAsync(); + } + } + finally + { + await ExecuteAsync(owner, null, + $"ALTER POLICY users_isolation ON public.users WITH CHECK ({check}); ALTER TABLE public.users ENABLE TRIGGER tg_users_no_update"); + } + (await UserControlCensusAsync(owner)).Should().Be(original); + } + + [Fact] + public async Task Direct_admission_function_returns_the_same_false_for_known_and_unknown_users() + { + await using var app = await OpenAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + await LockAsync(app, transaction, SchemaFixture.TenantA, null, true); + foreach (var user in new[] { AdminA, Guid.CreateVersion7() }) + (await ScalarAsync(app, transaction, + "SELECT public.fn_identity_admin_admission_state(@user,@tenant)", + ("user", user), ("tenant", SchemaFixture.TenantA))).Should().BeFalse(); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.Contention.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.Contention.cs new file mode 100644 index 000000000..3e94ce1cf --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.Contention.cs @@ -0,0 +1,144 @@ +using System.Diagnostics; +using FluentAssertions; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Application.Abstractions; +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Application.Seeding; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.Modules.Tenancy.Infrastructure.Persistence; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Results; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.SharedKernel.Time; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class IdentityMembershipTests +{ + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Post_acquisition_row_timeout_is_a_fixed_conflict_and_the_seed_handler_refuses_without_partial_profile(bool throughHandler) + { + await using var database = await DisposableSchemaDatabase.CreateAsync(fixture.Postgres); + await SeedSchemaAsync(database.MigrationConnectionString, database.AppConnectionString); + var tenant = TenantId.From(SchemaFixture.TenantA); + await SeedFoundationTenantAsync(database.AppConnectionString, tenant); + await using var blocker = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await using (var preparation = await blocker.BeginTransactionAsync()) + { + await ScopeAsync(blocker, preparation, tenant.Value); + await LockAsync(blocker, preparation, tenant.Value, null, false); + await ExecuteAsync(blocker, preparation, """ + UPDATE public.membership_profiles SET display_name=NULL,preferred_locale=NULL WHERE membership_id=@member; + SET CONSTRAINTS ALL IMMEDIATE; + """, ("member", LearnerMembershipA)); + await preparation.CommitAsync(); + } + await using var held = await blocker.BeginTransactionAsync(); + await ScopeAsync(blocker, held, tenant.Value); + await LockAsync(blocker, held, tenant.Value, null, false); + (await ScalarAsync(blocker, held, "SELECT id FROM public.memberships WHERE id=@member FOR NO KEY UPDATE", + ("member", LearnerMembershipA))).Should().Be(LearnerMembershipA); + + await using var source = ApplicationDataSource.Build(database.AppConnectionString); + await using var unit = new NpgsqlUnitOfWork(source, NullLogger.Instance); + await using var frame = await unit.BeginTransactionAsync(); + await unit.SetProvisioningTenantContextAsync(tenant); + var context = new FoundationProofContext(tenant); + await using var db = new IdentityDbContext(new DbContextOptionsBuilder().UseNpgsql(unit.Connection).Options, + new StaticTenantContextAccessor(context), EmptyIdentityScope.Instance); + await db.Database.UseTransactionAsync(unit.Transaction); + var store = new MembershipWriteStore(db, new ContextualIdentityStorageControl(db, unit)); + var locks = new IdentityMutationLocks(unit); + Task>? handled = null; + Task pending; + var started = Stopwatch.StartNew(); + if (throughHandler) + { + var role = RoleId(tenant.Value, BuiltInRoleKey.Learner, PermissionScope.Tenant); + var fingerprint = IdentityFoundationManifest.Version1.ProfileFingerprint(tenant, null, LearnerMembershipA, "timeout-proof", "en"); + var command = new SetSeedMembershipProfileCommand(LearnerMembershipA, UserId.From(PersonA), role, + PermissionScope.Tenant, "timeout-proof", "en", 1, fingerprint); + var admission = new FoundationProofAdmission(new SeedIdentityFoundationAct(SeedIdentityFoundationOperation.SetProfile, tenant, null, + UserId.SystemActor, LearnerMembershipA, UserId.From(PersonA), role, null, PermissionScope.Tenant, 1, fingerprint)); + var handler = new SetSeedMembershipProfileCommandHandler(store, context, admission, + new IdentityScopeLifecycleReader(unit), locks, new SystemClock()); + handled = handler.Handle(command, CancellationToken.None); + pending = handled; + } + else + { + await locks.AcquireAsync(new([], tenant, IdentityTenantLockMode.Shared)); + var membership = (await store.FindAsync(MembershipId.From(LearnerMembershipA)))!; + membership.SetProfile("timeout-proof", "en", DateTimeOffset.UtcNow, UserId.SystemActor).IsSuccess.Should().BeTrue(); + pending = store.UpdateAsync(membership); + } + await using var observer = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await WaitForBlockingBackendAsync(observer, ((NpgsqlConnection)unit.Connection).ProcessID, blocker.ProcessID); + pending.IsCompleted.Should().BeFalse("the actual UPDATE, after advisory acquisition, is waiting on the Membership row"); + if (throughHandler) + { + var result = await handled!; + result.IsFailure.Should().BeTrue(); + result.Error!.Code.Should().Be("identity_foundation_refused"); + } + else + { + var failure = (await FluentActions.Awaiting(() => pending).Should().ThrowAsync()).Which; + failure.Failure.Should().Be(IdentityFoundationStorageFailure.Conflict); + failure.InnerException.Should().BeNull(); + } + started.Elapsed.Should().BeGreaterThan(TimeSpan.FromSeconds(1.5)).And.BeLessThan(TimeSpan.FromSeconds(8)); + unit.IsRollbackOnly.Should().BeTrue(); + db.Database.AutoSavepointsEnabled.Should().BeTrue(); + await frame.FailAsync(); + await held.RollbackAsync(); + await using var read = await blocker.BeginTransactionAsync(); + await ScopeAsync(blocker, read, tenant.Value); + (await ScalarAsync(blocker, read, """ + SELECT count(*) FROM public.memberships member + JOIN public.membership_profiles profile ON profile.tenant_id=member.tenant_id AND profile.membership_id=member.id + WHERE member.id=@member AND member.row_version=0 AND profile.display_name IS NULL AND profile.preferred_locale IS NULL + """, ("member", LearnerMembershipA))).Should().Be(1); + } + + private static async Task SeedFoundationTenantAsync(string connectionString, TenantId tenant) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, tenant.Value); + await ExecuteAsync(app, transaction, """ + INSERT INTO public.tenants(id,slug,display_name,status,created_at,created_by,row_version) + VALUES(@tenant,@slug,'Foundation proof','Trial',clock_timestamp(),@actor,0) + """, ("tenant", tenant.Value), ("slug", "foundation-" + tenant.Value.ToString("N")), ("actor", UserId.SystemActor.Value)); + await transaction.CommitAsync(); + } + + private sealed class FoundationProofAdmission(params SeedIdentityFoundationAct[] permitted) : ISeedIdentityFoundationAdmission + { + public ValueTask AllowsFoundationAsync(SeedIdentityFoundationAct act, CancellationToken cancellationToken = default) => + ValueTask.FromResult(permitted.Contains(act)); + public ValueTask AllowsAsync(GlobalIdentitySubject subject, UserId declaredActor, CancellationToken cancellationToken = default) => + ValueTask.FromResult(false); + } + + private sealed class FoundationProofContext(TenantId tenant) : ITenantContext + { + public bool IsResolved => true; + public TenantContextOrigin? Origin => TenantContextOrigin.Ambient; + public TenantId TenantId => tenant; + public OrganizationId? OrganizationId => null; + 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/IdentityMembershipTests.FirstAdmin.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.FirstAdmin.cs new file mode 100644 index 000000000..5197fb767 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.FirstAdmin.cs @@ -0,0 +1,104 @@ +using System.Diagnostics; +using FluentAssertions; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; +using LearnStack.Tools.Seeder; +using MediatR; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class IdentityMembershipTests +{ + [Fact] + public async Task Competing_actual_first_admin_commands_recheck_history_after_the_tenant_wait_and_commit_exactly_one_graph() + { + await using var database = await DisposableSchemaDatabase.CreateAsync(fixture.Postgres); + await SeedSchemaAsync(database.MigrationConnectionString, database.AppConnectionString); + var tenant = TenantId.From(Guid.CreateVersion7()); + await SeedFoundationTenantAsync(database.AppConnectionString, tenant); + var role = Guid.CreateVersion7(); + var manifest = IdentityFoundationManifest.Version1; + var roleFingerprint = manifest.RoleFingerprint(tenant, role, BuiltInRoleKey.TenantAdmin, PermissionScope.Tenant); + var firstId = Guid.CreateVersion7(); + var secondId = Guid.CreateVersion7(); + var first = new CreateFirstSeedAdminMembershipCommand(firstId, UserId.From(PersonA), role, 1, + manifest.MembershipFingerprint(tenant, null, firstId, UserId.From(PersonA), role)); + var second = new CreateFirstSeedAdminMembershipCommand(secondId, UserId.From(PersonB), role, 1, + manifest.MembershipFingerprint(tenant, null, secondId, UserId.From(PersonB), role)); + var admission = new FoundationProofAdmission( + new(SeedIdentityFoundationOperation.InitializeRole, tenant, null, UserId.SystemActor, role, + null, null, BuiltInRoleKey.TenantAdmin, PermissionScope.Tenant, 1, roleFingerprint), + new(SeedIdentityFoundationOperation.CreateFirstAdmin, tenant, null, UserId.SystemActor, firstId, + first.UserId, role, null, PermissionScope.Tenant, 1, first.ExpectedFingerprint), + new(SeedIdentityFoundationOperation.CreateFirstAdmin, tenant, null, UserId.SystemActor, secondId, + second.UserId, role, null, PermissionScope.Tenant, 1, second.ExpectedFingerprint)); + var context = new FoundationProofContext(tenant); + await using var source = ApplicationDataSource.Build(database.AppConnectionString); + await using (var provider = SeedComposition.Build(source, context, NullLoggerFactory.Instance, + identityAuthority: Authority, seedAdmission: admission)) + { + await using var scope = provider.CreateAsyncScope(); + var initialized = await scope.ServiceProvider.GetRequiredService().Send( + new InitializeSeedRoleCommand(role, BuiltInRoleKey.TenantAdmin, PermissionScope.Tenant, 1, roleFingerprint)); + initialized.IsSuccess.Should().BeTrue(); + } + + await using var blocker = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await using var held = await blocker.BeginTransactionAsync(); + await ScopeAsync(blocker, held, tenant.Value); + await LockAsync(blocker, held, tenant.Value, null, true); + (await ScalarAsync(blocker, held, "SELECT count(*) FROM public.memberships")).Should().Be(0); + await using var leftProvider = SeedComposition.Build(source, context, NullLoggerFactory.Instance, + identityAuthority: Authority, seedAdmission: admission); + await using var rightProvider = SeedComposition.Build(source, context, NullLoggerFactory.Instance, + identityAuthority: Authority, seedAdmission: admission); + await using var left = leftProvider.CreateAsyncScope(); + await using var right = rightProvider.CreateAsyncScope(); + var leftTask = left.ServiceProvider.GetRequiredService().Send(first); + var rightTask = right.ServiceProvider.GetRequiredService().Send(second); + await using var observer = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + var budget = Stopwatch.StartNew(); + var waiting = false; + while (budget.Elapsed < TimeSpan.FromSeconds(5)) + { + if (await ScalarAsync(observer, null, """ + SELECT count(*) FROM pg_catalog.pg_locks + WHERE locktype='advisory' AND NOT granted AND objsubid=1 + AND database=(SELECT oid FROM pg_catalog.pg_database WHERE datname=current_database()) + AND ((classid::bigint << 32) | objid::bigint)=@key + """, ("key", IdentityAdvisoryLockKey.ForTenant(tenant))) == 2) + { + waiting = true; + break; + } + if (leftTask.IsCompleted || rightTask.IsCompleted) break; + await Task.Delay(10); + } + // Release before assertions so a failed observation cannot leave either + // actual command blocked while its scope is being disposed. + await held.CommitAsync(); + var results = await Task.WhenAll(leftTask, rightTask); + waiting.Should().BeTrue("both commands must pass their pre-lock absence read before either can commit"); + var winner = results.Should().ContainSingle(result => result.IsSuccess).Which.Value; + results.Should().ContainSingle(result => result.IsFailure).Which.Error!.Code.Should().Be("identity_foundation_refused"); + await using var read = await blocker.BeginTransactionAsync(); + await ScopeAsync(blocker, read, tenant.Value); + foreach (var table in new[] { "memberships", "membership_profiles", "membership_role_assignments" }) + (await ScalarAsync(blocker, read, $"SELECT count(*) FROM public.{table}")).Should().Be(1); + (await ScalarAsync(blocker, read, "SELECT id FROM public.memberships")).Should().Be(winner); + (await ScalarAsync(blocker, read, """ + SELECT count(*) FROM public.audit_log + WHERE operation='identity.membership.create_first_seed_admin' AND outcome='success' AND entity_id=@member + """, ("member", winner.ToString("D")))).Should().Be(1, + "the winning real command commits its central MUST row with the sole initial Membership graph"); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.Isolation.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.Isolation.cs new file mode 100644 index 000000000..5af38df3d --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.Isolation.cs @@ -0,0 +1,83 @@ +using FluentAssertions; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Permissions; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class IdentityMembershipTests +{ + public static IReadOnlyDictionary WithCheckProofs { get; } = + new Dictionary(StringComparer.Ordinal) + { + ["memberships"] = nameof(Contextual_WITH_CHECK_rejects_foreign_writes_and_its_dirty_twin_admits_them), + ["membership_profiles"] = nameof(Contextual_WITH_CHECK_rejects_foreign_writes_and_its_dirty_twin_admits_them), + ["membership_role_assignments"] = nameof(Contextual_WITH_CHECK_rejects_foreign_writes_and_its_dirty_twin_admits_them), + ["roles"] = nameof(Contextual_WITH_CHECK_rejects_foreign_writes_and_its_dirty_twin_admits_them), + ["role_permission_grants"] = nameof(Contextual_WITH_CHECK_rejects_foreign_writes_and_its_dirty_twin_admits_them), + }; + + [Theory] + [InlineData("memberships")] + [InlineData("membership_profiles")] + [InlineData("membership_role_assignments")] + [InlineData("roles")] + [InlineData("role_permission_grants")] + 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); + await SeedSchemaAsync(database.MigrationConnectionString, database.AppConnectionString); + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString); + var usingClause = await ScalarAsync(owner, null, + "SELECT pg_get_expr(polqual,polrelid) FROM pg_policy WHERE polrelid=@table::regclass AND polname=@policy", + ("table", "public." + table), ("policy", table + "_isolation")); + var checkClause = await ScalarAsync(owner, null, + "SELECT pg_get_expr(polwithcheck,polrelid) FROM pg_policy WHERE polrelid=@table::regclass AND polname=@policy", + ("table", "public." + table), ("policy", table + "_isolation")); + // This disposable control isolates WITH CHECK from the earlier lock and + // User admission guards. The dirty twin changes only that policy clause. + await ExecuteAsync(owner, null, $"ALTER TABLE public.{table} DISABLE TRIGGER tg_{table}_mutation_guard; ALTER POLICY {table}_isolation ON public.{table} USING (true)"); + if (table is "memberships" or "membership_role_assignments") + await ExecuteAsync(owner, null, $"ALTER TABLE public.{table} DISABLE TRIGGER tg_{table}_admission"); + try + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + var mutation = table switch + { + "memberships" => "UPDATE public.memberships SET row_version=row_version+1 WHERE id=@member", + "membership_profiles" => "UPDATE public.membership_profiles SET display_name='foreign-policy-control' WHERE membership_id=@member", + "roles" => "UPDATE public.roles SET row_version=row_version+1 WHERE id=@role", + "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)]; + await using (var clean = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, clean, SchemaFixture.TenantA); + var denied = () => ExecuteAsync(app, clean, mutation, values); + (await denied.Should().ThrowAsync()).Which.SqlState.Should().Be("42501"); + await clean.RollbackAsync(); + } + await ExecuteAsync(owner, null, $"ALTER POLICY {table}_isolation ON public.{table} WITH CHECK (true)"); + await using (var dirty = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, dirty, SchemaFixture.TenantA); + await ExecuteAsync(app, dirty, mutation, values); + await dirty.RollbackAsync(); + } + } + finally + { + await ExecuteAsync(owner, null, $"ALTER POLICY {table}_isolation ON public.{table} USING ({usingClause}) WITH CHECK ({checkClause}); ALTER TABLE public.{table} ENABLE TRIGGER tg_{table}_mutation_guard"); + if (table is "memberships" or "membership_role_assignments") + await ExecuteAsync(owner, null, $"ALTER TABLE public.{table} ENABLE TRIGGER tg_{table}_admission"); + } + (await ScalarAsync(owner, null, + "SELECT pg_get_expr(polwithcheck,polrelid) FROM pg_policy WHERE polrelid=@table::regclass AND polname=@policy", + ("table", "public." + table), ("policy", table + "_isolation"))).Should().Be(checkClause); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.Migrations.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.Migrations.cs new file mode 100644 index 000000000..8720357bb --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.Migrations.cs @@ -0,0 +1,167 @@ +using FluentAssertions; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class IdentityMembershipTests +{ + [Fact] + public async Task Parent_mirror_correction_replaces_only_its_function_and_reapplies_the_fresh_chain_exactly() + { + const string Predecessor = "20261025232309_add_contextual_identity"; + const string Correction = "20261026035353_correct_identity_parent_mirror_sqlstate"; + const string Guard = "fn_identity_contextual_mutation_guard()"; + await using var database = await DisposableSchemaDatabase.CreateAsync(fixture.Postgres); + await IdentityMembershipFixture.SeedSchemaAsync(database.MigrationConnectionString, database.AppConnectionString); + await using var context = new IdentityDbContext(new DbContextOptionsBuilder() + .UseNpgsql(database.MigrationConnectionString, options => + options.MigrationsHistoryTable(IdentityDbContextFactory.HistoryTable)).Options, + StaticTenantContextAccessor.Unresolved, EmptyIdentityScope.Instance); + context.Database.HasPendingModelChanges().Should().BeFalse(); + var fresh = await ReadIdentityFunctionsAsync(database); + fresh.Should().HaveCountGreaterThan(1, "the replacement must preserve actual sibling functions"); + await context.GetService().MigrateAsync(Correction); + var corrected = await ReadIdentityFunctionsAsync(database); + await AssertParentMirrorFailureAsync(database, "23514", "membership_parent_scope"); + + await context.GetService().MigrateAsync(Predecessor); + var predecessor = await ReadIdentityFunctionsAsync(database); + await AssertParentMirrorFailureAsync(database, "P0304", null); + var previousGuard = predecessor.Except(corrected).Should().ContainSingle().Which; + var correctedGuard = corrected.Except(predecessor).Should().ContainSingle().Which; + previousGuard.Identity.Should().Be(Guard); + correctedGuard.Identity.Should().Be(Guard); + (correctedGuard with { Definition = previousGuard.Definition }).Should().Be(previousGuard, + "CREATE OR REPLACE retains the same function OID, owner, ACL, volatility, invoker mode and search path"); + correctedGuard.Owner.Should().Be("learnstack_migration"); + correctedGuard.SecurityDefiner.Should().BeFalse(); + correctedGuard.Volatility.Should().Be("v"); + correctedGuard.Configuration.Should().Be("search_path=pg_catalog"); + previousGuard.Definition.Should().NotContain("membership_parent_scope"); + correctedGuard.Definition.Should().Contain("ERRCODE = '23514', CONSTRAINT = 'membership_parent_scope'"); + + await context.GetService().MigrateAsync(Correction); + (await ReadIdentityFunctionsAsync(database)).Should().Equal(corrected); + await AssertParentMirrorFailureAsync(database, "23514", "membership_parent_scope"); + await context.GetService().MigrateAsync(Predecessor); + (await ReadIdentityFunctionsAsync(database)).Should().Equal(predecessor); + await AssertParentMirrorFailureAsync(database, "P0304", null); + await context.GetService().MigrateAsync(Correction); + (await ReadIdentityFunctionsAsync(database)).Should().Equal(corrected); + await AssertParentMirrorFailureAsync(database, "23514", "membership_parent_scope"); + await context.Database.MigrateAsync(); + (await ReadIdentityFunctionsAsync(database)).Should().Equal(fresh); + context.Database.HasPendingModelChanges().Should().BeFalse(); + } + + [Fact] + public async Task Admission_parent_correction_preserves_its_definer_boundary_and_converges_with_the_fresh_chain() + { + const string Predecessor = "20261026035353_correct_identity_parent_mirror_sqlstate"; + const string Correction = "20261026043921_correct_identity_admission_parent_sqlstate"; + const string Guard = "fn_identity_membership_admission_guard()"; + await using var database = await DisposableSchemaDatabase.CreateAsync(fixture.Postgres); + await IdentityMembershipFixture.SeedSchemaAsync(database.MigrationConnectionString, database.AppConnectionString); + await using var context = new IdentityDbContext(new DbContextOptionsBuilder() + .UseNpgsql(database.MigrationConnectionString, options => + options.MigrationsHistoryTable(IdentityDbContextFactory.HistoryTable)).Options, + StaticTenantContextAccessor.Unresolved, EmptyIdentityScope.Instance); + context.Database.HasPendingModelChanges().Should().BeFalse(); + var fresh = await ReadIdentityFunctionsAsync(database); + await context.GetService().MigrateAsync(Correction); + var corrected = await ReadIdentityFunctionsAsync(database); + await AssertAdmissionParentFailureAsync(database, corrected: true); + + await context.GetService().MigrateAsync(Predecessor); + var predecessor = await ReadIdentityFunctionsAsync(database); + await AssertAdmissionParentFailureAsync(database, corrected: false); + var previousGuard = predecessor.Except(corrected).Should().ContainSingle().Which; + var correctedGuard = corrected.Except(predecessor).Should().ContainSingle().Which; + previousGuard.Identity.Should().Be(Guard); + correctedGuard.Identity.Should().Be(Guard); + (correctedGuard with { Definition = previousGuard.Definition }).Should().Be(previousGuard, + "the diagnostic correction retains function identity, ownership, ACL and the existing definer boundary"); + correctedGuard.Owner.Should().Be("learnstack_migration"); + correctedGuard.SecurityDefiner.Should().BeTrue(); + correctedGuard.Volatility.Should().Be("v"); + correctedGuard.Configuration.Should().Be("search_path=pg_catalog"); + previousGuard.Definition.Should().NotContain("membership_parent_scope"); + correctedGuard.Definition.Should().Contain("ERRCODE = '23514', CONSTRAINT = 'membership_parent_scope'") + .And.Contain("IF eligible IS NOT TRUE THEN\n RAISE EXCEPTION 'identity membership target is unavailable' USING ERRCODE = 'P0302';"); + + await context.GetService().MigrateAsync(Correction); + (await ReadIdentityFunctionsAsync(database)).Should().Equal(corrected); + await AssertAdmissionParentFailureAsync(database, corrected: true); + await context.GetService().MigrateAsync(Predecessor); + (await ReadIdentityFunctionsAsync(database)).Should().Equal(predecessor); + await AssertAdmissionParentFailureAsync(database, corrected: false); + await context.GetService().MigrateAsync(Correction); + (await ReadIdentityFunctionsAsync(database)).Should().Equal(corrected); + await AssertAdmissionParentFailureAsync(database, corrected: true); + await context.Database.MigrateAsync(); + (await ReadIdentityFunctionsAsync(database)).Should().Equal(fresh); + context.Database.HasPendingModelChanges().Should().BeFalse(); + } + + private static async Task AssertAdmissionParentFailureAsync(DisposableSchemaDatabase database, bool corrected) + { + foreach (var parent in new[] { "missing", "hidden" }) + { + var failure = await ParentMirrorStackFailureAsync(database.AppConnectionString, "assignment", parent); + failure.SqlState.Should().Be(corrected ? "23514" : "P0302"); + failure.ConstraintName.Should().Be(corrected ? "membership_parent_scope" : null); + failure.MessageText.Should().Be(corrected ? "identity graph is invalid" : "identity membership target is unavailable"); + failure.Detail.Should().BeNull(); + } + } + + private static async Task AssertParentMirrorFailureAsync(DisposableSchemaDatabase database, + string sqlState, string? constraint) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA, SchemaFixture.OrgA1); + await LockAsync(app, transaction, SchemaFixture.TenantA, PersonA, false); + var write = () => ExecuteAsync(app, transaction, + "INSERT INTO public.membership_role_assignments(tenant_id,membership_id,organization_id,role_id) VALUES(@tenant,@member,@organization,@role)", + ("tenant", SchemaFixture.TenantA), ("member", LearnerMembershipA), ("organization", SchemaFixture.OrgA1), + ("role", RoleId(SchemaFixture.TenantA, BuiltInRoleKey.Learner, PermissionScope.Organization))); + var failure = (await write.Should().ThrowAsync()).Which; + failure.SqlState.Should().Be(sqlState); + failure.ConstraintName.Should().Be(constraint); + failure.MessageText.Should().Be("identity graph is invalid"); + failure.Detail.Should().BeNull(); + } + + private static async Task> ReadIdentityFunctionsAsync(DisposableSchemaDatabase database) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString); + await using var query = new NpgsqlCommand(""" + SELECT proc.oid::regprocedure::text, proc.oid::bigint, pg_get_userbyid(proc.proowner), + proc.prosecdef, proc.provolatile::text, COALESCE(array_to_string(proc.proconfig, ','), ''), + COALESCE(proc.proacl::text, ''), pg_get_functiondef(proc.oid) + FROM pg_proc AS proc + WHERE proc.pronamespace = 'public'::regnamespace AND proc.proname LIKE 'fn_identity_%' + ORDER BY proc.oid::regprocedure::text + """, owner); + await using var reader = await query.ExecuteReaderAsync(); + var functions = new List(); + while (await reader.ReadAsync()) + functions.Add(new(reader.GetString(0), reader.GetInt64(1), reader.GetString(2), reader.GetBoolean(3), + reader.GetString(4), reader.GetString(5), reader.GetString(6), reader.GetString(7))); + return functions; + } + + private sealed record IdentityFunction(string Identity, long Oid, string Owner, bool SecurityDefiner, + string Volatility, string Configuration, string Acl, string Definition); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.OrgWriteControls.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.OrgWriteControls.cs new file mode 100644 index 000000000..30fe026d2 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.OrgWriteControls.cs @@ -0,0 +1,97 @@ +using FluentAssertions; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class IdentityMembershipTests +{ + [Theory] + [InlineData("memberships", "42501")] + [InlineData("membership_profiles", "23514")] + [InlineData("membership_role_assignments", "23514")] + public async Task Restrictive_org_write_policy_filters_rows_before_independent_guards_and_its_dirty_twin_reaches_them( + string table, string expectedState) + { + var (policy, mutation, targetColumn) = table switch + { + "memberships" => ("memberships_org_write_guard", + "UPDATE public.memberships SET row_version=row_version WHERE id=@member RETURNING 1", "id"), + "membership_profiles" => ("membership_profiles_org_write_guard", + "UPDATE public.membership_profiles SET display_name=display_name WHERE membership_id=@member RETURNING 1", "membership_id"), + "membership_role_assignments" => ("membership_role_assignments_org_delete_guard", + "DELETE FROM public.membership_role_assignments WHERE membership_id=@member RETURNING 1", "membership_id"), + _ => throw new ArgumentOutOfRangeException(nameof(table)), + }; + 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); + var original = await OrgWriteControlCensusAsync(owner); + var predicate = await ScalarAsync(owner, null, + "SELECT pg_get_expr(polqual,polrelid) FROM pg_policy WHERE polrelid=@table::regclass AND polname=@policy AND NOT polpermissive", + ("table", "public." + table), ("policy", policy)); + predicate.Should().NotBeNullOrWhiteSpace("the actual restrictive policy is the isolated control"); + var countedMutation = "WITH changed AS (" + mutation + ") SELECT count(*) FROM changed"; + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + await AssertFilteredAsync(); + try + { + // The target restrictive USING clause alone changes. The ordinary + // WITH CHECK, parent lock/read, triggers and grants remain intact. + await ExecuteAsync(owner, null, $"ALTER POLICY {policy} ON public.{table} USING (true)"); + await using var dirty = await app.BeginTransactionAsync(); + await AnnounceOrgWriteControlAsync(app, dirty); + Func write = () => ScalarAsync(app, dirty, countedMutation, ("member", BranchMembershipA2)); + var refusal = (await write.Should().ThrowAsync()).Which; + refusal.SqlState.Should().Be(expectedState); + if (expectedState == "23514") + refusal.ConstraintName.Should().Be("membership_parent_scope"); + await dirty.RollbackAsync(); + } + finally + { + await ExecuteAsync(owner, null, $"ALTER POLICY {policy} ON public.{table} USING ({predicate})"); + } + (await OrgWriteControlCensusAsync(owner)).Should().Be(original, + "the fixture restores exact policies, triggers, function bodies and grants"); + await AssertFilteredAsync(); + + async Task AssertFilteredAsync() + { + await using var clean = await app.BeginTransactionAsync(); + await AnnounceOrgWriteControlAsync(app, clean); + (await ScalarAsync(app, clean, + $"SELECT count(*) FROM public.{table} WHERE {targetColumn}=@member", + ("member", BranchMembershipA2))).Should().Be(1, + "the tenant read hatch exposes the existing other-organization row"); + (await ScalarAsync(app, clean, countedMutation, ("member", BranchMembershipA2))).Should().Be(0, + "the restrictive policy filters the row before independent guards run"); + await clean.RollbackAsync(); + } + } + + private static async Task AnnounceOrgWriteControlAsync(NpgsqlConnection app, NpgsqlTransaction transaction) + { + await ScopeAsync(app, transaction, SchemaFixture.TenantA, SchemaFixture.OrgA1); + await ExecuteAsync(app, transaction, "SELECT set_config('app.scope','tenant',true)"); + await LockAsync(app, transaction, SchemaFixture.TenantA, null, false); + } + + private static Task OrgWriteControlCensusAsync(NpgsqlConnection owner) => ScalarAsync(owner, null, """ + SELECT jsonb_build_object( + 'policies',(SELECT jsonb_agg(jsonb_build_array(polrelid,polname,polpermissive,polroles,polcmd, + pg_get_expr(polqual,polrelid),pg_get_expr(polwithcheck,polrelid)) ORDER BY polrelid,polname) + FROM pg_policy WHERE polrelid IN ('public.memberships'::regclass, + 'public.membership_profiles'::regclass,'public.membership_role_assignments'::regclass)), + 'triggers',(SELECT jsonb_agg(jsonb_build_array(tgrelid,tgname,tgenabled,pg_get_triggerdef(oid)) ORDER BY tgrelid,tgname) + FROM pg_trigger WHERE NOT tgisinternal AND tgrelid IN ('public.memberships'::regclass, + 'public.membership_profiles'::regclass,'public.membership_role_assignments'::regclass)), + 'functions',(SELECT jsonb_agg(jsonb_build_array(proname,prosrc,prosecdef,provolatile,proconfig,proacl::text,proowner) ORDER BY proname) + FROM pg_proc WHERE pronamespace='public'::regnamespace AND proname LIKE 'fn_identity_%'), + 'table_acl',(SELECT jsonb_agg(jsonb_build_array(oid,relacl::text) ORDER BY oid) + FROM pg_class WHERE oid IN ('public.memberships'::regclass, + 'public.membership_profiles'::regclass,'public.membership_role_assignments'::regclass)))::text + """); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.ParentLifecycle.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.ParentLifecycle.cs new file mode 100644 index 000000000..fc9d4697e --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.ParentLifecycle.cs @@ -0,0 +1,115 @@ +using System.Diagnostics; +using FluentAssertions; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.Tools.Seeder; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class IdentityMembershipTests +{ + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Assignment_addition_serializes_with_Membership_Revoke_and_the_predecessor_exposes_the_race(bool corrected) + { + await using var database = await DisposableSchemaDatabase.CreateAsync(fixture.Postgres); + await SeedSchemaAsync(database.MigrationConnectionString, database.AppConnectionString); + await using var migration = new IdentityDbContext(new DbContextOptionsBuilder() + .UseNpgsql(database.MigrationConnectionString, options => + options.MigrationsHistoryTable(IdentityDbContextFactory.HistoryTable)).Options, + StaticTenantContextAccessor.Unresolved, EmptyIdentityScope.Instance); + var currentFunctions = await ReadIdentityFunctionsAsync(database); + await migration.GetService().MigrateAsync("20261026043921_correct_identity_admission_parent_sqlstate"); + var predecessorFunctions = await ReadIdentityFunctionsAsync(database); + var currentGuard = currentFunctions.Except(predecessorFunctions).Should().ContainSingle().Which; + var previousGuard = predecessorFunctions.Except(currentFunctions).Should().ContainSingle().Which; + currentGuard.Identity.Should().Be("fn_identity_contextual_mutation_guard()"); + (currentGuard with { Definition = previousGuard.Definition }).Should().Be(previousGuard, + "the forward replacement preserves function identity, owner, ACL, volatility and execution mode"); + currentGuard.Definition.Should().Be(previousGuard.Definition.Replace( + "target_member FOR KEY SHARE;", "target_member FOR NO KEY UPDATE;", StringComparison.Ordinal)); + if (corrected) + { + await migration.Database.MigrateAsync(); + (await ReadIdentityFunctionsAsync(database)).Should().Equal(currentFunctions); + } + migration.Database.HasPendingModelChanges().Should().BeFalse(); + + await using var source = ApplicationDataSource.Build(database.AppConnectionString); + await using var revoker = new NpgsqlUnitOfWork(source, NullLogger.Instance); + await using var retirement = await revoker.BeginTransactionAsync(); + var tenant = TenantId.From(SchemaFixture.TenantA); + await revoker.SetProvisioningTenantContextAsync(tenant); + await new IdentityMutationLocks(revoker).AcquireAsync(new([], tenant, IdentityTenantLockMode.Shared)); + await using var db = new IdentityDbContext(new DbContextOptionsBuilder().UseNpgsql(revoker.Connection).Options, + new StaticTenantContextAccessor(new SeedTenantContext(tenant, null)), EmptyIdentityScope.Instance); + await db.Database.UseTransactionAsync(revoker.Transaction); + var store = new MembershipWriteStore(db, new ContextualIdentityStorageControl(db, revoker)); + var membership = (await store.FindAsync(MembershipId.From(LearnerMembershipA)))!; + membership.Revoke(DateTimeOffset.UtcNow, UserId.SystemActor).IsSuccess.Should().BeTrue(); + await store.UpdateAsync(membership); + await store.ValidateGraphAsync(); + (await ScalarAsync((NpgsqlConnection)revoker.Connection, (NpgsqlTransaction)revoker.Transaction!, + "SELECT public.fn_identity_lock_held('user',@user,true)", ("user", PersonA))).Should().BeFalse( + "nonadministrator revocation keeps its accepted shared tenant plan without a new User fence"); + + await using var inserter = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await using var observer = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(inserter); + await using var addition = await inserter.BeginTransactionAsync(); + await ScopeAsync(inserter, addition, tenant.Value); + await LockAsync(inserter, addition, tenant.Value, PersonA, false); + var instructor = RoleId(tenant.Value, BuiltInRoleKey.Instructor, PermissionScope.Tenant); + var pending = ExecuteAsync(inserter, addition, """ + INSERT INTO public.membership_role_assignments(tenant_id,membership_id,role_id) + VALUES(@tenant,@member,@role) + """, ("tenant", tenant.Value), ("member", LearnerMembershipA), ("role", instructor)); + if (corrected) + { + await WaitForBlockingBackendAsync(observer, inserter.ProcessID, ((NpgsqlConnection)revoker.Connection).ProcessID); + pending.IsCompleted.Should().BeFalse(); + await retirement.CompleteAsync(); + (await FluentActions.Awaiting(() => pending).Should().ThrowAsync()).Which.SqlState.Should().Be("P0304", + "the locking read must see the committed Revoked lifecycle before admitting the child"); + await addition.RollbackAsync(); + } + else + { + await pending.WaitAsync(TimeSpan.FromSeconds(5)); + await ExecuteAsync(inserter, addition, "SET CONSTRAINTS ALL IMMEDIATE"); + await addition.CommitAsync(); + await retirement.CompleteAsync(); + } + await using var read = await inserter.BeginTransactionAsync(); + await ScopeAsync(inserter, read, tenant.Value); + (await ScalarAsync(inserter, read, "SELECT status FROM public.memberships WHERE id=@member", + ("member", LearnerMembershipA))).Should().Be("Revoked"); + (await ScalarAsync(inserter, read, "SELECT count(*) FROM public.membership_role_assignments WHERE membership_id=@member AND role_id=@role", + ("member", LearnerMembershipA), ("role", instructor))).Should().Be(corrected ? 0 : 1); + } + + private static async Task WaitForBlockingBackendAsync(NpgsqlConnection observer, int waiting, int blocker) + { + var budget = Stopwatch.StartNew(); + while (budget.Elapsed < TimeSpan.FromSeconds(5)) + { + if (await ScalarAsync(observer, null, "SELECT @blocker=ANY(pg_catalog.pg_blocking_pids(@waiting))", + ("blocker", blocker), ("waiting", waiting))) return; + await Task.Delay(10); + } + throw new InvalidOperationException("The fixture did not observe the required competing backend wait."); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.ParentMirrors.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.ParentMirrors.cs new file mode 100644 index 000000000..aeb402233 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.ParentMirrors.cs @@ -0,0 +1,88 @@ +using FluentAssertions; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Permissions; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class IdentityMembershipTests +{ + [Theory] + [InlineData("profile", "missing")] + [InlineData("profile", "hidden")] + [InlineData("profile", "mismatched")] + [InlineData("assignment", "missing")] + [InlineData("assignment", "hidden")] + [InlineData("assignment", "mismatched")] + public async Task Complete_child_trigger_stack_has_one_parent_scope_refusal(string child, string parent) + { + var failure = await ParentMirrorStackFailureAsync(fixture.Postgres.AppConnectionString, child, parent); + failure.SqlState.Should().Be("23514"); + failure.ConstraintName.Should().Be("membership_parent_scope"); + failure.MessageText.Should().Be("identity graph is invalid"); + failure.Detail.Should().BeNull(); + } + + private static async Task ParentMirrorStackFailureAsync(string appConnection, + string child, string parent) + { + var member = parent switch + { + "missing" => Guid.CreateVersion7(), + "hidden" => BranchMembershipA2, + "mismatched" => LearnerMembershipA, + _ => throw new ArgumentOutOfRangeException(nameof(parent)), + }; + if (parent == "hidden") + { + await using var visible = (NpgsqlConnection)await PostgresFixture.OpenAsync(appConnection); + await SchemaQueries.AssertApplicationRoleAsync(visible); + await using var visibleTransaction = await visible.BeginTransactionAsync(); + await ScopeAsync(visible, visibleTransaction, SchemaFixture.TenantA, SchemaFixture.OrgA2); + (await ScalarAsync(visible, visibleTransaction, + "SELECT count(*) FROM public.memberships WHERE id=@member", ("member", member))).Should().Be(1, + "the hidden parent exists and is visible through its own authenticated app-role organization scope"); + } + + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(appConnection); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA, SchemaFixture.OrgA1); + await LockAsync(app, transaction, SchemaFixture.TenantA, PersonA, false); + (await ScalarAsync(app, transaction, + "SELECT count(*) FROM public.memberships WHERE id=@member", ("member", member))).Should() + .Be(parent == "mismatched" ? 1 : 0); + + var role = RoleId(SchemaFixture.TenantA, BuiltInRoleKey.OrgInstructor, PermissionScope.Organization); + if (child == "profile") + { + await ExecuteAsync(app, transaction, + "UPDATE public.membership_profiles SET display_name='parent-mirror-control' WHERE membership_id=@member", + ("member", BranchMembershipA1)); + (await ScalarAsync(app, transaction, + "SELECT count(*) FROM public.membership_profiles WHERE membership_id=@member AND display_name='parent-mirror-control'", + ("member", BranchMembershipA1))).Should().Be(1); + } + else + { + child.Should().Be("assignment"); + await ExecuteAsync(app, transaction, + "INSERT INTO public.membership_role_assignments(tenant_id,membership_id,organization_id,role_id) VALUES(@tenant,@member,@organization,@role)", + ("tenant", SchemaFixture.TenantA), ("member", BranchMembershipA1), + ("organization", SchemaFixture.OrgA1), ("role", role)); + (await ScalarAsync(app, transaction, + "SELECT count(*) FROM public.membership_role_assignments WHERE membership_id=@member AND role_id=@role", + ("member", BranchMembershipA1), ("role", role))).Should().Be(1); + } + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + var sql = child == "profile" + ? "INSERT INTO public.membership_profiles(tenant_id,membership_id,organization_id) VALUES(@tenant,@member,@organization)" + : "INSERT INTO public.membership_role_assignments(tenant_id,membership_id,organization_id,role_id) VALUES(@tenant,@member,@organization,@role)"; + var write = () => ExecuteAsync(app, transaction, sql, + ("tenant", SchemaFixture.TenantA), ("member", member), + ("organization", SchemaFixture.OrgA1), ("role", role)); + return (await write.Should().ThrowAsync()).Which; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.Races.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.Races.cs new file mode 100644 index 000000000..9468406dd --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.Races.cs @@ -0,0 +1,254 @@ +using System.Diagnostics; +using FluentAssertions; +using LearnStack.Modules.Identity.Domain; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class IdentityMembershipTests +{ + [Theory] + [InlineData(false, "creation", UserStatus.Closing)] + [InlineData(true, "creation", UserStatus.Closing)] + [InlineData(false, "reactivation", UserStatus.Closing)] + [InlineData(false, "assignment", UserStatus.Closing)] + [InlineData(false, "creation", UserStatus.Closed)] + [InlineData(false, "reactivation", UserStatus.Closed)] + [InlineData(false, "assignment", UserStatus.Closed)] + public async Task Actual_User_fence_orders_Membership_against_a_committing_closure_and_freshly_reads_status(bool membershipWins, string operation, UserStatus targetStatus) + { + if (targetStatus is not (UserStatus.Closing or UserStatus.Closed)) throw new ArgumentOutOfRangeException(nameof(targetStatus)); + 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); + var original = await UserControlCensusAsync(owner); + var check = await ScalarAsync(owner, null, + "SELECT pg_get_expr(polwithcheck,polrelid) FROM pg_policy WHERE polrelid='public.users'::regclass AND polname='users_isolation'"); + // ADR-0074 permits this exact fixture-only accommodation. Neither missing + // app grants nor FORCE RLS alone makes the migration owner a closure writer. + await ExecuteAsync(owner, null, $""" + ALTER TABLE public.users DISABLE TRIGGER tg_users_no_update; + ALTER POLICY users_isolation ON public.users WITH CHECK (({check}) OR + (current_user='learnstack_migration' AND id='{PersonB:D}'::uuid AND status='{targetStatus}' + AND deleted_at IS NULL AND deleted_by IS NULL)); + """); + try + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await using var observer = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + var tenant = operation == "creation" ? SchemaFixture.TenantA : SchemaFixture.TenantB; + Guid? organization = operation == "creation" ? null : SchemaFixture.OrgB1; + if (operation == "reactivation") + { + await using var suspend = await app.BeginTransactionAsync(); + await ScopeAsync(app, suspend, tenant, organization); + await LockAsync(app, suspend, tenant, null, false); + await ExecuteAsync(app, suspend, "UPDATE public.memberships SET status='Suspended' WHERE id=@id", ("id", BranchMembershipB)); + await ExecuteAsync(app, suspend, "SET CONSTRAINTS ALL IMMEDIATE"); + await suspend.CommitAsync(); + } + await using var admission = await app.BeginTransactionAsync(); + await ScopeAsync(app, admission, tenant, organization); + var member = Guid.CreateVersion7(); + if (membershipWins) + { + await LockAsync(app, admission, SchemaFixture.TenantA, PersonB, false); + await InsertMemberAsync(app, admission, SchemaFixture.TenantA, null, member, PersonB, + RoleId(SchemaFixture.TenantA, BuiltInRoleKey.Learner, PermissionScope.Tenant)); + await ExecuteAsync(app, admission, "SET CONSTRAINTS ALL IMMEDIATE"); + var close = CloseUserAsync(owner, targetStatus); + await WaitForAdvisoryWaitAsync(observer, owner.ProcessID); + close.IsCompleted.Should().BeFalse(); + await admission.CommitAsync(); + await close; + await using var read = await app.BeginTransactionAsync(); + await ScopeAsync(app, read, SchemaFixture.TenantA); + (await ScalarAsync(app, read, "SELECT count(*) FROM public.memberships WHERE id=@id", ("id", member))).Should().Be(1); + await read.RollbackAsync(); + } + else + { + await using var close = await owner.BeginTransactionAsync(); + await ClosureLocksAsync(owner, close); + await TransitionUserAsync(owner, close, targetStatus); + var waiting = LockAsync(app, admission, tenant, PersonB, false); + await WaitForAdvisoryWaitAsync(observer, app.ProcessID); + waiting.IsCompleted.Should().BeFalse(); + await close.CommitAsync(); + await waiting; + Func mutate = operation switch + { + "reactivation" => () => ExecuteAsync(app, admission, "UPDATE public.memberships SET status='Active' WHERE id=@id", ("id", BranchMembershipB)), + "assignment" => () => ExecuteAsync(app, admission, + "INSERT INTO public.membership_role_assignments(tenant_id,membership_id,organization_id,role_id) VALUES(@tenant,@member,@organization,@role)", + ("tenant", tenant), ("member", BranchMembershipB), ("organization", organization), + ("role", RoleId(tenant, BuiltInRoleKey.OrgInstructor, PermissionScope.Organization))), + _ => () => InsertMemberAsync(app, admission, tenant, organization, member, PersonB, + RoleId(tenant, BuiltInRoleKey.Learner, PermissionScope.Tenant)), + }; + var refused = (await mutate.Should().ThrowAsync()).Which; + refused.SqlState.Should().Be("P0302"); + refused.MessageText.Should().Be("identity membership target is unavailable"); + await admission.RollbackAsync(); + } + (await ScalarAsync(owner, null, "SELECT status FROM public.users WHERE id=@user", ("user", PersonB))).Should().Be(targetStatus.ToString()); + if (targetStatus == UserStatus.Closed) + (await ScalarAsync(owner, null, "SELECT provider_subject IS NULL FROM public.users WHERE id=@user", ("user", PersonB))).Should().BeTrue(); + } + finally + { + await ExecuteAsync(owner, null, $"ALTER POLICY users_isolation ON public.users WITH CHECK ({check}); ALTER TABLE public.users ENABLE TRIGGER tg_users_no_update"); + } + (await UserControlCensusAsync(owner)).Should().Be(original, "the fixture restores exact bodies, ACLs, owner, policy and trigger census"); + var ownerUpdate = () => ExecuteAsync(owner, null, "UPDATE public.users SET status=status WHERE id=@user", ("user", PersonB)); + (await ownerUpdate.Should().ThrowAsync()).Which.SqlState.Should().Be("23514"); + } + + [Fact] + public async Task Shared_writers_coexist_but_exclusive_writer_waits_until_real_commit() + { + await using var first = await OpenAsync(); + await using var second = await OpenAsync(); + await using var observer = await OpenAsync(); + await using var left = await first.BeginTransactionAsync(); + await using var right = await second.BeginTransactionAsync(); + await ScopeAsync(first, left, SchemaFixture.TenantA); + await ScopeAsync(second, right, SchemaFixture.TenantA); + await LockAsync(first, left, SchemaFixture.TenantA, null, false); + await LockAsync(second, right, SchemaFixture.TenantA, null, false); + await ExecuteAsync(second, right, "UPDATE public.membership_profiles SET display_name=display_name WHERE membership_id=@id", ("id", LearnerMembershipA)); + await ExecuteAsync(second, right, "SET CONSTRAINTS ALL IMMEDIATE"); + await right.RollbackAsync(); + await using var exclusive = await second.BeginTransactionAsync(); + await ScopeAsync(second, exclusive, SchemaFixture.TenantA); + var waiting = LockAsync(second, exclusive, SchemaFixture.TenantA, null, true); + await WaitForAdvisoryWaitAsync(observer, second.ProcessID); + await left.CommitAsync(); + await waiting; + (await ScalarAsync(second, exclusive, "SELECT public.fn_identity_lock_held('tenant',@id,true)", ("id", SchemaFixture.TenantA))).Should().BeTrue(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Real_lock_timeout_or_cancellation_releases_transaction_without_partial_graph(bool cancel) + { + await using var blocker = await OpenAsync(); + await using var waiting = await OpenAsync(); + await using var observer = await OpenAsync(); + await using var held = await blocker.BeginTransactionAsync(); + await LockAsync(blocker, held, SchemaFixture.TenantA, PersonB, false); + await using var work = await waiting.BeginTransactionAsync(); + await ScopeAsync(waiting, work, SchemaFixture.TenantA); + await ExecuteAsync(waiting, work, "SET LOCAL lock_timeout='200ms'"); + using var cancellation = new CancellationTokenSource(); + await using var command = new NpgsqlCommand("SELECT pg_advisory_xact_lock(@key)", waiting, work); + command.Parameters.AddWithValue("key", IdentityAdvisoryLockKey.ForUser(UserId.From(PersonB))); + var pending = command.ExecuteNonQueryAsync(cancellation.Token); + await WaitForAdvisoryWaitAsync(observer, waiting.ProcessID); + if (cancel) + { + cancellation.Cancel(); + await FluentActions.Awaiting(async () => await pending).Should().ThrowAsync(); + } + else (await FluentActions.Awaiting(async () => await pending).Should().ThrowAsync()).Which.SqlState.Should().Be("55P03"); + await work.RollbackAsync(); + (await ScalarAsync(waiting, null, "SELECT public.fn_identity_lock_held('user',@id,true)", ("id", PersonB))).Should().BeFalse(); + } + + [Theory] + [InlineData(System.Data.IsolationLevel.RepeatableRead)] + [InlineData(System.Data.IsolationLevel.Serializable)] + public async Task Contextual_guards_refuse_incompatible_snapshot_isolation(System.Data.IsolationLevel isolation) + { + await using var app = await OpenAsync(); + await using var transaction = await app.BeginTransactionAsync(isolation); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + await LockAsync(app, transaction, SchemaFixture.TenantA, null, false); + var update = () => ExecuteAsync(app, transaction, "UPDATE public.membership_profiles SET display_name=display_name WHERE membership_id=@id", ("id", LearnerMembershipA)); + (await update.Should().ThrowAsync()).Which.SqlState.Should().Be("P0301"); + } + + [Fact] + public async Task Competing_administrator_retirements_wait_for_commit_then_preserve_the_last_admin() + { + await using var database = await DisposableSchemaDatabase.CreateAsync(fixture.Postgres); + await SeedSchemaAsync(database.MigrationConnectionString, database.AppConnectionString); + await using var first = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await using var second = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await using var observer = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + var secondAdmin = Guid.CreateVersion7(); + await using (var seed = await first.BeginTransactionAsync()) + { + await ScopeAsync(first, seed, SchemaFixture.TenantA); + await LockAsync(first, seed, SchemaFixture.TenantA, PersonB, true); + await InsertMemberAsync(first, seed, SchemaFixture.TenantA, null, secondAdmin, PersonB, + RoleId(SchemaFixture.TenantA, BuiltInRoleKey.TenantAdmin, PermissionScope.Tenant)); + await ExecuteAsync(first, seed, "SET CONSTRAINTS ALL IMMEDIATE"); + await seed.CommitAsync(); + } + await using var retirement = await first.BeginTransactionAsync(); + await ScopeAsync(first, retirement, SchemaFixture.TenantA); + await LockAsync(first, retirement, SchemaFixture.TenantA, null, true); + await ExecuteAsync(first, retirement, "UPDATE public.memberships SET status='Suspended' WHERE id=@id", ("id", AdminMembershipA)); + await ExecuteAsync(first, retirement, "SET CONSTRAINTS ALL IMMEDIATE"); + await using var competing = await second.BeginTransactionAsync(); + await ScopeAsync(second, competing, SchemaFixture.TenantA); + var waiting = LockAsync(second, competing, SchemaFixture.TenantA, null, true); + await WaitForAdvisoryWaitAsync(observer, second.ProcessID); + await retirement.CommitAsync(); + await waiting; + await ExecuteAsync(second, competing, "UPDATE public.memberships SET status='Suspended' WHERE id=@id", ("id", secondAdmin)); + var finish = () => ExecuteAsync(second, competing, "SET CONSTRAINTS ALL IMMEDIATE"); + (await finish.Should().ThrowAsync()).Which.SqlState.Should().Be("P0303"); + await competing.RollbackAsync(); + } + + private static async Task CloseUserAsync(NpgsqlConnection owner, UserStatus targetStatus) + { + await using var transaction = await owner.BeginTransactionAsync(); + await ClosureLocksAsync(owner, transaction); + await TransitionUserAsync(owner, transaction, targetStatus); + await transaction.CommitAsync(); + } + + private static Task TransitionUserAsync(NpgsqlConnection owner, NpgsqlTransaction transaction, UserStatus targetStatus) => + ExecuteAsync(owner, transaction, + "UPDATE public.users SET status=@status,provider_subject=CASE WHEN @status='Closed' THEN NULL ELSE provider_subject END WHERE id=@user", + ("status", targetStatus.ToString()), ("user", PersonB)); + + private static async Task ClosureLocksAsync(NpgsqlConnection owner, NpgsqlTransaction transaction) + { + await ExecuteAsync(owner, transaction, "SELECT pg_advisory_xact_lock(@key)", ("key", IdentityAdvisoryLockKey.ForUser(UserId.From(PersonB)))); + foreach (var tenant in new[] { SchemaFixture.TenantA, SchemaFixture.TenantB }.OrderBy(id => IdentityAdvisoryLockKey.ForTenant(TenantId.From(id)))) + await ExecuteAsync(owner, transaction, "SELECT pg_advisory_xact_lock(@key)", ("key", IdentityAdvisoryLockKey.ForTenant(TenantId.From(tenant)))); + } + + private static async Task WaitForAdvisoryWaitAsync(NpgsqlConnection observer, int pid) + { + var watch = Stopwatch.StartNew(); + while (watch.Elapsed < TimeSpan.FromSeconds(5)) + { + if (await ScalarAsync(observer, null, "SELECT EXISTS(SELECT 1 FROM pg_locks WHERE pid=@pid AND locktype='advisory' AND NOT granted)", ("pid", pid))) return; + await Task.Delay(10); + } + throw new InvalidOperationException("The fixture did not observe the required competing advisory wait."); + } + + private static Task UserControlCensusAsync(NpgsqlConnection owner) => ScalarAsync(owner, null, """ + SELECT jsonb_build_object( + 'functions',(SELECT jsonb_agg(jsonb_build_array(p.proname,p.prosrc,p.prosecdef,p.provolatile,p.proconfig,p.proacl::text,p.proowner) ORDER BY p.proname) + FROM pg_proc p WHERE p.pronamespace='public'::regnamespace AND p.proname LIKE 'fn_identity_%'), + 'triggers',(SELECT jsonb_agg(jsonb_build_array(tgname,tgenabled,pg_get_triggerdef(oid)) ORDER BY tgname) + FROM pg_trigger WHERE tgrelid='public.users'::regclass AND NOT tgisinternal), + 'policies',(SELECT jsonb_agg(jsonb_build_array(polname,polpermissive,polroles,pg_get_expr(polqual,polrelid),pg_get_expr(polwithcheck,polrelid)) ORDER BY polname) + FROM pg_policy WHERE polrelid='public.users'::regclass), + 'table_acl',(SELECT relacl::text FROM pg_class WHERE oid='public.users'::regclass))::text + """); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.Storage.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.Storage.cs new file mode 100644 index 000000000..26733d3ee --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.Storage.cs @@ -0,0 +1,77 @@ +using FluentAssertions; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Application.Abstractions; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.Modules.Tenancy.Infrastructure.Persistence; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; +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.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class IdentityMembershipTests +{ + [Theory] + [InlineData("success")] + [InlineData("constraint")] + [InlineData("cancel")] + public async Task Contextual_whole_act_save_restores_EF_default_and_every_failure_poisons_the_owner(string outcome) + { + await using var source = ApplicationDataSource.Build(fixture.Postgres.AppConnectionString); + await using var unit = new NpgsqlUnitOfWork(source, NullLogger.Instance); + await using var frame = await unit.BeginTransactionAsync(); + var tenant = TenantId.From(outcome == "constraint" ? SchemaFixture.TenantA : Guid.CreateVersion7()); + var scope = new StaticTenantContextAccessor(new SeedTenantContext(tenant, null)); + await unit.SetProvisioningTenantContextAsync(tenant); + var locks = new IdentityMutationLocks(unit); + await locks.AcquireAsync(new([], tenant, IdentityTenantLockMode.Shared)); + await using var db = new IdentityDbContext(new DbContextOptionsBuilder().UseNpgsql(unit.Connection).Options, + scope, EmptyIdentityScope.Instance); + await db.Database.UseTransactionAsync(unit.Transaction); + await using var ordinary = new TenancyDbContext(new DbContextOptionsBuilder().UseNpgsql(unit.Connection).Options, scope); + db.Database.AutoSavepointsEnabled.Should().BeTrue(); + ordinary.Database.AutoSavepointsEnabled.Should().BeTrue(); + var control = new ContextualIdentityStorageControl(db, unit); + var store = new RoleWriteStore(db, control); + var id = LearnStack.Modules.Identity.Domain.RoleId.From(Guid.CreateVersion7()); + var role = Role.Create(id, tenant, BuiltInRoleKey.Instructor, PermissionScope.Tenant, + DateTimeOffset.UtcNow, UserId.SystemActor).Value!; + using var cancellation = new CancellationTokenSource(); + if (outcome == "cancel") cancellation.Cancel(); + var save = () => store.AddAsync(role, cancellation.Token); + if (outcome == "success") + { + await save(); + await store.ValidateGraphAsync(); + unit.IsRollbackOnly.Should().BeFalse(); + (await ScalarAsync((NpgsqlConnection)unit.Connection, (NpgsqlTransaction)unit.Transaction!, + "SELECT xmin=pg_current_xact_id()::text::xid FROM public.roles WHERE id=@id", ("id", id.Value))).Should().BeTrue(); + } + else if (outcome == "constraint") + { + (await save.Should().ThrowAsync()).Which.Failure + .Should().Be(IdentityFoundationStorageFailure.Conflict); + unit.IsRollbackOnly.Should().BeTrue(); + } + else + { + await save.Should().ThrowAsync(); + unit.IsRollbackOnly.Should().BeTrue(); + } + db.Database.AutoSavepointsEnabled.Should().BeTrue("the global Identity adapter receives the unchanged default after every contextual exit"); + ordinary.Database.AutoSavepointsEnabled.Should().BeTrue("the contextual setting never alters a sibling module context"); + await frame.FailAsync(); + await using var read = await OpenAsync(); + await using var readTx = await read.BeginTransactionAsync(); + await ScopeAsync(read, readTx, tenant.Value); + (await ScalarAsync(read, readTx, "SELECT count(*) FROM public.roles WHERE id=@id", ("id", id.Value))).Should().Be(0); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.cs new file mode 100644 index 000000000..bc76f2c6a --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMembershipTests.cs @@ -0,0 +1,311 @@ +using LearnStack.Modules.Identity.Domain; +using FluentAssertions; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.Tools.Seeder; +using Microsoft.EntityFrameworkCore; +using Npgsql; +using Xunit; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed partial class IdentityMembershipTests(IdentityMembershipFixture fixture) : IClassFixture +{ + [Fact] + public async Task Populated_graphs_are_isolated_by_actual_app_RLS_and_parameterized_EF_scope() + { + await using var app = await OpenAsync(); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using var transaction = await app.BeginTransactionAsync(); + (await ScalarAsync(app, transaction, "SELECT count(*) FROM public.memberships")).Should().Be(0); + var scope = new StaticTenantContextAccessor(new SeedTenantContext(TenantId.From(SchemaFixture.TenantA), null)); + await using var db = new IdentityDbContext(new DbContextOptionsBuilder().UseNpgsql(app).Options, + scope, EmptyIdentityScope.Instance); + await db.Database.UseTransactionAsync(transaction); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + (await db.Memberships.CountAsync()).Should().Be(2); + (await db.MembershipProfiles.CountAsync()).Should().Be(2); + (await db.MembershipRoleAssignments.CountAsync()).Should().Be(2); + (await db.Roles.CountAsync()).Should().Be(8); + (await db.RolePermissionGrants.CountAsync()).Should().Be(7); + await ScopeAsync(app, transaction, SchemaFixture.TenantB); + (await db.Memberships.CountAsync()).Should().Be(0, "the independent EF filter still binds tenant A"); + (await ScalarAsync(app, transaction, "SELECT count(*) FROM public.memberships")).Should().Be(1); + await ScopeAsync(app, transaction, SchemaFixture.TenantA, SchemaFixture.OrgA1); + (await ScalarAsync(app, transaction, "SELECT count(*) FROM public.memberships")).Should().Be(3); + (await ScalarAsync(app, transaction, "SELECT count(*) FROM public.memberships WHERE organization_id=@other", ("other", SchemaFixture.OrgA2))).Should().Be(0); + await ExecuteAsync(app, transaction, "SELECT set_config('app.scope','tenant',true)"); + (await ScalarAsync(app, transaction, "SELECT count(*) FROM public.memberships")).Should().Be(4); + await LockAsync(app, transaction, SchemaFixture.TenantA, null, false); + (await ScalarAsync(app, transaction, "WITH changed AS (UPDATE public.membership_profiles SET display_name='forbidden' WHERE membership_id=@id RETURNING 1) SELECT count(*) FROM changed", ("id", BranchMembershipA2))).Should().Be(0); + (await ScalarAsync(app, transaction, "WITH changed AS (UPDATE public.membership_profiles SET display_name='forbidden' WHERE membership_id=@id RETURNING 1) SELECT count(*) FROM changed", ("id", AdminMembershipA))).Should().Be(0); + } + + [Theory] + [InlineData("missing")] + [InlineData("shared")] + [InlineData("wrong")] + [InlineData("two-int")] + [InlineData("foreign")] + public async Task Actual_admission_requires_own_backend_exclusive_single_bigint_User_fence(string mode) + { + await using var app = await OpenAsync(); + await using var other = await OpenAsync(); + await using var otherTx = await other.BeginTransactionAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + var key = IdentityAdvisoryLockKey.ForUser(UserId.From(PersonB)); + if (mode == "shared") await ExecuteAsync(app, transaction, "SELECT pg_advisory_xact_lock_shared(@key)", ("key", key)); + if (mode == "wrong") await ExecuteAsync(app, transaction, "SELECT pg_advisory_xact_lock(@key)", ("key", key ^ 1)); + if (mode == "two-int") await ExecuteAsync(app, transaction, "SELECT pg_advisory_xact_lock(@first,@second)", ("first", (int)(key >> 32)), ("second", unchecked((int)key))); + if (mode == "foreign") await ExecuteAsync(other, otherTx, "SELECT pg_advisory_xact_lock(@key)", ("key", key)); + await LockAsync(app, transaction, SchemaFixture.TenantA, null, false); + await ExecuteAsync(app, transaction, "SAVEPOINT before_admission"); + var insert = () => InsertMemberAsync(app, transaction, SchemaFixture.TenantA, null, Guid.CreateVersion7(), PersonB, + RoleId(SchemaFixture.TenantA, BuiltInRoleKey.Learner, PermissionScope.Tenant)); + (await insert.Should().ThrowAsync()).Which.SqlState.Should().Be("P0301"); + await ExecuteAsync(app, transaction, "ROLLBACK TO SAVEPOINT before_admission"); + (await ScalarAsync(app, transaction, "SELECT public.fn_identity_lock_held('user',@id,true)", ("id", PersonB))).Should().BeFalse(); + } + + [Theory] + [InlineData("019a1929-5450-7bbb-8df1-516e8e002501", 6536232317004839961L, 8764202873088396187L)] + [InlineData("01930000-0000-7000-8000-00000000a001", 7247098387317121321L, -9009402356915246337L)] + [InlineData("ffffffff-ffff-7fff-bfff-ffffffffffff", -2062124468225165546L, 7755294501392127735L)] + public async Task SQL_and_CSharp_User_and_Tenant_keys_agree_in_both_signed_ranges(string text, long user, long tenant) + { + var id = Guid.Parse(text); + await using var app = await OpenAsync(); + IdentityAdvisoryLockKey.ForUser(UserId.From(id)).Should().Be(user); + IdentityAdvisoryLockKey.ForTenant(TenantId.From(id)).Should().Be(tenant); + (await ScalarAsync(app, null, "SELECT public.fn_identity_contextual_lock_key('user',@id)", ("id", id))).Should().Be(user); + (await ScalarAsync(app, null, "SELECT public.fn_identity_contextual_lock_key('tenant',@id)", ("id", id))).Should().Be(tenant); + } + + [Fact] + public async Task Session_fence_demonstrates_observation_limit_and_transaction_fence_ends_on_rollback() + { + await using var app = await OpenAsync(); + var key = IdentityAdvisoryLockKey.ForUser(UserId.From(PersonB)); + await ExecuteAsync(app, null, "SELECT pg_advisory_lock(@key)", ("key", key)); + try + { + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + await LockAsync(app, transaction, SchemaFixture.TenantA, null, false); + await InsertMemberAsync(app, transaction, SchemaFixture.TenantA, null, Guid.CreateVersion7(), PersonB, + RoleId(SchemaFixture.TenantA, BuiltInRoleKey.Learner, PermissionScope.Tenant)); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await transaction.RollbackAsync(); + (await ScalarAsync(app, null, "SELECT public.fn_identity_lock_held('user',@id,true)", ("id", PersonB))).Should().BeTrue(); + } + finally { await ExecuteAsync(app, null, "SELECT pg_advisory_unlock(@key)", ("key", key)); } + await using (var transaction = await app.BeginTransactionAsync()) + { + await ExecuteAsync(app, transaction, "SELECT pg_advisory_xact_lock(@key)", ("key", key)); + await transaction.RollbackAsync(); + } + (await ScalarAsync(app, null, "SELECT public.fn_identity_lock_held('user',@id,true)", ("id", PersonB))).Should().BeFalse(); + } + + [Fact] + public async Task Unknown_target_refuses_before_FK_with_same_fixed_target_diagnostic() + { + await using var app = await OpenAsync(); + await using var transaction = await app.BeginTransactionAsync(); + var unknown = Guid.CreateVersion7(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + await LockAsync(app, transaction, SchemaFixture.TenantA, unknown, false); + var insert = () => InsertMemberAsync(app, transaction, SchemaFixture.TenantA, null, Guid.CreateVersion7(), unknown, + RoleId(SchemaFixture.TenantA, BuiltInRoleKey.Learner, PermissionScope.Tenant)); + var failure = (await insert.Should().ThrowAsync()).Which; + failure.SqlState.Should().Be("P0302"); + failure.MessageText.Should().Be("identity membership target is unavailable"); + failure.Detail.Should().BeNull(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Complete_second_admin_graph_requires_preheld_exclusive_tenant_mode(bool exclusive) + { + await using var app = await OpenAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + await LockAsync(app, transaction, SchemaFixture.TenantA, PersonB, exclusive); + var insert = () => InsertMemberAsync(app, transaction, SchemaFixture.TenantA, null, Guid.CreateVersion7(), PersonB, + RoleId(SchemaFixture.TenantA, BuiltInRoleKey.TenantAdmin, PermissionScope.Tenant)); + if (!exclusive) (await insert.Should().ThrowAsync()).Which.SqlState.Should().Be("P0301"); + else + { + await insert(); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + (await ScalarAsync(app, transaction, "SELECT count(*) FROM public.memberships")).Should().Be(3); + } + } + + [Fact] + public async Task Every_assignment_addition_including_empty_role_requires_User_but_profile_and_removal_do_not() + { + await using var app = await OpenAsync(); + await using (var transaction = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + await LockAsync(app, transaction, SchemaFixture.TenantA, null, false); + var add = () => ExecuteAsync(app, transaction, "INSERT INTO public.membership_role_assignments(tenant_id,membership_id,role_id) VALUES(@tenant,@member,@role)", + ("tenant", SchemaFixture.TenantA), ("member", LearnerMembershipA), ("role", RoleId(SchemaFixture.TenantA, BuiltInRoleKey.Instructor, PermissionScope.Tenant))); + (await add.Should().ThrowAsync()).Which.SqlState.Should().Be("P0301"); + } + await using (var transaction = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + await LockAsync(app, transaction, SchemaFixture.TenantA, null, false); + await ExecuteAsync(app, transaction, "UPDATE public.membership_profiles SET display_name='changed' WHERE membership_id=@member; DELETE FROM public.membership_role_assignments WHERE membership_id=@member", ("member", LearnerMembershipA)); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + (await ScalarAsync(app, transaction, "SELECT public.fn_identity_lock_held('user',@id,true)", ("id", PersonA))).Should().BeFalse(); + } + await using (var transaction = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + await LockAsync(app, transaction, SchemaFixture.TenantA, PersonA, false); + await ExecuteAsync(app, transaction, "INSERT INTO public.membership_role_assignments(tenant_id,membership_id,role_id) VALUES(@tenant,@member,@role)", + ("tenant", SchemaFixture.TenantA), ("member", LearnerMembershipA), ("role", RoleId(SchemaFixture.TenantA, BuiltInRoleKey.Instructor, PermissionScope.Tenant))); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + } + } + + [Theory] + [InlineData("suspend")] + [InlineData("revoke")] + [InlineData("assignment")] + [InlineData("kernel")] + public async Task Final_administrator_changes_are_refused_by_complete_graph_preflight(string change) + { + await using var app = await OpenAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + await LockAsync(app, transaction, SchemaFixture.TenantA, null, true); + var sql = change switch + { + "suspend" => "UPDATE public.memberships SET status='Suspended' WHERE id=@member", + "revoke" => "UPDATE public.memberships SET status='Revoked',deleted_at=clock_timestamp(),deleted_by=@actor WHERE id=@member", + "assignment" => "DELETE FROM public.membership_role_assignments WHERE membership_id=@member", + _ => "DELETE FROM public.role_permission_grants WHERE role_id=@role AND permission_key=@key", + }; + await ExecuteAsync(app, transaction, sql, ("member", AdminMembershipA), ("actor", UserId.SystemActor.Value), + ("role", RoleId(SchemaFixture.TenantA, BuiltInRoleKey.TenantAdmin, PermissionScope.Tenant)), ("key", IdentityFoundationManifest.RoleAdmin)); + var validate = () => ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + (await validate.Should().ThrowAsync()).Which.SqlState.Should().Be("P0303"); + } + + [Fact] + public async Task Revocation_is_terminal_and_rejoin_uses_a_new_identity_with_NULL_scope_uniqueness() + { + await using var app = await OpenAsync(); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + await LockAsync(app, transaction, SchemaFixture.TenantA, PersonA, false); + await ExecuteAsync(app, transaction, "UPDATE public.memberships SET status='Revoked',deleted_at=clock_timestamp(),deleted_by=@actor WHERE id=@id", ("actor", UserId.SystemActor.Value), ("id", LearnerMembershipA)); + await ExecuteAsync(app, transaction, "SAVEPOINT retired"); + var revive = () => ExecuteAsync(app, transaction, "UPDATE public.memberships SET status='Active',deleted_at=NULL,deleted_by=NULL WHERE id=@id", ("id", LearnerMembershipA)); + (await revive.Should().ThrowAsync()).Which.SqlState.Should().Be("P0304"); + await ExecuteAsync(app, transaction, "ROLLBACK TO SAVEPOINT retired"); + await InsertMemberAsync(app, transaction, SchemaFixture.TenantA, null, Guid.CreateVersion7(), PersonA, + RoleId(SchemaFixture.TenantA, BuiltInRoleKey.Learner, PermissionScope.Tenant)); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await ExecuteAsync(app, transaction, "SAVEPOINT joined"); + var duplicate = () => InsertMemberAsync(app, transaction, SchemaFixture.TenantA, null, Guid.CreateVersion7(), PersonA, + RoleId(SchemaFixture.TenantA, BuiltInRoleKey.Learner, PermissionScope.Tenant)); + (await duplicate.Should().ThrowAsync()).Which.SqlState.Should().Be("23505"); + await ExecuteAsync(app, transaction, "ROLLBACK TO SAVEPOINT joined"); + } + + [Fact] + public async Task NULL_parent_mirror_and_role_capability_are_checked_independently_of_RLS() + { + await using var app = await OpenAsync(); + 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, "SAVEPOINT clean"); + var mirror = () => ExecuteAsync(app, transaction, "INSERT INTO public.membership_role_assignments(tenant_id,membership_id,organization_id,role_id) VALUES(@tenant,@member,@organization,@role)", + ("tenant", SchemaFixture.TenantA), ("member", LearnerMembershipA), ("organization", SchemaFixture.OrgA1), ("role", RoleId(SchemaFixture.TenantA, BuiltInRoleKey.Learner, PermissionScope.Organization))); + var mirrorFailure = (await mirror.Should().ThrowAsync()).Which; + mirrorFailure.SqlState.Should().Be("23514"); + mirrorFailure.ConstraintName.Should().Be("membership_parent_scope"); + await ExecuteAsync(app, transaction, "ROLLBACK TO SAVEPOINT clean"); + var capability = () => ExecuteAsync(app, transaction, "INSERT INTO public.membership_role_assignments(tenant_id,membership_id,organization_id,role_id) VALUES(@tenant,@member,@organization,@role)", + ("tenant", SchemaFixture.TenantA), ("member", BranchMembershipA1), ("organization", SchemaFixture.OrgA1), ("role", RoleId(SchemaFixture.TenantA, BuiltInRoleKey.Instructor, PermissionScope.Tenant))); + (await capability.Should().ThrowAsync()).Which.SqlState.Should().Be("P0304"); + } + + [Fact] + public async Task Initial_Role_exception_admits_only_exact_fresh_graph_and_refuses_committed_repairs() + { + await using var app = await OpenAsync(); + var tenant = Guid.CreateVersion7(); + var role = Guid.CreateVersion7(); + await using (var bad = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, bad, tenant); + await LockAsync(app, bad, tenant, null, false); + await ExecuteAsync(app, bad, + "INSERT INTO public.roles(id,tenant_id,built_in_key,permission_scope,created_at,created_by) VALUES(@role,@tenant,'Instructor','Tenant',clock_timestamp(),@actor); INSERT INTO public.role_permission_grants(tenant_id,role_id,permission_scope,permission_key) VALUES(@tenant,@role,'Tenant',@key)", + ("role", role), ("tenant", tenant), ("actor", UserId.SystemActor.Value), ("key", IdentityFoundationManifest.ProfileWrite)); + var validate = () => ExecuteAsync(app, bad, "SET CONSTRAINTS ALL IMMEDIATE"); + (await validate.Should().ThrowAsync()).Which.SqlState.Should().Be("P0304"); + await bad.RollbackAsync(); + } + await using (var initial = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, initial, tenant); + await LockAsync(app, initial, tenant, null, false); + await ExecuteAsync(app, initial, + "INSERT INTO public.roles(id,tenant_id,built_in_key,permission_scope,created_at,created_by) VALUES(@role,@tenant,'Instructor','Tenant',clock_timestamp(),@actor)", + ("role", role), ("tenant", tenant), ("actor", UserId.SystemActor.Value)); + await ExecuteAsync(app, initial, "SET CONSTRAINTS ALL IMMEDIATE"); + await initial.CommitAsync(); + } + await using var repair = await app.BeginTransactionAsync(); + await ScopeAsync(app, repair, tenant); + await LockAsync(app, repair, tenant, null, false); + (await ScalarAsync(app, repair, "SELECT count(*) FROM public.memberships")).Should().Be(0); + var change = () => ExecuteAsync(app, repair, + "INSERT INTO public.role_permission_grants(tenant_id,role_id,permission_scope,permission_key) VALUES(@tenant,@role,'Tenant',@key)", + ("role", role), ("tenant", tenant), ("key", IdentityFoundationManifest.ProfileWrite)); + (await change.Should().ThrowAsync()).Which.SqlState.Should().Be("P0304"); + } + + [Fact] + public async Task Reactivation_requires_User_fence_and_revoked_history_remains_in_the_EF_model() + { + await using var app = await OpenAsync(); + await using (var withoutUser = await app.BeginTransactionAsync()) + { + await ScopeAsync(app, withoutUser, SchemaFixture.TenantA); + await LockAsync(app, withoutUser, SchemaFixture.TenantA, null, false); + await ExecuteAsync(app, withoutUser, "UPDATE public.memberships SET status='Suspended' WHERE id=@id", ("id", LearnerMembershipA)); + var activate = () => ExecuteAsync(app, withoutUser, "UPDATE public.memberships SET status='Active' WHERE id=@id", ("id", LearnerMembershipA)); + (await activate.Should().ThrowAsync()).Which.SqlState.Should().Be("P0301"); + await withoutUser.RollbackAsync(); + } + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + await LockAsync(app, transaction, SchemaFixture.TenantA, PersonA, false); + await ExecuteAsync(app, transaction, "UPDATE public.memberships SET status='Suspended' WHERE id=@id; UPDATE public.memberships SET status='Active' WHERE id=@id", ("id", LearnerMembershipA)); + await ExecuteAsync(app, transaction, "SET CONSTRAINTS ALL IMMEDIATE"); + await ExecuteAsync(app, transaction, "UPDATE public.memberships SET status='Revoked',deleted_at=clock_timestamp(),deleted_by=@actor WHERE id=@id", ("id", LearnerMembershipA), ("actor", UserId.SystemActor.Value)); + await using var db = new IdentityDbContext(new DbContextOptionsBuilder().UseNpgsql(app).Options, + new StaticTenantContextAccessor(new SeedTenantContext(TenantId.From(SchemaFixture.TenantA), null)), EmptyIdentityScope.Instance); + await db.Database.UseTransactionAsync(transaction); + (await db.Memberships.AnyAsync(member => member.Id == MembershipId.From(LearnerMembershipA) + && member.Status == MembershipStatus.Revoked)).Should().BeTrue("history reads retain the terminal row under the unchanged tenant/org filter"); + } + + private async Task OpenAsync() => (NpgsqlConnection)await PostgresFixture.OpenAsync(fixture.Postgres.AppConnectionString); +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityMutationLockTests.Controls.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMutationLockTests.Controls.cs new file mode 100644 index 000000000..7daa7e189 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMutationLockTests.Controls.cs @@ -0,0 +1,298 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Diagnostics.Metrics; +using FluentAssertions; +using LearnStack.Infrastructure.Persistence; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class IdentityMutationLockTests +{ + [Fact] + public async Task Actual_helper_waits_for_the_user_owner_and_a_separate_postwait_statement_observes_its_commit() + { + await using var source = ApplicationDataSource.Build(_schema.Postgres.AppConnectionString); + await using var owner = Unit(source); + await using var ownerFrame = await owner.BeginTransactionAsync(); + await owner.SetProvisioningTenantContextAsync(Tenant); + await new IdentityMutationLocks(owner).AcquireAsync(new([User], Tenant, IdentityTenantLockMode.Shared)); + var ownerXid = await ValueAsync(owner, "SELECT pg_current_xact_id()::text"); + await using var waiter = Unit(source); + await using var waiterFrame = await waiter.BeginTransactionAsync(); + await waiter.SetProvisioningTenantContextAsync(Tenant); + (await ValueAsync(waiter, "SELECT pg_visible_in_snapshot(@xid::xid8, pg_current_snapshot())", ownerXid)) + .Should().BeFalse("the competing transaction is actually in progress in the pre-wait snapshot"); + var plan = new IdentityMutationLockPlan([User], Tenant, IdentityTenantLockMode.Shared); + var helper = new IdentityMutationLocks(waiter); + var waiting = helper.AcquireAsync(plan); + await using var observer = (NpgsqlConnection)await PostgresFixture.OpenAsync(_schema.Postgres.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(observer); + await ObserveWaitAsync(observer, ((NpgsqlConnection)waiter.Connection).ProcessID, IdentityAdvisoryLockKey.ForUser(User)); + waiting.IsCompleted.Should().BeFalse(); + (await ModeCountAsync(observer, ((NpgsqlConnection)waiter.Connection).ProcessID, + IdentityAdvisoryLockKey.ForTenant(Tenant), true)).Should().Be(0, + "the tenant family cannot be acquired beneath a pending User acquisition"); + await ownerFrame.CompleteAsync(); + await waiting; + helper.RequireCurrent(plan); + (await ValueAsync(waiter, "SELECT pg_visible_in_snapshot(@xid::xid8, pg_current_snapshot())", ownerXid)) + .Should().BeTrue("a separate READ COMMITTED statement observes the actual competing COMMIT"); + (await HeldAsync(waiter, IdentityAdvisoryLockKey.ForUser(User))).Should().Equal("ExclusiveLock"); + await waiterFrame.FailAsync(); + (await HeldAsync(waiter, IdentityAdvisoryLockKey.ForUser(User))).Should().BeEmpty(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Waiting_helper_timeout_or_cancellation_rolls_back_releases_and_reuses_the_physical_pool_connection(bool cancel) + { + await using var holderSource = ApplicationDataSource.Build(_schema.Postgres.AppConnectionString); + await using var holder = Unit(holderSource); + await using var holderFrame = await holder.BeginTransactionAsync(); + await holder.SetProvisioningTenantContextAsync(Tenant); + await new IdentityMutationLocks(holder).AcquireAsync(new([User], Tenant, IdentityTenantLockMode.Shared)); + var connectionString = new NpgsqlConnectionStringBuilder(_schema.Postgres.AppConnectionString) + { MaxPoolSize = 1, MinPoolSize = 0, Pooling = true }.ConnectionString; + await using var waiterSource = ApplicationDataSource.Build(connectionString); + int processId; + using var signals = new LockSignals(); + using var cancellation = new CancellationTokenSource(); + await using (var waiter = Unit(waiterSource)) + { + await using var frame = await waiter.BeginTransactionAsync(); + await waiter.SetProvisioningTenantContextAsync(Tenant); + processId = ((NpgsqlConnection)waiter.Connection).ProcessID; + var helper = new IdentityMutationLocks(waiter); + var plan = new IdentityMutationLockPlan([User], Tenant, IdentityTenantLockMode.Shared); + var started = Stopwatch.StartNew(); + var waiting = helper.AcquireAsync(plan, cancellation.Token); + await using var observer = (NpgsqlConnection)await PostgresFixture.OpenAsync(_schema.Postgres.AppConnectionString); + await ObserveWaitAsync(observer, processId, IdentityAdvisoryLockKey.ForUser(User)); + waiting.IsCompleted.Should().BeFalse(); + if (cancel) + { + cancellation.Cancel(); + await FluentActions.Awaiting(() => waiting).Should().ThrowAsync(); + } + else + { + await FluentActions.Awaiting(() => waiting).Should().ThrowAsync(); + started.Elapsed.Should().BeGreaterThan(TimeSpan.FromSeconds(1.5)); + } + started.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(8)); + waiter.IsRollbackOnly.Should().BeTrue(); + await frame.FailAsync(); + waiter.HasActiveTransaction.Should().BeFalse(); + (await HeldAsync(waiter, IdentityAdvisoryLockKey.ForUser(User))).Should().BeEmpty(); + (await HeldAsync(waiter, IdentityAdvisoryLockKey.ForTenant(Tenant))).Should().BeEmpty(); + signals.AssertOneFailure("user", cancel ? "cancelled" : "timeout"); + } + await holderFrame.CompleteAsync(); + await using var reused = Unit(waiterSource); + await using var reusedFrame = await reused.BeginTransactionAsync(); + ((NpgsqlConnection)reused.Connection).ProcessID.Should().Be(processId, + "the one-connection pool must reuse the actual cleaned backend rather than prove a fresh socket is clean"); + (await ValueAsync(reused, """ + 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.identity_authority_id',true),'') IS NULL + """)).Should().BeTrue(); + (await HeldAsync(reused, IdentityAdvisoryLockKey.ForUser(User))).Should().BeEmpty(); + await reused.SetProvisioningTenantContextAsync(Tenant); + var fresh = new IdentityMutationLocks(reused); + var freshPlan = new IdentityMutationLockPlan([User], Tenant, IdentityTenantLockMode.Shared); + await fresh.AcquireAsync(freshPlan); + fresh.RequireCurrent(freshPlan); + await reusedFrame.CompleteAsync(); + (await HeldAsync(reused, IdentityAdvisoryLockKey.ForUser(User))).Should().BeEmpty(); + } + + [Fact] + public async Task Separate_shared_helpers_coexist_exclusive_waits_and_repeat_upgrade_refusals_emit_one_fixed_fault() + { + await using var source = ApplicationDataSource.Build(_schema.Postgres.AppConnectionString); + await using var first = Unit(source); + await using var firstFrame = await first.BeginTransactionAsync(); + await first.SetProvisioningTenantContextAsync(Tenant); + var firstHelper = new IdentityMutationLocks(first); + var firstPlan = new IdentityMutationLockPlan([], Tenant, IdentityTenantLockMode.Shared); + await firstHelper.AcquireAsync(firstPlan); + await using var second = Unit(source); + await using var secondFrame = await second.BeginTransactionAsync(); + await second.SetProvisioningTenantContextAsync(Tenant); + var secondHelper = new IdentityMutationLocks(second); + await secondHelper.AcquireAsync(new([], Tenant, IdentityTenantLockMode.Shared)); + ((NpgsqlConnection)first.Connection).ProcessID.Should().NotBe(((NpgsqlConnection)second.Connection).ProcessID); + (await HeldAsync(first, IdentityAdvisoryLockKey.ForTenant(Tenant))).Should().Equal("ShareLock"); + (await HeldAsync(second, IdentityAdvisoryLockKey.ForTenant(Tenant))).Should().Equal("ShareLock"); + await using var exclusive = Unit(source); + await using var exclusiveFrame = await exclusive.BeginTransactionAsync(); + await exclusive.SetProvisioningTenantContextAsync(Tenant); + var exclusiveHelper = new IdentityMutationLocks(exclusive); + var exclusivePlan = new IdentityMutationLockPlan([], Tenant, IdentityTenantLockMode.Exclusive); + using var signals = new LockSignals(); + var waiting = exclusiveHelper.AcquireAsync(exclusivePlan); + await using var observer = (NpgsqlConnection)await PostgresFixture.OpenAsync(_schema.Postgres.AppConnectionString); + await ObserveWaitAsync(observer, ((NpgsqlConnection)exclusive.Connection).ProcessID, IdentityAdvisoryLockKey.ForTenant(Tenant)); + for (var attempt = 0; attempt < 2; attempt++) + await FluentActions.Awaiting(() => firstHelper.AcquireAsync(new([], Tenant, IdentityTenantLockMode.Exclusive))) + .Should().ThrowAsync(); + signals.AssertOnePlanFault("tenant"); + (await HeldAsync(first, IdentityAdvisoryLockKey.ForTenant(Tenant))).Should().Equal("ShareLock"); + await firstFrame.FailAsync(); + await ObserveWaitAsync(observer, ((NpgsqlConnection)exclusive.Connection).ProcessID, IdentityAdvisoryLockKey.ForTenant(Tenant)); + waiting.IsCompleted.Should().BeFalse("the independently held second shared fence still excludes an exclusive owner"); + await secondFrame.CompleteAsync(); + await waiting; + exclusiveHelper.RequireCurrent(exclusivePlan); + (await HeldAsync(exclusive, IdentityAdvisoryLockKey.ForTenant(Tenant))).Should().Equal("ExclusiveLock"); + signals.AssertAcquired("tenant"); + await exclusiveFrame.CompleteAsync(); + (await HeldAsync(exclusive, IdentityAdvisoryLockKey.ForTenant(Tenant))).Should().BeEmpty(); + } + + [Fact] + public async Task Actual_global_subject_acquisition_emits_a_positive_finite_measurement_and_releases_on_rollback() + { + var subject = new GlobalIdentitySubject(IdentityAuthorityId.From(Guid.Parse("01930000-0000-7000-8000-00000000f001")), + "https://lock-metrics.invalid/realms/learnstack", "subject-canary-must-not-be-a-metric-tag"); + await using var source = ApplicationDataSource.Build(_schema.Postgres.AppConnectionString); + await using var unit = Unit(source); + var descriptor = SubjectSignalMint.Create(subject); + await using var frame = await unit.BeginGlobalIdentityTransactionAsync(descriptor, + LearnStack.SharedKernel.Persistence.TransactionMode.ReadWrite); + using var signals = new LockSignals(); + await unit.AcquireGlobalIdentitySubjectLockAsync(descriptor); + (await HeldAsync(unit, IdentityAdvisoryLockKey.ForSubject(subject))).Should().Equal("ExclusiveLock"); + signals.AssertAcquired("subject"); + signals.Snapshot().SelectMany(signal => signal.Tags.Values).Should().NotContain(subject.Subject); + await frame.FailAsync(); + (await HeldAsync(unit, IdentityAdvisoryLockKey.ForSubject(subject))).Should().BeEmpty(); + } + + private static async Task ValueAsync(NpgsqlUnitOfWork unit, string sql, string? xid = null) + { + await using var command = new NpgsqlCommand(sql, (NpgsqlConnection)unit.Connection, + (NpgsqlTransaction?)unit.Transaction) + { CommandTimeout = 10 }; + if (xid is not null) command.Parameters.AddWithValue("xid", xid); + return (T)(await command.ExecuteScalarAsync())!; + } + + private static async Task ObserveWaitAsync(NpgsqlConnection observer, int processId, long key) + { + var deadline = Stopwatch.StartNew(); + while (deadline.Elapsed < TimeSpan.FromSeconds(1.5)) + { + if (await ModeCountAsync(observer, processId, key, false) == 1) return; + await Task.Delay(10); + } + throw new InvalidOperationException("The competing helper never entered the exact PostgreSQL advisory wait."); + } + + private static async Task ModeCountAsync(NpgsqlConnection observer, int processId, long key, bool granted) + { + await using var command = new NpgsqlCommand(""" + SELECT count(*) FROM pg_catalog.pg_locks l JOIN pg_catalog.pg_stat_activity a ON a.pid=l.pid + WHERE l.pid=@pid AND l.database=(SELECT oid FROM pg_catalog.pg_database WHERE datname=current_database()) + AND l.locktype='advisory' AND l.objsubid=1 AND l.granted=@granted + AND (l.classid::bigint << 32 | l.objid::bigint)=@key + AND (@granted OR (a.wait_event_type='Lock' AND a.wait_event='advisory')) + """, observer) { CommandTimeout = 5 }; + command.Parameters.AddWithValue("pid", processId); + command.Parameters.AddWithValue("key", key); + command.Parameters.AddWithValue("granted", granted); + return (long)(await command.ExecuteScalarAsync())!; + } + + private sealed record LockSignal(string Instrument, double Value, IReadOnlyDictionary Tags); + + private sealed class LockSignals : IDisposable + { + private static readonly AsyncLocal Current = new(); + private readonly LockSignals? _previous = Current.Value; + private static readonly string[] WaitTagNames = ["lock_kind", "outcome"]; + private static readonly string[] RefusalTagNames = ["lock_kind", "reason"]; + private readonly ConcurrentQueue _signals = new(); + private readonly MeterListener _listener = new(); + internal LockSignals() + { + Current.Value = this; + _listener.InstrumentPublished = (instrument, listener) => + { + if (instrument.Meter.Name == IdentityLockObservation.MeterName) + listener.EnableMeasurementEvents(instrument); + }; + _listener.SetMeasurementEventCallback((instrument, value, tags, _) => + Record(instrument, value, tags)); + _listener.SetMeasurementEventCallback((instrument, value, tags, _) => + Record(instrument, value, tags)); + _listener.Start(); + } + + internal LockSignal[] Snapshot() => _signals.ToArray(); + internal void AssertOneFailure(string kind, string outcome) + { + AssertFinite(); + var matching = Snapshot().Where(signal => signal.Tags["lock_kind"] == kind).ToArray(); + matching.Where(signal => signal.Instrument == "learnstack_identity_lock_wait_seconds") + .Should().ContainSingle().Which.Tags["outcome"].Should().Be(outcome); + matching.Where(signal => signal.Instrument == "learnstack_identity_lock_refusals_total") + .Should().ContainSingle().Which.Value.Should().Be(1); + matching.Single(signal => signal.Instrument == "learnstack_identity_lock_refusals_total") + .Tags["reason"].Should().Be(outcome); + } + internal void AssertOnePlanFault(string kind) + { + AssertFinite(); + Snapshot().Where(signal => signal.Instrument == "learnstack_identity_lock_refusals_total" + && signal.Tags["lock_kind"] == kind).Should().ContainSingle() + .Which.Tags["reason"].Should().Be("fault"); + } + internal void AssertAcquired(string kind) + { + AssertFinite(); + Snapshot().Where(signal => signal.Instrument == "learnstack_identity_lock_wait_seconds" + && signal.Tags["lock_kind"] == kind && signal.Tags["outcome"] == "acquired") + .Should().ContainSingle().Which.Value.Should().BeGreaterThanOrEqualTo(0); + } + private void AssertFinite() + { + Snapshot().Should().NotBeEmpty("the sink must have received actual positive or failed production measurements"); + foreach (var signal in Snapshot()) + { + signal.Instrument.Should().BeOneOf("learnstack_identity_lock_wait_seconds", "learnstack_identity_lock_refusals_total"); + signal.Tags.Keys.Should().BeEquivalentTo(signal.Instrument == "learnstack_identity_lock_wait_seconds" + ? WaitTagNames : RefusalTagNames); + signal.Tags["lock_kind"].Should().BeOneOf("subject", "user", "tenant"); + if (signal.Instrument == "learnstack_identity_lock_wait_seconds") + signal.Tags["outcome"].Should().BeOneOf("acquired", "timeout", "cancelled", "fault"); + else signal.Tags["reason"].Should().BeOneOf("timeout", "cancelled", "fault"); + } + } + private void Record(Instrument instrument, double value, ReadOnlySpan> tags) + { + if (ReferenceEquals(Current.Value, this)) + _signals.Enqueue(new(instrument.Name, value, tags.ToArray().ToDictionary(tag => tag.Key, + tag => tag.Value?.ToString() ?? string.Empty, StringComparer.Ordinal))); + } + public void Dispose() + { + _listener.Dispose(); + Current.Value = _previous; + } + } + + private sealed class SubjectSignalEntity; + private sealed class SubjectSignalContext; + private sealed class SubjectSignalMint : GlobalIdentityOwnerDescriptor.MintingSource + { + internal static GlobalIdentityOwnerDescriptor Create(GlobalIdentitySubject subject) => + ForBootstrap(subject, typeof(SubjectSignalContext), typeof(SubjectSignalEntity)); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityMutationLockTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMutationLockTests.cs new file mode 100644 index 000000000..e37a9fcaa --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityMutationLockTests.cs @@ -0,0 +1,133 @@ +using FluentAssertions; +using LearnStack.Infrastructure.Persistence; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Persistence; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed partial class IdentityMutationLockTests(SchemaFixture schema) +{ + private readonly SchemaFixture _schema = schema; + private static readonly UserId User = UserId.From(Guid.Parse("01930000-0000-7000-8000-00000000a001")); + private static readonly TenantId Tenant = TenantId.From(SchemaFixture.TenantA); + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Complete_plan_holds_actual_exclusive_user_then_required_tenant_mode_and_releases_at_transaction_end(bool rollback) + { + await using var source = ApplicationDataSource.Build(_schema.Postgres.AppConnectionString); + await using var unit = Unit(source); + await using var frame = await unit.BeginTransactionAsync(); + await unit.SetProvisioningTenantContextAsync(Tenant); + var locks = new IdentityMutationLocks(unit); + var plan = new IdentityMutationLockPlan([User], Tenant, IdentityTenantLockMode.Shared); + await locks.AcquireAsync(plan); + locks.RequireCurrent(plan); + (await HeldAsync(unit, IdentityAdvisoryLockKey.ForUser(User))).Should().Equal("ExclusiveLock"); + (await HeldAsync(unit, IdentityAdvisoryLockKey.ForTenant(Tenant))).Should().Equal("ShareLock"); + await SqlAsync(unit, "SAVEPOINT after_admission"); + await SqlAsync(unit, "ROLLBACK TO SAVEPOINT after_admission"); + locks.RequireCurrent(plan); + (await HeldAsync(unit, IdentityAdvisoryLockKey.ForUser(User))).Should().Equal("ExclusiveLock"); + if (rollback) await frame.FailAsync(); else await frame.CompleteAsync(); + // These queries use the same physical backend outside its completed transaction. + (await HeldAsync(unit, IdentityAdvisoryLockKey.ForUser(User))).Should().BeEmpty(); + (await HeldAsync(unit, IdentityAdvisoryLockKey.ForTenant(Tenant))).Should().BeEmpty(); + var stale = () => locks.RequireCurrent(plan); + stale.Should().Throw(); + } + + [Fact] + public async Task Profile_or_removal_plan_has_no_user_hold_and_cannot_upgrade_or_reuse_a_generation() + { + await using var source = ApplicationDataSource.Build(_schema.Postgres.AppConnectionString); + await using var unit = Unit(source); + var first = await unit.BeginTransactionAsync(); + await unit.SetProvisioningTenantContextAsync(Tenant); + var locks = new IdentityMutationLocks(unit); + var plan = new IdentityMutationLockPlan([], Tenant, IdentityTenantLockMode.Shared); + await locks.AcquireAsync(plan); + (await HeldAsync(unit, IdentityAdvisoryLockKey.ForUser(User))).Should().BeEmpty(); + (await HeldAsync(unit, IdentityAdvisoryLockKey.ForTenant(Tenant))).Should().Equal("ShareLock"); + await first.CompleteAsync(); + await using var second = await unit.BeginTransactionAsync(); + await unit.SetProvisioningTenantContextAsync(Tenant); + var stale = () => locks.RequireCurrent(plan); + stale.Should().Throw(); + unit.IsRollbackOnly.Should().BeTrue(); + } + + [Theory] + [InlineData("unannounced")] + [InlineData("foreign")] + [InlineData("repeatable")] + [InlineData("read-only")] + public async Task Missing_or_incompatible_owner_refuses_before_any_advisory_hold(string defect) + { + await using var source = ApplicationDataSource.Build(_schema.Postgres.AppConnectionString); + await using var unit = Unit(source); + await using var frame = await unit.BeginTransactionAsync(defect == "read-only" + ? TransactionMode.ReadOnly : TransactionMode.ReadWrite); + if (defect == "repeatable") await SqlAsync(unit, "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"); + if (defect != "unannounced") + await unit.SetProvisioningTenantContextAsync(defect == "foreign" ? TenantId.From(SchemaFixture.TenantB) : Tenant); + var locks = new IdentityMutationLocks(unit); + await FluentActions.Awaiting(() => locks.AcquireAsync(new([User], Tenant, IdentityTenantLockMode.Exclusive))) + .Should().ThrowAsync(); + unit.IsRollbackOnly.Should().BeTrue(); + (await HeldAsync(unit, IdentityAdvisoryLockKey.ForUser(User))).Should().BeEmpty(); + (await HeldAsync(unit, IdentityAdvisoryLockKey.ForTenant(Tenant))).Should().BeEmpty(); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task An_acquired_shared_plan_never_upgrades_or_adds_a_late_user(bool addUser) + { + await using var source = ApplicationDataSource.Build(_schema.Postgres.AppConnectionString); + await using var unit = Unit(source); + await using var frame = await unit.BeginTransactionAsync(); + await unit.SetProvisioningTenantContextAsync(Tenant); + var locks = new IdentityMutationLocks(unit); + await locks.AcquireAsync(new([], Tenant, IdentityTenantLockMode.Shared)); + await FluentActions.Awaiting(() => locks.AcquireAsync(new(addUser ? [User] : [], Tenant, + addUser ? IdentityTenantLockMode.Shared : IdentityTenantLockMode.Exclusive))) + .Should().ThrowAsync(); + (await HeldAsync(unit, IdentityAdvisoryLockKey.ForTenant(Tenant))).Should().Equal("ShareLock"); + (await HeldAsync(unit, IdentityAdvisoryLockKey.ForUser(User))).Should().BeEmpty(); + } + + private static NpgsqlUnitOfWork Unit(NpgsqlDataSource source) => new(source, NullLogger.Instance); + + private static async Task SqlAsync(NpgsqlUnitOfWork unit, string sql) + { + await using var command = new NpgsqlCommand(sql, (NpgsqlConnection)unit.Connection, + (NpgsqlTransaction?)unit.Transaction) + { CommandTimeout = 10 }; + await command.ExecuteNonQueryAsync(); + } + + private static async Task HeldAsync(NpgsqlUnitOfWork unit, long key) + { + await using var command = new NpgsqlCommand(""" + SELECT mode FROM pg_catalog.pg_locks + WHERE pid = pg_catalog.pg_backend_pid() + AND database = (SELECT oid FROM pg_catalog.pg_database WHERE datname = pg_catalog.current_database()) + AND locktype = 'advisory' AND granted AND objsubid = 1 + AND (classid::bigint << 32 | objid::bigint) = @key + ORDER BY mode + """, (NpgsqlConnection)unit.Connection, (NpgsqlTransaction?)unit.Transaction) { CommandTimeout = 10 }; + command.Parameters.AddWithValue("key", key); + var modes = new List(); + await using var reader = await command.ExecuteReaderAsync(); + while (await reader.ReadAsync()) modes.Add(reader.GetString(0)); + return [.. modes]; + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityPublicReadFixture.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityPublicReadFixture.cs new file mode 100644 index 000000000..4e93934ce --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityPublicReadFixture.cs @@ -0,0 +1,97 @@ +using FluentAssertions; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Application.Contracts.Bindings; +using LearnStack.Modules.Identity.Application.Contracts.Seeding; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.Tools.Seeder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; + +namespace LearnStack.Tests.Integration.Database; + +/// A single immutable issuer anchor and real app-role bindings, isolated from anonymous fixtures. +internal sealed class IdentityPublicReadFixture : PublicReadFixture +{ + private IdentityPublicReadFixture(DisposableSchemaDatabase database, IdentityAuthorityRegistration registration) + : base(database) => Registration = registration; + + internal IdentityAuthorityRegistration Registration { get; } + protected override bool RetainIdentityQualification => true; + + internal static async Task CreateAsync(PublicReadFixture parent, string issuer, + IReadOnlyDictionary? subjects = null) + { + var registration = new IdentityAuthorityRegistration(IdentityAuthorityId.From(Guid.CreateVersion7()), issuer); + var database = await DisposableSchemaDatabase.CreateAsync(parent.Postgres); + var fixture = new IdentityPublicReadFixture(database, registration); + try + { + await fixture.InitializeAsync(); + await using (var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString)) + await IdentityAuthorityDeploymentInstaller.InstallAsync(owner, fixture.Registration); + if (subjects is not null) + foreach (var (actor, subject) in subjects) await fixture.AdoptAsync(actor, subject); + return fixture; + } + catch + { + await fixture.DisposeAsync(); + throw; + } + } + + internal async Task SeedFoundationAsync(SeedProviderWitness witness) + { + await using var source = ApplicationDataSource.Build(AppConnectionString); + var admission = new FixedSeedIdentityFoundationAdmission(witness); + var runner = new SeedIdentityFoundationRunner(context => SeedComposition.Build(source, context, + NullLoggerFactory.Instance, identityAuthority: Registration, seedAdmission: admission), admission); + await runner.RunAsync(); + foreach (var (actor, subject) in witness.Subjects) + { + await using var provider = SeedComposition.Build(source, null, NullLoggerFactory.Instance, + identityAuthority: Registration); + await provider.GetRequiredService().QualifyAsync(); + await using var scope = provider.CreateAsyncScope(); + var found = await scope.ServiceProvider.GetRequiredService().ResolveExistingAsync(subject); + found.Outcome.Should().Be(IdentityBindingOutcome.Existing); + found.Actor.Should().Be(actor); + } + } + + // Fixture-created synthetic/claimless subjects still use the production writer, + // an exact single-act admission and a separate app-role owner outside HTTP admission. + internal async Task AdoptAsync(UserId actor, string opaqueSubject) + { + var subject = new GlobalIdentitySubject(Registration.AuthorityId, Registration.Issuer, opaqueSubject); + await using var source = ApplicationDataSource.Build(AppConnectionString); + await using var provider = SeedComposition.Build(source, null, NullLoggerFactory.Instance, + identityAuthority: Registration, seedAdmission: new ExactBindingAdmission(subject, actor)); + await provider.GetRequiredService().QualifyAsync(); + await using var scope = provider.CreateAsyncScope(); + var result = await scope.ServiceProvider.GetRequiredService().AdoptAsync(subject, actor); + result.IsBound.Should().BeTrue(); + result.Actor.Should().Be(actor); + } + + protected override void ConfigureTestHost(IWebHostBuilder builder) + { + base.ConfigureTestHost(builder); + builder.UseSetting("Identity:AuthorityId", Registration.AuthorityId.Value.ToString("D")); + builder.UseSetting("Authentication:Tenant:Issuer", Registration.Issuer); + } + + private sealed class ExactBindingAdmission(GlobalIdentitySubject subject, UserId actor) : ISeedIdentityFoundationAdmission + { + public ValueTask AllowsAsync(GlobalIdentitySubject candidate, UserId declaredActor, + CancellationToken cancellationToken = default) => ValueTask.FromResult(declaredActor == actor + && candidate.AuthorityId == subject.AuthorityId + && candidate.SubjectKey.Equals(subject.SubjectKey) + && string.Equals(candidate.Issuer, subject.Issuer, StringComparison.Ordinal) + && string.Equals(candidate.Subject, subject.Subject, StringComparison.Ordinal)); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityReadDiagnosticSinkTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityReadDiagnosticSinkTests.cs new file mode 100644 index 000000000..f47cf6879 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityReadDiagnosticSinkTests.cs @@ -0,0 +1,220 @@ +using System.Data.Common; +using System.Diagnostics; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Permissions; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.Tools.Seeder; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; +using Xunit; +using IdentityRoleId = LearnStack.Modules.Identity.Domain.RoleId; +using static LearnStack.Tests.Integration.Database.IdentityMembershipFixture; + +namespace LearnStack.Tests.Integration.Database; + +/// Current contextual read ports preserve G19 without a public Identity route. +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(IdentityDiagnosticSinkGroup.Name)] +public sealed class IdentityReadDiagnosticSinkTests(IdentityMembershipFixture fixture) +{ + private const string Neutral = "identity-read-neutral-827be"; + private const string Nested = "identity-read-nested-912ac"; + private const string Sensitive = "identity-read-sensitive-613fd"; + private static readonly string Payload = JsonSerializer.Serialize(new + { + value = Neutral, + items = new[] { new { value = Nested, token = Sensitive } }, + }); + private static readonly string[] Canaries = [Neutral, Nested, Sensitive]; + + [Theory] + [InlineData("role-find", false)] + [InlineData("role-history", true)] + [InlineData("membership-find", false)] + [InlineData("membership-find", true)] + [InlineData("membership-history", false)] + [InlineData("role-read", true)] + [InlineData("seed-role", false)] + [InlineData("seed-membership", true)] + public async Task Actual_contextual_read_ports_drop_provider_payloads_before_the_existing_diagnostic_sinks( + string port, bool transient) + { + // 55000 exercises the non-retrying EF wrapper without 53300's separate + // connector-break/secondary-cleanup behavior. + var sqlState = transient ? PostgresErrorCodes.ObjectNotInPrerequisiteState : "P0399"; + var table = port is "role-find" or "role-read" or "seed-role" ? "roles" : "memberships"; + await using var database = await DisposableSchemaDatabase.CreateAsync(fixture.Postgres); + await SeedSchemaAsync(database.MigrationConnectionString, database.AppConnectionString); + await StoreCanaryAsync(database.AppConnectionString); + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString); + var originalPolicies = await PolicyCensusAsync(owner); + using var sinks = new IdentityDiagnosticSinks(); + using var callers = new ActivitySource("learnstack.identity.storage-qualification"); + using var caller = callers.StartActivity("contextual-read-port"); + caller.Should().NotBeNull(); + await using var source = ApplicationDataSource.Build(database.AppConnectionString, sinks.Loggers); + await AssertReadSucceedsAsync(source, sinks.Loggers, port); + await ExecuteAsync(owner, null, $$""" + CREATE FUNCTION public.identity_contextual_read_sink_fault() RETURNS boolean + LANGUAGE plpgsql SECURITY INVOKER SET search_path=pg_catalog AS $$ + DECLARE payload text; + BEGIN + SELECT display_name INTO STRICT payload FROM public.membership_profiles + WHERE membership_id='{{LearnerMembershipA:D}}'::uuid; + RAISE EXCEPTION USING ERRCODE='{{sqlState}}', MESSAGE=payload; + END $$; + REVOKE ALL ON FUNCTION public.identity_contextual_read_sink_fault() FROM PUBLIC; + GRANT EXECUTE ON FUNCTION public.identity_contextual_read_sink_fault() TO learnstack_app; + CREATE POLICY identity_contextual_read_sink_fault ON public.{{table}} + AS RESTRICTIVE FOR SELECT TO learnstack_app + USING(public.identity_contextual_read_sink_fault()); + """); + Exception? failure = null; + try + { + (await PolicyCensusAsync(owner)).Should().NotBe(originalPolicies); + var witness = new ProviderFailureWitness(); + await using var unit = new NpgsqlUnitOfWork(source, sinks.Loggers.CreateLogger()); + await using var frame = await unit.BeginTransactionAsync(); + await unit.SetProvisioningTenantContextAsync(TenantId.From(SchemaFixture.TenantA)); + await SchemaQueries.AssertApplicationRoleAsync((NpgsqlConnection)unit.Connection); + await using var db = CreateContext(unit, sinks.Loggers, witness); + await db.Database.UseTransactionAsync(unit.Transaction); + failure = await Record.ExceptionAsync(() => ReadPortAsync(db, new ContextualIdentityStorageControl(db, unit), port)); + witness.Failure.Should().BeOfType(); + var providerFailure = (PostgresException)witness.Failure!; + providerFailure.SqlState.Should().Be(sqlState); + providerFailure.MessageText.Should().Be(Payload, + "the app-role policy must read the stored neutral, nested and sensitive values before failing"); + witness.Commands.Should().Be(1); + await frame.FailAsync(); + failure.Should().BeOfType(); + failure!.InnerException.Should().BeNull(); + } + finally + { + await ExecuteAsync(owner, null, $""" + DROP POLICY identity_contextual_read_sink_fault ON public.{table}; + DROP FUNCTION public.identity_contextual_read_sink_fault(); + """); + } + (await PolicyCensusAsync(owner)).Should().Be(originalPolicies); + await AssertReadSucceedsAsync(source, sinks.Loggers, port); + Activity.Current.Should().BeSameAs(caller); + caller!.Stop(); + caller.Status.Should().Be(ActivityStatusCode.Unset); + sinks.AssertCompleteEfTraceCoverage(); + IdentityDiagnosticSinks.AssertEfCallerAncestry(sinks.Traces, caller); + sinks.Traces.Where(trace => trace.Source == IdentityDiagnosticSinks.EfSource + && trace.Status == ActivityStatusCode.Error).Should().NotBeEmpty() + .And.OnlyContain(trace => trace.Description == "Identity storage command failed."); + // Reuse the established real sink vehicle; this is not an added HTTP route. + await sinks.CaptureThroughL1Async(failure!); + var captured = await sinks.ReadAsync(); + captured.AssertPositiveControls(); + captured.Log.Should().Contain("IdentityStorageReadFailed").And.NotContain("QueryIterationFailed"); + captured.AssertExcludes(Canaries); + } + + [Fact] + public async Task Current_read_ports_preserve_cancellation_and_programming_failures() + { + await using var source = ApplicationDataSource.Build(fixture.Postgres.AppConnectionString); + await using var unit = new NpgsqlUnitOfWork(source, NullLogger.Instance); + await using var frame = await unit.BeginTransactionAsync(); + await unit.SetProvisioningTenantContextAsync(TenantId.From(SchemaFixture.TenantA)); + var witness = new ProviderFailureWitness(); + await using var db = CreateContext(unit, NullLoggerFactory.Instance, witness); + await db.Database.UseTransactionAsync(unit.Transaction); + var control = new ContextualIdentityStorageControl(db, unit); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + var cancelled = await Assert.ThrowsAnyAsync(() => + ReadPortAsync(db, control, "role-read", cancellation.Token)); + cancelled.CancellationToken.Should().Be(cancellation.Token); + witness.Commands.Should().Be(0); + await db.DisposeAsync(); + await Assert.ThrowsAsync(() => ReadPortAsync(db, control, "role-read")); + witness.Commands.Should().Be(0); + } + + private static IdentityDbContext CreateContext(NpgsqlUnitOfWork unit, ILoggerFactory loggers, + params IInterceptor[] interceptors) => new(new DbContextOptionsBuilder() + .UseNpgsql(unit.Connection).UseLoggerFactory(loggers).AddInterceptors(interceptors).Options, + new StaticTenantContextAccessor(new SeedTenantContext(TenantId.From(SchemaFixture.TenantA), null)), + EmptyIdentityScope.Instance); + + private static async Task ReadPortAsync(IdentityDbContext db, ContextualIdentityStorageControl control, + string port, CancellationToken cancellationToken = default) + { + var role = IdentityRoleId.From(RoleId(SchemaFixture.TenantA, BuiltInRoleKey.Learner, PermissionScope.Tenant)); + var member = MembershipId.From(LearnerMembershipA); + return port switch + { + "role-find" => await new RoleWriteStore(db, control).FindAsync(role, cancellationToken), + "role-history" => await new RoleWriteStore(db, control).HasMembershipHistoryAsync(cancellationToken), + "membership-find" => await new MembershipWriteStore(db, control).FindAsync(member, cancellationToken), + "membership-history" => await new MembershipWriteStore(db, control).HasMembershipHistoryAsync(cancellationToken), + "role-read" => await new RoleReadStore(db).ReadAsync(role, cancellationToken), + "seed-role" => await new SeedStateReader(db).ReadRoleAsync(role, cancellationToken), + "seed-membership" => await new SeedStateReader(db).ReadMembershipAsync(member, cancellationToken), + _ => throw new ArgumentOutOfRangeException(nameof(port)), + }; + } + + private static async Task AssertReadSucceedsAsync(NpgsqlDataSource source, ILoggerFactory loggers, string port) + { + await using var unit = new NpgsqlUnitOfWork(source, loggers.CreateLogger()); + await using var frame = await unit.BeginTransactionAsync(); + await unit.SetProvisioningTenantContextAsync(TenantId.From(SchemaFixture.TenantA)); + await using var db = CreateContext(unit, loggers); + await db.Database.UseTransactionAsync(unit.Transaction); + var value = await ReadPortAsync(db, new ContextualIdentityStorageControl(db, unit), port); + if (port.EndsWith("history", StringComparison.Ordinal)) value.Should().Be(true); + else value.Should().NotBeNull(); + await frame.CompleteAsync(); + } + + private static async Task StoreCanaryAsync(string connectionString) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(connectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using var transaction = await app.BeginTransactionAsync(); + await ScopeAsync(app, transaction, SchemaFixture.TenantA); + await LockAsync(app, transaction, SchemaFixture.TenantA, null, false); + await ExecuteAsync(app, transaction, """ + UPDATE public.membership_profiles SET display_name=@payload WHERE membership_id=@member; + SET CONSTRAINTS ALL IMMEDIATE; + """, ("payload", Payload), ("member", LearnerMembershipA)); + await transaction.CommitAsync(); + } + + private static Task PolicyCensusAsync(NpgsqlConnection owner) => ScalarAsync(owner, null, """ + SELECT jsonb_build_object( + 'policies',(SELECT jsonb_agg(jsonb_build_array(polrelid,polname,polpermissive,polcmd,polroles::text, + pg_get_expr(polqual,polrelid),pg_get_expr(polwithcheck,polrelid)) ORDER BY polrelid,polname) + FROM pg_policy WHERE polrelid IN ('public.roles'::regclass,'public.memberships'::regclass)), + 'function_exists',to_regprocedure('public.identity_contextual_read_sink_fault()') IS NOT NULL)::text + """); + + private sealed class ProviderFailureWitness : DbCommandInterceptor + { + public Exception? Failure { get; private set; } + public int Commands { get; private set; } + public override Task CommandFailedAsync(DbCommand command, CommandErrorEventData eventData, + CancellationToken cancellationToken = default) + { + Failure = eventData.Exception; + Commands++; + return Task.CompletedTask; + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/IdentityScopeLifecycleTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentityScopeLifecycleTests.cs new file mode 100644 index 000000000..6e9405713 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentityScopeLifecycleTests.cs @@ -0,0 +1,117 @@ +using FluentAssertions; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Tenancy.Application.Contracts.IdentityLifecycle; +using LearnStack.Modules.Tenancy.Infrastructure.Persistence; +using LearnStack.SharedKernel.Errors; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed class IdentityScopeLifecycleTests(SchemaFixture schema) +{ + [Theory] + [InlineData("Trial", true)] + [InlineData("Active", true)] + [InlineData("Suspended", false)] + [InlineData("Archived", false)] + public async Task Tenant_facts_use_fresh_real_status_and_absent_org_has_no_organization_facts(string status, bool allows) + { + 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 context = new Context(TenantId.From(SchemaFixture.TenantA), null); + await unit.SetTenantContextAsync(context); + var reader = new IdentityScopeLifecycleReader(unit); + await ExecuteAsync(unit, "UPDATE public.tenants SET status = @status WHERE id = @tenant", ("status", status), ("tenant", context.TenantId.Value)); + (await reader.ReadAsync(context.TenantId, null)).Should().Be(new IdentityScopeLifecycle(true, allows, false, false)); + // A second fresh statement must see the actual current state, not the first result. + await ExecuteAsync(unit, "UPDATE public.tenants SET status = 'Active' WHERE id = @tenant", ("tenant", context.TenantId.Value)); + (await reader.ReadAsync(context.TenantId, null)).TenantAllowsOrdinaryWork.Should().BeTrue(); + // Status changes are a fixture accommodation and roll back with this frame. + } + + [Theory] + [InlineData("Active", true)] + [InlineData("Suspended", false)] + [InlineData("Archived", false)] + public async Task Organization_belonging_is_separate_from_current_work_eligibility(string status, bool allows) + { + 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 context = new Context(TenantId.From(SchemaFixture.TenantA), OrganizationId.From(SchemaFixture.OrgA1)); + await unit.SetTenantContextAsync(context); + await ExecuteAsync(unit, "UPDATE public.organizations SET status = @status WHERE id = @org", ("status", status), ("org", context.OrganizationId!.Value.Value)); + var facts = await new IdentityScopeLifecycleReader(unit).ReadAsync(context.TenantId, context.OrganizationId); + facts.TenantExistsAndNotDeleted.Should().BeTrue(); + facts.OrganizationBelongsToTenant.Should().BeTrue(); + facts.OrganizationAllowsOrdinaryWork.Should().Be(allows); + } + + [Fact] + public async Task Missing_or_foreign_scope_facts_are_closed_and_cannot_retarget_the_announcement() + { + 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 context = new Context(TenantId.From(SchemaFixture.TenantA), OrganizationId.From(SchemaFixture.OrgB1)); + await unit.SetTenantContextAsync(context); + var reader = new IdentityScopeLifecycleReader(unit); + var facts = await reader.ReadAsync(context.TenantId, context.OrganizationId); + facts.OrganizationBelongsToTenant.Should().BeFalse(); + facts.OrganizationAllowsOrdinaryWork.Should().BeFalse(); + await FluentActions.Awaiting(() => reader.ReadAsync(TenantId.From(SchemaFixture.TenantB), context.OrganizationId)) + .Should().ThrowAsync().WithMessage("Identity scope lifecycle is unavailable."); + await FluentActions.Awaiting(() => reader.ReadAsync(context.TenantId, null)) + .Should().ThrowAsync(); + unit.GetTenantContextAnnouncement(unit.Transaction)!.TenantId.Should().Be(context.TenantId); + } + + [Fact] + public async Task Actual_server_isolation_cannot_be_replaced_by_the_drivers_cached_mode() + { + 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(); + await ExecuteAsync(unit, "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ"); + var context = new Context(TenantId.From(SchemaFixture.TenantA), null); + await unit.SetTenantContextAsync(context); + await FluentActions.Awaiting(() => new IdentityScopeLifecycleReader(unit).ReadAsync(context.TenantId, null)) + .Should().ThrowAsync().WithMessage("Identity scope lifecycle is unavailable."); + } + + [Fact] + public async Task Missing_tenant_and_unannounced_owner_cannot_produce_live_facts() + { + await using var source = ApplicationDataSource.Build(schema.Postgres.AppConnectionString); + await using var unit = new NpgsqlUnitOfWork(source, NullLogger.Instance); + var reader = new IdentityScopeLifecycleReader(unit); + await FluentActions.Awaiting(() => reader.ReadAsync(TenantId.From(SchemaFixture.TenantA), null)) + .Should().ThrowAsync(); + await using var frame = await unit.BeginTransactionAsync(); + var missing = TenantId.From(Guid.CreateVersion7()); + await unit.SetProvisioningTenantContextAsync(missing); + (await reader.ReadAsync(missing, null)).Should().Be(new IdentityScopeLifecycle(false, false, false, false)); + } + + private static async Task ExecuteAsync(NpgsqlUnitOfWork unit, string sql, params (string Key, object Value)[] values) + { + await using var command = new NpgsqlCommand(sql, (NpgsqlConnection)unit.Connection, (NpgsqlTransaction)unit.Transaction!); + foreach (var (key, value) in values) command.Parameters.AddWithValue(key, value); + await command.ExecuteNonQueryAsync(); + } + + 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/IdentitySeederTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/IdentitySeederTests.cs new file mode 100644 index 000000000..3718c1afa --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/IdentitySeederTests.cs @@ -0,0 +1,383 @@ +using System.Text; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Application.Contracts.Bindings; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Secrets; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.Tools.Seeder; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Logging; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +/// The shipped external Seeder capability, app-role commands and durable separate acts. +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +[Collection(SharedSchema.Name)] +public sealed class IdentitySeederTests(SchemaFixture schema) : IAsyncLifetime +{ + private static readonly IdentityAuthorityRegistration Registration = new( + IdentityAuthorityId.From(Guid.Parse("01930000-0000-7000-8000-000000009001")), + "http://localhost:8080/realms/learnstack"); + private DisposableSchemaDatabase _database = null!; + + public async Task InitializeAsync() + { + _database = await DisposableSchemaDatabase.CreateAsync(schema.Postgres); + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.MigrationConnectionString); + await IdentityAuthorityDeploymentInstaller.InstallAsync(owner, Registration); + } + + public Task DisposeAsync() => _database.DisposeAsync().AsTask(); + + [Fact] + public async Task Four_actual_provider_bindings_sixteen_templates_and_four_scoped_memberships_are_exact_and_reruns_write_nothing() + { + var captured = new SeedLogCapture(); + using var logs = LoggerFactory.Create(builder => builder.AddProvider(captured)); + await using var dataSource = ApplicationDataSource.Build(_database.AppConnectionString); + await SeedContentAsync(dataSource, logs); + await RunAsync(dataSource, loggerFactory: logs); + await AssertCompleteAsync(); + await AssertCapturedChildrenAsync(); + captured.Text.Should().NotBeNullOrEmpty(); + for (var index = 0; index < 4; index++) captured.Text.Should().NotContain($"provider-admin-id-{index}"); + var before = await AuditCountAsync(); + before.Should().Be(SeedData.ExpectedCombinedAuditWrites); + await RunAsync(dataSource); + await AssertCompleteAsync(); + (await AuditCountAsync()).Should().Be(before, "completed acts are read before any writer is dispatched"); + } + + [Theory] + [InlineData("identity.membership.create_first_seed_admin", 0)] + [InlineData("identity.membership_profile.set_seed_profile", 4)] + public async Task Central_MUST_failure_rolls_back_only_the_failed_graph_and_clean_rerun_resumes(string operation, long priorMembers) + { + await using var dataSource = ApplicationDataSource.Build(_database.AppConnectionString); + await SeedContentAsync(dataSource); + if (operation is not ("identity.membership.create_first_seed_admin" or "identity.membership_profile.set_seed_profile")) + throw new ArgumentException("Fixture operation is invalid.", nameof(operation)); + await DeploymentAsync($$""" + CREATE FUNCTION public.proof_reject_seed_success() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + IF NEW.operation='{{operation}}' AND NEW.outcome='success' THEN + RAISE EXCEPTION 'fixed audit proof refusal' USING ERRCODE='23514'; + END IF; + RETURN NEW; + END $$; + CREATE TRIGGER proof_reject_seed_success BEFORE INSERT ON public.audit_log + FOR EACH ROW EXECUTE FUNCTION public.proof_reject_seed_success(); + """); + try + { + var act = async () => await RunAsync(dataSource); + await act.Should().ThrowAsync(); + (await CountContextualAsync("roles")).Should().Be(16L); + (await CountContextualAsync("memberships")).Should().Be(priorMembers); + (await CountContextualAsync("membership_profiles")).Should().Be(priorMembers); + (await CountContextualAsync("membership_role_assignments")).Should().Be(priorMembers); + await using var platform = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.PlatformConnectionString); + (await IdentityMembershipFixture.ScalarAsync(platform, null, + "SELECT count(*) FROM public.audit_log WHERE operation=@operation AND outcome='success'", ("operation", operation))).Should().Be(0L); + (await IdentityMembershipFixture.ScalarAsync(platform, null, + "SELECT count(*) FROM public.audit_log WHERE operation='identity.user.create' AND outcome='success'")).Should().Be(4L); + if (priorMembers == 4) + { + foreach (var member in SeedData.IdentityMemberships) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await IdentityMembershipFixture.ScopeAsync(app, transaction, member.Identity.Tenant.TenantId.Value, member.OrganizationId?.Value); + (await IdentityMembershipFixture.ScalarAsync(app, transaction, """ + SELECT count(*) 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=@member AND m.row_version=0 AND p.display_name IS NULL AND p.preferred_locale IS NULL + """, ("member", member.MembershipId))).Should().Be(1L); + } + } + } + finally + { + await DeploymentAsync("DROP TRIGGER proof_reject_seed_success ON public.audit_log; DROP FUNCTION public.proof_reject_seed_success();"); + } + await RunAsync(dataSource); + await AssertCompleteAsync(); + await using var success = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.PlatformConnectionString); + (await IdentityMembershipFixture.ScalarAsync(success, null, + "SELECT count(*) FROM public.audit_log WHERE outcome='success'")).Should().Be(SeedData.ExpectedCombinedAuditWrites); + } + + [Theory] + [InlineData(7, 2, 0)] + [InlineData(55, 16, 2)] + [InlineData(64, 16, 4)] + public async Task Interrupted_committed_acts_resume_only_missing_declarations(int failAtContext, long expectedRoles, long expectedMembers) + { + await using var dataSource = ApplicationDataSource.Build(_database.AppConnectionString); + await SeedContentAsync(dataSource); + var act = async () => await RunAsync(dataSource, failAtContext); + await act.Should().ThrowAsync(); + (await CountContextualAsync("roles")).Should().Be(expectedRoles); + (await CountContextualAsync("memberships")).Should().Be(expectedMembers); + await RunAsync(dataSource); + await AssertCompleteAsync(); + (await AuditCountAsync()).Should().Be(SeedData.ExpectedCombinedAuditWrites); + } + + [Fact] + public async Task Edited_or_upgraded_initial_grants_refuse_without_repair_or_additional_audit() + { + await using var dataSource = ApplicationDataSource.Build(_database.AppConnectionString); + await SeedContentAsync(dataSource); + await RunAsync(dataSource); + var role = SeedData.IdentityRoles[0]; + await using (var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.AppConnectionString)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await IdentityMembershipFixture.ScopeAsync(app, transaction, role.Tenant.TenantId.Value); + await IdentityMembershipFixture.LockAsync(app, transaction, role.Tenant.TenantId.Value, null, true); + await IdentityMembershipFixture.ExecuteAsync(app, transaction, """ + DELETE FROM public.role_permission_grants WHERE tenant_id=@tenant AND role_id=@role + AND permission_key='identity.membership_profile.write'; + UPDATE public.roles SET row_version=row_version+1 WHERE tenant_id=@tenant AND id=@role; + SET CONSTRAINTS ALL IMMEDIATE; + """, ("tenant", role.Tenant.TenantId.Value), ("role", role.RoleId)); + await transaction.CommitAsync(); + } + var before = await AuditCountAsync(); + var act = async () => await RunAsync(dataSource); + (await act.Should().ThrowAsync()).Which.Message + .Should().Be("Development identity foundation was refused."); + (await AuditCountAsync()).Should().Be(before); + (await CountContextualAsync("role_permission_grants")).Should().Be(SeedData.IdentityRoles.Sum(roleDeclaration => + LearnStack.Modules.Identity.Domain.IdentityFoundationManifest.Version1.FindTemplate(roleDeclaration.BuiltInKey, roleDeclaration.Scope)!.Grants.Length) - 1); + } + + [Theory] + [InlineData("Suspended")] + [InlineData("Revoked")] + public async Task A_nonactive_membership_stops_remaining_acts_and_is_never_recreated(string status) + { + await using var dataSource = ApplicationDataSource.Build(_database.AppConnectionString); + await SeedContentAsync(dataSource); + await RunAsync(dataSource); + var member = SeedData.IdentityMemberships[1]; + await using (var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.AppConnectionString)) + await using (var transaction = await app.BeginTransactionAsync()) + { + await IdentityMembershipFixture.ScopeAsync(app, transaction, member.Identity.Tenant.TenantId.Value); + await IdentityMembershipFixture.LockAsync(app, transaction, member.Identity.Tenant.TenantId.Value, null, false); + await IdentityMembershipFixture.ExecuteAsync(app, transaction, """ + UPDATE public.memberships SET status=@status,row_version=row_version+1, + deleted_at=CASE WHEN @status='Revoked' THEN clock_timestamp() ELSE NULL END, + deleted_by=CASE WHEN @status='Revoked' THEN @actor ELSE NULL END + WHERE tenant_id=@tenant AND id=@member; + SET CONSTRAINTS ALL IMMEDIATE; + """, ("status", status), ("actor", UserId.SystemActor.Value), + ("tenant", member.Identity.Tenant.TenantId.Value), ("member", member.MembershipId)); + await transaction.CommitAsync(); + } + var before = await AuditCountAsync(); + var act = async () => await RunAsync(dataSource); + await act.Should().ThrowAsync(); + (await AuditCountAsync()).Should().Be(before); + (await CountContextualAsync("memberships")).Should().Be(4L); + } + + [Fact] + public async Task A_mismatched_deployment_anchor_refuses_before_any_binding_or_contextual_mutation() + { + await using var dataSource = ApplicationDataSource.Build(_database.AppConnectionString); + var other = new IdentityAuthorityRegistration(Registration.AuthorityId, "https://localhost/realms/learnstack"); + var witness = await WitnessAsync(other); + var admission = new FixedSeedIdentityFoundationAdmission(witness); + var runner = new SeedIdentityFoundationRunner(context => SeedComposition.Build(dataSource, context, + NullLoggerFactory.Instance, identityAuthority: other, seedAdmission: admission), admission); + var act = async () => await runner.RunAsync(); + await act.Should().ThrowAsync(); + (await AuditCountAsync()).Should().Be(0L); + (await CountContextualAsync("roles")).Should().Be(0L); + } + + private static Task SeedContentAsync(NpgsqlDataSource dataSource, ILoggerFactory? loggerFactory = null) => + new SeedRunner(context => SeedComposition.Build(dataSource, context, loggerFactory ?? NullLoggerFactory.Instance), + (loggerFactory ?? NullLoggerFactory.Instance).CreateLogger()).RunAsync(CancellationToken.None); + + private static async Task RunAsync(NpgsqlDataSource dataSource, int? failAtContext = null, ILoggerFactory? loggerFactory = null) + { + var witness = await WitnessAsync(Registration); + var admission = new FixedSeedIdentityFoundationAdmission(witness); + var contexts = 0; + var runner = new SeedIdentityFoundationRunner(context => + { + if (context is not null && ++contexts == failAtContext) + throw new InvalidOperationException("Fixture interruption before dispatch."); + return SeedComposition.Build(dataSource, context, loggerFactory ?? NullLoggerFactory.Instance, + identityAuthority: Registration, seedAdmission: admission); + }, admission); + await runner.RunAsync(); + foreach (var person in SeedData.IdentityUsers) + { + await using var provider = SeedComposition.Build(dataSource, null, NullLoggerFactory.Instance, + identityAuthority: Registration, seedAdmission: admission); + await provider.GetRequiredService().QualifyAsync(); + await using var scope = provider.CreateAsyncScope(); + var binding = await scope.ServiceProvider.GetRequiredService() + .ResolveExistingAsync(witness.Subjects[person.UserId]); + binding.IsBound.Should().BeTrue(); + binding.Actor.Should().Be(person.UserId); + } + } + + private static async Task WitnessAsync(IdentityAuthorityRegistration registration) + { + var source = JsonSerializer.Serialize(new + { + version = 1, + issuer = registration.Issuer, + users = SeedData.IdentityUsers.Select((person, index) => new { actorId = person.UserId.Value, opaqueSub = $"provider-admin-id-{index}" }), + }); + await using var input = new MemoryStream(Encoding.UTF8.GetBytes(source)); + return await SeedProviderWitness.ReadAsync(input, registration); + } + + private async Task AssertCompleteAsync() + { + (await CountContextualAsync("roles")).Should().Be(16L); + (await CountContextualAsync("memberships")).Should().Be(4L); + (await CountContextualAsync("membership_profiles")).Should().Be(4L); + (await CountContextualAsync("membership_role_assignments")).Should().Be(4L); + foreach (var declared in SeedData.IdentityMemberships) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await IdentityMembershipFixture.ScopeAsync(app, transaction, declared.Identity.Tenant.TenantId.Value, + declared.OrganizationId?.Value); + (await IdentityMembershipFixture.ScalarAsync(app, transaction, """ + SELECT count(*) FROM public.memberships m JOIN public.membership_profiles p + ON p.tenant_id=m.tenant_id AND p.membership_id=m.id + JOIN public.membership_role_assignments a ON a.tenant_id=m.tenant_id AND a.membership_id=m.id + WHERE m.id=@member AND m.user_id=@person AND m.organization_id IS NOT DISTINCT FROM @organization + AND m.status='Active' AND m.deleted_at IS NULL AND m.row_version=1 + AND p.display_name=@display AND p.preferred_locale=@locale AND a.role_id=@role + """, ("member", declared.MembershipId), ("person", declared.Identity.UserId.Value), + ("organization", declared.OrganizationId?.Value), ("display", declared.DisplayName), + ("locale", declared.PreferredLocale), ("role", declared.Role.RoleId))).Should().Be(1L); + } + } + + private async Task CountContextualAsync(string table) + { + if (table is not ("roles" or "role_permission_grants" or "memberships" or "membership_profiles" or "membership_role_assignments")) + throw new ArgumentException("Fixture table is invalid.", nameof(table)); + long count = 0; + foreach (var tenant in SeedData.All) + { + OrganizationId?[] organizations = table is "roles" or "role_permission_grants" + ? [null] : [null, tenant.DefaultOrganization.OrganizationId, tenant.SecondOrganization.OrganizationId]; + foreach (var organization in organizations) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await SchemaQueries.AssertApplicationRoleAsync(app); + await IdentityMembershipFixture.ScopeAsync(app, transaction, tenant.TenantId.Value, organization?.Value); + count += table is "roles" or "role_permission_grants" + ? await IdentityMembershipFixture.ScalarAsync(app, transaction, $"SELECT count(*) FROM public.{table}") + : await IdentityMembershipFixture.ScalarAsync(app, transaction, + $"SELECT count(*) FROM public.{table} WHERE organization_id IS NOT DISTINCT FROM @organization", + ("organization", organization?.Value)); + } + } + return count; + } + + private async Task AuditCountAsync() + { + await using var platform = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.PlatformConnectionString); + return await IdentityMembershipFixture.ScalarAsync(platform, null, "SELECT count(*) FROM public.audit_log"); + } + + private async Task DeploymentAsync(string sql) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.MigrationConnectionString); + await IdentityMembershipFixture.ExecuteAsync(owner, null, sql); + } + + private async Task AssertCapturedChildrenAsync() + { + await using var platform = (NpgsqlConnection)await PostgresFixture.OpenAsync(_database.PlatformConnectionString); + await using var command = new NpgsqlCommand(""" + SELECT operation,coalesce(after_state::text,''),coalesce(changes::text,''),coalesce(before_state::text,'') + FROM public.audit_log WHERE module='identity' AND outcome='success' + """, platform); + await using var rows = await command.ExecuteReaderAsync(); + var roles = 0; var grantedRoles = 0; var members = 0; var profiles = 0; + while (await rows.ReadAsync()) + { + var operation = rows.GetString(0); + var after = rows.GetString(1); + var changes = rows.GetString(2); + var snapshots = after + changes + rows.GetString(3); + for (var index = 0; index < 4; index++) snapshots.Should().NotContain($"provider-admin-id-{index}"); + if (operation == "identity.role.initialize") + { + roles++; + if (after.Contains("permissionKey", StringComparison.OrdinalIgnoreCase)) + { + grantedRoles++; + after.Should().ContainEquivalentOf("grants"); + changes.Should().ContainEquivalentOf("grants"); + } + } + else if (operation is "identity.membership.create_first_seed_admin" or "identity.membership.create_seed") + { + members++; + after.Should().ContainEquivalentOf("profile").And.ContainEquivalentOf("roleAssignments"); + changes.Should().ContainEquivalentOf("roleAssignments"); + using var created = JsonDocument.Parse(after); + created.RootElement.GetProperty("Profile").GetProperty("DisplayName").GetString() + .Should().Be(SensitiveTokenCatalog.RedactedValue); + created.RootElement.GetProperty("Profile").GetProperty("PreferredLocale").GetString() + .Should().Be(SensitiveTokenCatalog.RedactedValue); + } + else if (operation == "identity.membership_profile.set_seed_profile") + { + profiles++; + changes.Should().ContainEquivalentOf("profile").And.Contain(SensitiveTokenCatalog.RedactedValue); + using var diff = JsonDocument.Parse(changes); + var sensitive = diff.RootElement.EnumerateArray().Where(field => + field.GetProperty("path").GetString() is { } path && path.Contains("/Profile/", StringComparison.Ordinal) + && (path.EndsWith("/DisplayName", StringComparison.Ordinal) || path.EndsWith("/PreferredLocale", StringComparison.Ordinal))).ToArray(); + sensitive.Should().HaveCount(2); + sensitive.Should().OnlyContain(field => field.GetProperty("after").GetString() == SensitiveTokenCatalog.RedactedValue + && field.GetProperty("before").GetString() == SensitiveTokenCatalog.RedactedValue); + foreach (var member in SeedData.IdentityMemberships) snapshots.Should().NotContain(member.DisplayName); + } + } + roles.Should().Be(16); grantedRoles.Should().Be(8); members.Should().Be(4); profiles.Should().Be(4); + } + + private sealed class SeedLogCapture : ILoggerProvider + { + private readonly List _messages = []; + public string Text { get { lock (_messages) return string.Join('\n', _messages); } } + public ILogger CreateLogger(string categoryName) => new CapturingLogger(this); + public void Dispose() { } + private sealed class CapturingLogger(SeedLogCapture owner) : 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) + { + lock (owner._messages) owner._messages.Add(formatter(state, exception)); + } + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/MigrationChains.cs b/backend/tests/LearnStack.Tests.Integration/Database/MigrationChains.cs index 3cd4462d5..7848d2aef 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/MigrationChains.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/MigrationChains.cs @@ -2,6 +2,7 @@ using LearnStack.Modules.Audit.Infrastructure.Persistence; using LearnStack.Modules.Customization.Infrastructure.Persistence; using LearnStack.Modules.Education.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Infrastructure.Persistence; using LearnStack.Modules.Tenancy.Infrastructure.Persistence; using LearnStack.SharedKernel.Tenancy; using Microsoft.EntityFrameworkCore; @@ -41,14 +42,6 @@ public static async Task ApplyAllAsync(string migrationConnectionString) await platform.Database.MigrateAsync(); } - await using (var customization = new CustomizationDbContext( - Options( - migrationConnectionString, CustomizationDbContextFactory.HistoryTable), - StaticTenantContextAccessor.Unresolved)) - { - await customization.Database.MigrateAsync(); - } - // Tenancy is first, and that order is not cosmetic: audit_config // carries the schema's only foreign key crossing two chains, to `tenants`. A // fixture that hand-orders what `make migrate` globs is how a suite goes green @@ -61,6 +54,20 @@ public static async Task ApplyAllAsync(string migrationConnectionString) await audit.Database.MigrateAsync(); + // The central creation witnesses require the existing Audit schema. + await using var identity = new IdentityDbContext( + Options(migrationConnectionString, IdentityDbContextFactory.HistoryTable), + StaticTenantContextAccessor.Unresolved, EmptyIdentityScope.Instance); + await identity.Database.MigrateAsync(); + + await using (var customization = new CustomizationDbContext( + Options( + migrationConnectionString, CustomizationDbContextFactory.HistoryTable), + StaticTenantContextAccessor.Unresolved)) + { + await customization.Database.MigrateAsync(); + } + // Education's organization guards call the shared function owned by Tenancy. // Its parent references remain inside Education (ADR-0003 Amendment 6). await using var education = new EducationDbContext( @@ -86,6 +93,7 @@ public static async Task ApplyTenancyAsync(string migrationConnectionString) CustomizationDbContextFactory.HistoryTable, AuditDbContextFactory.HistoryTable, EducationDbContextFactory.HistoryTable, + IdentityDbContextFactory.HistoryTable, ]; private static DbContextOptions Options( diff --git a/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs index 0bb4d070e..5c3a3b094 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/MigrationRollbackTests.cs @@ -4,6 +4,7 @@ using LearnStack.Modules.Customization.Infrastructure.Persistence; using LearnStack.Modules.Education.Infrastructure.Persistence; using LearnStack.Modules.Tenancy.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Infrastructure.Persistence; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; @@ -49,9 +50,9 @@ public async Task EveryChainReversesToAnEmptySchema() // Applied state first, so a rollback that reversed nothing because nothing // was there cannot pass. - (await CountAsync(connection, TablesQuery)).Should().Be(47L, + (await CountAsync(connection, TablesQuery)).Should().Be(55L, "eight tenancy tables, twenty-four platform tables, four customization tables, " - + "two audit tables, four Education tables, and five history tables"); + + "two audit tables, four Education tables, seven Identity tables and six history tables"); (await CountAsync(connection, FunctionQuery)).Should().Be(1L, "fn_organization_id_immutable backs the tenant_settings trigger"); (await CountAsync(connection, AuditFunctionQuery)).Should().Be(2L, @@ -61,6 +62,8 @@ public async Task EveryChainReversesToAnEmptySchema() "each Education parent relation has its own invoker scope check"); (await CountAsync(connection, InboxFunctionQuery)).Should().Be(1L, "fn_inbox_messages_immutable backs the shared inbox append-only trigger"); + (await CountAsync(connection, IdentityFunctionQuery)).Should().Be(12L, + "Identity installs five global binding/creation/evidence functions and seven contextual functions"); (await CountAsync(connection, JobFunctionQuery)).Should().BeGreaterThan(0, "the new job guards must be installed before their reversal is tested"); @@ -69,8 +72,8 @@ public async Task EveryChainReversesToAnEmptySchema() await _fixture.RollBackAsync(); // The history tables survive: `database update 0` empties them, it does not - // drop them. Everything the five chains created is gone. - (await CountAsync(connection, TablesQuery)).Should().Be(5L); + // drop them. Everything the six chains created is gone. + (await CountAsync(connection, TablesQuery)).Should().Be(6L); (await CountAsync(connection, FunctionQuery)).Should().Be(0L); // The audit triggers went with their table; the FUNCTIONS did not, and a @@ -80,6 +83,7 @@ public async Task EveryChainReversesToAnEmptySchema() (await CountAsync(connection, AuditFunctionQuery)).Should().Be(0L); (await CountAsync(connection, EducationFunctionQuery)).Should().Be(0L); (await CountAsync(connection, InboxFunctionQuery)).Should().Be(0L); + (await CountAsync(connection, IdentityFunctionQuery)).Should().Be(0L); (await CountAsync(connection, PolicyQuery)).Should().Be(0L); (await CountAsync(connection, JobFunctionQuery)).Should().Be(0L); @@ -87,11 +91,12 @@ public async Task EveryChainReversesToAnEmptySchema() // A successful Down must also leave a state that can be installed again. await MigrationChains.ApplyAllAsync(_fixture.Postgres.MigrationConnectionString); - (await CountAsync(connection, TablesQuery)).Should().Be(47L); + (await CountAsync(connection, TablesQuery)).Should().Be(55L); (await CountAsync(connection, FunctionQuery)).Should().Be(1L); (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(12L); await EducationSchemaSeed.SeedAsync(_fixture.Postgres.AppConnectionString); await using var app = await PostgresFixture.OpenAsync(_fixture.Postgres.AppConnectionString); await using var transaction = await app.BeginTransactionAsync(); @@ -129,6 +134,9 @@ public async Task EveryChainReversesToAnEmptySchema() "SELECT count(*) FROM pg_proc WHERE pronamespace = 'public'::regnamespace " + "AND proname = 'fn_inbox_messages_immutable'"; + private const string IdentityFunctionQuery = + "SELECT count(*) FROM pg_proc WHERE pronamespace = 'public'::regnamespace AND proname LIKE 'fn_identity_%'"; + private const string EducationFunctionQuery = "SELECT count(*) FROM pg_proc WHERE pronamespace = 'public'::regnamespace " + "AND proname IN ('fn_lessons_parent_scope', 'fn_course_translations_parent_scope', " @@ -167,6 +175,13 @@ public async Task InitializeAsync() /// public async Task RollBackAsync() { + // Disposable-schema reversal only: normal deployment never retires permanent + // bindings by rolling this chain back. Release Audit witness dependencies first. + await using (var identity = CreateIdentity()) + { + await identity.GetService().MigrateAsync(Migration.InitialDatabase); + } + // Education first: its four immutability triggers call Tenancy's function. await using (var education = CreateEducation()) { @@ -205,6 +220,12 @@ private TenancyDbContext CreateTenancy() => .Options, StaticTenantContextAccessor.Unresolved); + private IdentityDbContext CreateIdentity() => + new(new DbContextOptionsBuilder() + .UseNpgsql(Postgres.MigrationConnectionString, provider => + provider.MigrationsHistoryTable(IdentityDbContextFactory.HistoryTable)).Options, + StaticTenantContextAccessor.Unresolved, EmptyIdentityScope.Instance); + private EducationDbContext CreateEducation() => new( new DbContextOptionsBuilder() diff --git a/backend/tests/LearnStack.Tests.Integration/Database/NoOpAuditStore.cs b/backend/tests/LearnStack.Tests.Integration/Database/NoOpAuditStore.cs index ead8fb37b..c087b9639 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/NoOpAuditStore.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/NoOpAuditStore.cs @@ -17,6 +17,14 @@ namespace LearnStack.Tests.Integration.Database; /// internal sealed class NoOpAuditStore : IAuditStore { + public Task WriteGlobalIdentityPendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unit, + GlobalIdentityCreationReference creation, CancellationToken cancellationToken = default) => + throw new NotSupportedException("Global identity has its own cases."); + + public Task ReconcileGlobalIdentityAsync(AuditIntent intent, IReadOnlyList changes, + AuditIntentState state, DateTimeOffset timestamp, CancellationToken cancellationToken = default) => + throw new NotSupportedException("Global identity has its own cases."); + public int PendingWrites { get; private set; } public Task WritePendingAsync(IUnitOfWork unitOfWork, CancellationToken cancellationToken = default) diff --git a/backend/tests/LearnStack.Tests.Integration/Database/OutboxDispatchStoreTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/OutboxDispatchStoreTests.cs index c1d650f0c..5acd7fcc8 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/OutboxDispatchStoreTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/OutboxDispatchStoreTests.cs @@ -1199,6 +1199,14 @@ private sealed class TerminalAuditDecorator( IAuditStore inner, Func terminal) : IAuditStore { + public Task WriteGlobalIdentityPendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unit, + GlobalIdentityCreationReference creation, CancellationToken cancellationToken = default) => + inner.WriteGlobalIdentityPendingAsync(unit, creation, cancellationToken); + + public Task ReconcileGlobalIdentityAsync(AuditIntent intent, IReadOnlyList changes, + AuditIntentState state, DateTimeOffset timestamp, CancellationToken cancellationToken = default) => + inner.ReconcileGlobalIdentityAsync(intent, changes, state, timestamp, cancellationToken); + public Task WriteJobTerminalAsync(AuditEntryDraft entry, JobTerminalTransition transition, DbConnection connection, DbTransaction transaction, CancellationToken cancellationToken = default) => inner.WriteJobTerminalAsync(entry, transition, connection, transaction, cancellationToken); public Task WritePendingAsync(IUnitOfWork unitOfWork, CancellationToken cancellationToken = default) => diff --git a/backend/tests/LearnStack.Tests.Integration/Database/OutboxProcessorTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/OutboxProcessorTests.cs index 4cfc03d0c..4adc553ac 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/OutboxProcessorTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/OutboxProcessorTests.cs @@ -3,6 +3,7 @@ using System.Diagnostics; using System.Net; using FluentAssertions; +using LearnStack.Api.Authentication; using LearnStack.Api.Jobs; using LearnStack.Api.Messaging; using LearnStack.Infrastructure.Messaging; @@ -844,10 +845,11 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) builder.UseSetting("ConnectionStrings:OutboxDispatcher", credential); builder.ConfigureTestServices(services => { - // This fixture proves producer acceptance independently of business delivery. + // This fixture owns real producer acceptance, but no business delivery or Identity authority. foreach (var descriptor in services.Where(descriptor => descriptor.ServiceType == typeof(IHostedService) && (descriptor.ImplementationType ?? descriptor.ImplementationFactory?.Method.ReturnType) is { } implementation - && (implementation == typeof(DeliveryProcessor) || implementation == typeof(BackgroundJobHostedService))).ToArray()) + && (implementation == typeof(DeliveryProcessor) || implementation == typeof(BackgroundJobHostedService) + || implementation == typeof(TenantIdentityAuthorityStartupService))).ToArray()) services.Remove(descriptor); services.RemoveAll(); services.AddSingleton(bounds ?? Bounds); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/OutboxProducerTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/OutboxProducerTests.cs index c7c356edc..ce01d6805 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/OutboxProducerTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/OutboxProducerTests.cs @@ -766,7 +766,7 @@ private static Task> RunAsync( services.GetRequiredService(), services.GetRequiredService(), services.GetRequiredService(), - NullLogger.Instance); + NullLogger.Instance, services.GetRequiredService()); return audit.ExecuteAsync(audited ? typeof(DirectHandler) : typeof(OffHandler), provisioning, () => services.GetRequiredService().ExecuteAsync( provisioning, mode, "outbox-proof", body), CancellationToken.None); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs index aaaa4cad0..984230053 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/PlatformAdminScopeTests.cs @@ -714,6 +714,7 @@ private static IServiceScopeFactory AuditStoreScopeFactory() => .AddSingleton() .AddSingleton(new AuditCatalog([new TenancyAuditCatalogSource()])) .AddSingleton(StaticTenantContextAccessor.Unresolved) + .AddScoped() .AddSingleton(new Lazy( () => throw new InvalidOperationException( "The platform-scope row is written on the scope's own connection, so " @@ -731,6 +732,14 @@ private static IServiceScopeFactory RefusingStore() => private sealed class RefusingAuditStore : IAuditStore { + public Task WriteGlobalIdentityPendingAsync(LearnStack.SharedKernel.Persistence.IUnitOfWork unit, + GlobalIdentityCreationReference creation, CancellationToken cancellationToken = default) => + throw new NotSupportedException("Global identity has its own cases."); + + public Task ReconcileGlobalIdentityAsync(AuditIntent intent, IReadOnlyList changes, + AuditIntentState state, DateTimeOffset timestamp, CancellationToken cancellationToken = default) => + throw new NotSupportedException("Global identity has its own cases."); + public Task WritePendingAsync( LearnStack.SharedKernel.Persistence.IUnitOfWork unitOfWork, CancellationToken cancellationToken = default) => diff --git a/backend/tests/LearnStack.Tests.Integration/Database/ProducerExecutionTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/ProducerExecutionTests.cs index 1e7864926..e7ee33c73 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/ProducerExecutionTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/ProducerExecutionTests.cs @@ -597,7 +597,7 @@ private static AuditExecutionCoordinator DirectAudit(IServiceProvider services, services.GetRequiredService(), services.GetRequiredService(), services.GetRequiredService(), - NullLogger.Instance); + NullLogger.Instance, services.GetRequiredService()); private static void AssertClean(IServiceProvider services) { diff --git a/backend/tests/LearnStack.Tests.Integration/Database/PublicLocalLaunchTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/PublicLocalLaunchTests.cs index 430b0bb0c..292ebc791 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/PublicLocalLaunchTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/PublicLocalLaunchTests.cs @@ -14,7 +14,7 @@ namespace LearnStack.Tests.Integration.Database; /// Exercises the actual local API launcher with explicit application and dispatcher credentials. [Collection(PublicReadTestGroup.Name)] [Trait(RequiresDocker.Key, RequiresDocker.Value)] -public sealed class PublicLocalLaunchTests(PublicReadFixture fixture) +public sealed class PublicLocalLaunchTests(PublicReadFixture parent) { private const string Secret = "test-only-public-local-launch-secret-at-least-32"; @@ -30,6 +30,7 @@ public async Task Demo_API_runtime_rejects_a_foreign_user_secret_only_with_profi private async Task AssertLauncherAsync(bool useDemoRuntime, bool isolateProfile = true) { + await using var fixture = await IdentityPublicReadFixture.CreateAsync(parent, "http://localhost:8080/realms/learnstack"); var repository = RepositoryRoot(); var temporary = Path.Combine(Path.GetTempPath(), "learnstack-public-local-" + Guid.NewGuid().ToString("N")); var app = Path.Combine(temporary, "frontend/apps/web"); @@ -106,6 +107,8 @@ await File.WriteAllTextAsync(script, """ process.StartInfo.ArgumentList.Add(Path.Combine(temporary, "scripts/public-local.mjs")); process.StartInfo.ArgumentList.Add("api"); } + process.StartInfo.Environment["Identity__AuthorityId"] = fixture.Registration.AuthorityId.Value.ToString("D"); + process.StartInfo.Environment["Authentication__Tenant__Issuer"] = fixture.Registration.Issuer; process.StartInfo.Environment["ConnectionStrings__Default"] = fixture.AppConnectionString; process.StartInfo.Environment["ConnectionStrings__OutboxDispatcher"] = fixture.OutboxConnectionString; process.StartInfo.Environment["LEARNSTACK_PUBLIC_API_ORIGIN"] = "http://127.0.0.1:0"; diff --git a/backend/tests/LearnStack.Tests.Integration/Database/PublicReadFixture.cs b/backend/tests/LearnStack.Tests.Integration/Database/PublicReadFixture.cs index ba8e01a77..ed4d0f039 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/PublicReadFixture.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/PublicReadFixture.cs @@ -26,26 +26,46 @@ public sealed class PublicReadTestGroup : ICollectionFixture } /// Production API composition, seeded through real writers in an isolated four-role database. -public sealed class PublicReadFixture : ConstructionOnlyApiFactory, IAsyncLifetime +public class PublicReadFixture : ConstructionOnlyApiFactory, IAsyncLifetime { - private readonly PostgresFixture _postgres = new(); - public string AppConnectionString => _postgres.AppConnectionString; - public string OutboxConnectionString => _postgres.OutboxConnectionString; + private readonly PostgresFixture? _postgres; + private readonly DisposableSchemaDatabase? _database; + private bool _databaseDisposed; + + public PublicReadFixture() => _postgres = new(); + private protected PublicReadFixture(DisposableSchemaDatabase database) => _database = database; + internal PostgresFixture Postgres => _postgres ?? throw new InvalidOperationException("This fixture does not own PostgreSQL."); + public string AppConnectionString => _database?.AppConnectionString ?? Postgres.AppConnectionString; + public string OutboxConnectionString => _database?.OutboxConnectionString ?? Postgres.OutboxConnectionString; + internal string MigrationConnectionString => _database?.MigrationConnectionString ?? Postgres.MigrationConnectionString; + private string PlatformConnectionString => _database?.PlatformConnectionString ?? Postgres.PlatformConnectionString; public PublicReadObservation Observation { get; } = new(); public async Task InitializeAsync() { - await _postgres.InitializeAsync(); - await MigrationChains.ApplyAllAsync(_postgres.MigrationConnectionString); + if (_database is null) + { + await Postgres.InitializeAsync(); + await MigrationChains.ApplyAllAsync(MigrationConnectionString); + } await using var source = NpgsqlDataSource.Create(AppConnectionString); var runner = new SeedRunner(context => SeedComposition.Build(source, context, NullLoggerFactory.Instance), NullLogger.Instance); (await runner.RunAsync(CancellationToken.None)).Should().Be(0); } - async Task IAsyncLifetime.DisposeAsync() + async Task IAsyncLifetime.DisposeAsync() => await DisposeAsync(); + + public override async ValueTask DisposeAsync() { - await base.DisposeAsync(); - await _postgres.DisposeAsync(); + if (_databaseDisposed) return; + _databaseDisposed = true; + try { await base.DisposeAsync(); } + finally + { + if (_database is not null) await _database.DisposeAsync(); + else await Postgres.DisposeAsync(); + } + GC.SuppressFinalize(this); } public HttpClient ClientFor(string host, Action? configure = null, @@ -79,7 +99,7 @@ protected override void ConfigureTestHost(IWebHostBuilder builder) ArgumentNullException.ThrowIfNull(builder); builder.UseEnvironment(Environments.Development); builder.UseSetting("ConnectionStrings:Default", AppConnectionString); - builder.UseSetting("ConnectionStrings:PlatformAdmin", _postgres.PlatformConnectionString); + builder.UseSetting("ConnectionStrings:PlatformAdmin", PlatformConnectionString); builder.ConfigureTestServices(services => { services.AddSingleton(Observation); @@ -94,7 +114,7 @@ public Task ExecuteAsync(SeedTenant tenant, string sql, IReadOnlyDictionaryOwner-only corruption setup for immutable satellites; public reads still use the application role. public Task ExecuteOwnerFixtureAsync(SeedTenant tenant, string sql, IReadOnlyDictionary? parameters = null, OrganizationId? organization = null) => - ExecuteFixtureAsync(tenant, sql, _postgres.MigrationConnectionString, parameters, organization); + ExecuteFixtureAsync(tenant, sql, MigrationConnectionString, parameters, organization); private static async Task ExecuteFixtureAsync(SeedTenant tenant, string sql, string connectionString, IReadOnlyDictionary? parameters, OrganizationId? organization) { diff --git a/backend/tests/LearnStack.Tests.Integration/Database/PublicReadTransactionTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/PublicReadTransactionTests.cs index 4419a8a94..813204889 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/PublicReadTransactionTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/PublicReadTransactionTests.cs @@ -317,7 +317,7 @@ private ServiceProvider BuildProvider(ILoggerFactory? injectedLogs = null) capture, new Lazy(services.GetRequiredService), NullLogger.Instance, services.GetRequiredService(), new AuditHealth(), new AuditCatalog([]), - services.GetRequiredService()); + services.GetRequiredService(), new LearnStack.Infrastructure.Persistence.GlobalIdentityEnrollment()); private static async Task AssertRoleAsync(IUnitOfWork unit) { diff --git a/backend/tests/LearnStack.Tests.Integration/Database/SchemaFixture.cs b/backend/tests/LearnStack.Tests.Integration/Database/SchemaFixture.cs index 544194eab..f2592982e 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/SchemaFixture.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/SchemaFixture.cs @@ -58,7 +58,7 @@ public sealed class SchemaFixture : IAsyncLifetime public const string HostB = "beta.example.com"; /// - /// The forty-two data tables the five chains create, used only to prove that a + /// The data tables the six chains create, used only to prove that a /// catalogue sweep read something. /// /// @@ -140,6 +140,17 @@ public sealed class SchemaFixture : IAsyncLifetime static SchemaFixture() { + RowsVisibleToTenantA["users"] = 0; + RowsVisibleToTenantB["users"] = 0; + // Contextual subjects need an admitted immutable global authority; this + // platform read exposes no User row without its exact self announcement. + RowsVisibleToTenantA["identity_authority"] = 1; + RowsVisibleToTenantB["identity_authority"] = 1; + foreach (var table in SchemaTableClasses.IdentityContextual) + { + RowsVisibleToTenantA[table] = table == "roles" ? 8 : table == "role_permission_grants" ? 7 : 2; + RowsVisibleToTenantB[table] = table == "roles" ? 8 : table == "role_permission_grants" ? 7 : 1; + } foreach (var table in SchemaTableClasses.JobTenant) { RowsVisibleToTenantA[table] = table == "background_job_reservations" ? 3 : 1; @@ -165,6 +176,7 @@ public async Task InitializeAsync() await EducationSchemaSeed.SeedAsync(Postgres.AppConnectionString); await BackgroundJobSchemaSeed.SeedAsync(Postgres.AppConnectionString, Postgres.OutboxConnectionString); await HangfireSchemaSeed.SeedAsync(Postgres.OutboxConnectionString); + await IdentityMembershipFixture.SeedSchemaAsync(Postgres.MigrationConnectionString, Postgres.AppConnectionString); } public async Task DisposeAsync() => await Postgres.DisposeAsync(); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/SchemaTableClasses.cs b/backend/tests/LearnStack.Tests.Integration/Database/SchemaTableClasses.cs index 6c0705d21..51ed99ebb 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/SchemaTableClasses.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/SchemaTableClasses.cs @@ -30,7 +30,12 @@ internal static class SchemaTableClasses "platform_killswitches", "courses", "lessons", "course_translations", "lesson_translations", ]; - public static readonly string[] Data = [.. Existing, .. JobTenant, .. Control, .. Vendor]; + public static readonly string[] GlobalIdentity = ["users"]; + public static readonly string[] IdentityPlatform = ["identity_authority"]; + public static readonly string[] IdentityContextual = ["memberships", "membership_profiles", + "membership_role_assignments", "roles", "role_permission_grants"]; + public static readonly string[] Data = [.. Existing, .. JobTenant, .. Control, .. Vendor, + .. GlobalIdentity, .. IdentityPlatform, .. IdentityContextual]; public static bool AppSelectDenied(string table) => Control.Contains(table) || Vendor.Contains(table); internal static Task> ReadAsync(DbConnection connection, DbTransaction? transaction = null) => @@ -43,7 +48,7 @@ public static async Task AssertCompleteAsync(DbConnection connection, DbTransact { var discovered = await ReadAsync(connection, transaction); discovered.Should().BeEquivalentTo(Data.Concat(MigrationChains.HistoryTables), - "every public table must have an exact reviewed class, including the five history tables; " + "every public table must have an exact reviewed class, including the six history tables; " + "Fix: classify a new table under Standards 05 rather than excluding it from discovery"); } } diff --git a/backend/tests/LearnStack.Tests.Integration/Database/TenancySchemaTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/TenancySchemaTests.cs index 8975a0450..9eb49c9c6 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/TenancySchemaTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/TenancySchemaTests.cs @@ -149,15 +149,17 @@ public async Task Unsetting_tenant_context_returns_zero_rows_through_RLS() var counts = await SchemaQueries.CountEveryTableAsync(connection, transaction: null); - // ONE declared exception, and the sweep still enumerates the catalogue. It is not + // Declared platform reads, and the sweep still enumerates the catalogue. It is not // taught with a hand-written inclusion list of names: such a list fails open, which // is how a second permissive policy on outbox_messages once passed the whole suite. // What changes is the EXPECTATION, not the reach. - counts.Where(entry => entry.Key != KillswitchTable && !SchemaTableClasses.AppSelectDenied(entry.Key)) + counts.Where(entry => entry.Key != KillswitchTable && !SchemaTableClasses.IdentityPlatform.Contains(entry.Key) + && !SchemaTableClasses.AppSelectDenied(entry.Key)) .Should().OnlyContain(entry => entry.Value == 0, "with no app.tenant_id every policy predicate is NULL, which is false"); counts.Keys.Should().BeEquivalentTo(SchemaFixture.KnownTables); + counts["identity_authority"].Should().Be(1, "the immutable deployment anchor is an explicit platform read without person fields"); counts.Where(entry => SchemaTableClasses.AppSelectDenied(entry.Key)).Should() .OnlyContain(entry => entry.Value == SchemaTableClasses.SelectDenied, "vendor/control reads are real 42501 refusals, not silently omitted or counted as zero"); @@ -721,8 +723,24 @@ FROM pg_policies } guarded.Should().NotBeEmpty("the sweep must be reading the applied schema, not an empty result set"); + foreach (var proof in GlobalIdentitySchemaTests.WithCheckProofs.Values) + { + var method = typeof(GlobalIdentitySchemaTests).GetMethod(proof); + method.Should().NotBeNull(); + method!.GetCustomAttributes(typeof(FactAttribute), inherit: true).Should().NotBeEmpty( + "each non-tenant write predicate has an actual executable class-specific proof"); + } + foreach (var proof in IdentityMembershipTests.WithCheckProofs.Values) + { + var method = typeof(IdentityMembershipTests).GetMethod(proof); + method.Should().NotBeNull(); + method!.GetCustomAttributes(typeof(FactAttribute), inherit: true).Should().NotBeEmpty( + "contextual policies have class-specific clean/dirty controls independent of the lock guards"); + } guarded.Should().BeEquivalentTo( - ForeignTenantWrites.Keys.Concat(OwnerForeignTenantWrites.Keys), + ForeignTenantWrites.Keys.Concat(OwnerForeignTenantWrites.Keys) + .Concat(GlobalIdentitySchemaTests.WithCheckProofs.Keys) + .Concat(IdentityMembershipTests.WithCheckProofs.Keys), "every table whose policy constrains a write has a write that proves it, " + "and every case here names a table that still has one"); } @@ -1279,7 +1297,13 @@ AND grantee IN ('learnstack_app', 'learnstack_platform', 'learnstack_outbox_admi """); grants.Should().BeEquivalentTo( - ExistingTableGrants.Concat(BackgroundJobGrantExpectations.TableGrants), + ExistingTableGrants.Concat(BackgroundJobGrantExpectations.TableGrants) + .Concat(["learnstack_app identity_authority SELECT", "learnstack_app users SELECT", + "learnstack_app memberships INSERT,SELECT,UPDATE", + "learnstack_app membership_profiles INSERT,SELECT,UPDATE", + "learnstack_app roles INSERT,SELECT,UPDATE", + "learnstack_app membership_role_assignments DELETE,INSERT,SELECT", + "learnstack_app role_permission_grants 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/TenantAssertionAuditTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/TenantAssertionAuditTests.cs index 01f5ff690..8e0c1e722 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/TenantAssertionAuditTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/TenantAssertionAuditTests.cs @@ -57,7 +57,7 @@ public async Task An_authenticated_mismatch_lands_an_attributed_tenant_wide_row( NullLogger.Instance, MeterFactory, new AuditHealth(), - new AuditCatalog([]), StaticTenantContextAccessor.Unresolved); + new AuditCatalog([]), StaticTenantContextAccessor.Unresolved, new LearnStack.Infrastructure.Persistence.GlobalIdentityEnrollment()); var recorder = Recorder(store, threshold: 10); @@ -123,7 +123,7 @@ public async Task An_anonymous_burst_lands_one_row_however_long_the_run_is() NullLogger.Instance, MeterFactory, new AuditHealth(), - new AuditCatalog([]), StaticTenantContextAccessor.Unresolved); + new AuditCatalog([]), StaticTenantContextAccessor.Unresolved, new LearnStack.Infrastructure.Persistence.GlobalIdentityEnrollment()); var recorder = Recorder(store, threshold: 3); diff --git a/backend/tests/LearnStack.Tests.Integration/Database/TenantAuthenticationRejectionAuditTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/TenantAuthenticationRejectionAuditTests.cs index 0b2d2e1e3..be7646ce1 100644 --- a/backend/tests/LearnStack.Tests.Integration/Database/TenantAuthenticationRejectionAuditTests.cs +++ b/backend/tests/LearnStack.Tests.Integration/Database/TenantAuthenticationRejectionAuditTests.cs @@ -133,7 +133,7 @@ private static AuditingTenantAssertionRecorder Recorder(IServiceProvider service var store = new PostgresAuditStore(new AuditStateCapture(), dataSource, services.GetRequiredService>(), services.GetRequiredService(), health, catalog, - services.GetRequiredService()); + services.GetRequiredService(), new LearnStack.Infrastructure.Persistence.GlobalIdentityEnrollment()); return new AuditingTenantAssertionRecorder(services.GetRequiredService(), catalog, store, new TenantAssertionBurstDetector(Options.Create(new AssertionBurstOptions()), new SystemClock()), services.GetRequiredService(), diff --git a/backend/tests/LearnStack.Tests.Integration/Database/TenantExistingBindingAdmissionTests.Diagnostics.cs b/backend/tests/LearnStack.Tests.Integration/Database/TenantExistingBindingAdmissionTests.Diagnostics.cs new file mode 100644 index 000000000..ebb1b9a2b --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/TenantExistingBindingAdmissionTests.Diagnostics.cs @@ -0,0 +1,275 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Net; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.Modules.Tenancy.Infrastructure.Persistence; +using LearnStack.SharedKernel.Tenancy; +using LearnStack.Tools.Seeder; +using Microsoft.EntityFrameworkCore; +using LearnStack.SharedKernel.Identity; +using Microsoft.EntityFrameworkCore.Diagnostics; +using Microsoft.Extensions.DependencyInjection; +using Npgsql; +using OpenTelemetry; +using OpenTelemetry.Trace; +using Serilog.Core; +using Serilog.Events; +using Serilog.Formatting.Json; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class TenantExistingBindingAdmissionTests +{ + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Value_bearing_binding_read_failure_has_fixed_HTTP_diagnostics_and_recovers_with_exact_RLS_cleanup(bool transient) + { + var sqlState = transient ? PostgresErrorCodes.LockNotAvailable : "P0399"; + const string neutral = "binding-read-neutral-78e4"; + const string nested = "binding-read-nested-69f2"; + const string sensitive = "binding-read-sensitive-96a3"; + var payload = JsonSerializer.Serialize(new { value = neutral, items = new[] { new { value = nested, token = sensitive } } }); + var canaries = new[] { neutral, nested, sensitive }; + await using var issuer = await TenantAuthenticationIssuer.StartAsync(); + await using var database = await IdentityPublicReadFixture.CreateAsync(parent, issuer.Issuer, + new Dictionary { [Actor] = payload }); + var subject = new GlobalIdentitySubject(database.Registration.AuthorityId, issuer.Issuer, payload); + var observation = new BindingObservation(); + var logs = new ReadDiagnosticLogSink(); + var spans = new ReadDiagnosticExporter(); + using var source = new ReadFailureWitness(); + using var client = Client(database, observation, services => + { + services.AddSingleton(logs); + services.AddOpenTelemetry().WithTracing(tracing => tracing.AddProcessor(new SimpleActivityExportProcessor(spans))); + }); + var token = Token(issuer, subject: payload, includeActor: false); + using (var control = await SendAsync(client, token)) control.StatusCode.Should().Be(HttpStatusCode.OK); + (await ReadStoredSubjectAsync(database, subject)).Should().Be(payload); + var reads = database.Observation.Reads; + var originalPolicies = await ReadFaultShapeAsync(database); + originalPolicies.FunctionExists.Should().BeFalse(); + await ExecuteOwnerAsync(database, """ + CREATE FUNCTION public.identity_read_sink_fault(value text) RETURNS boolean LANGUAGE plpgsql AS $$ + BEGIN RAISE EXCEPTION USING ERRCODE='P0399', MESSAGE=value; END $$; + REVOKE ALL ON FUNCTION public.identity_read_sink_fault(text) FROM PUBLIC; + GRANT EXECUTE ON FUNCTION public.identity_read_sink_fault(text) TO learnstack_app; + CREATE POLICY identity_read_sink_fault ON public.users AS RESTRICTIVE FOR SELECT TO learnstack_app + USING(public.identity_read_sink_fault(provider_subject)); + """.Replace("P0399", sqlState, StringComparison.Ordinal)); + try + { + var dirty = await ReadFaultShapeAsync(database); + dirty.FunctionExists.Should().BeTrue(); + dirty.Policies.Should().NotBe(originalPolicies.Policies, + "the restoration comparison must detect the deliberately dirty fixture before cleanup"); + logs.Entries.Clear(); + spans.Items.Clear(); + using var efActivities = new IdentityDiagnosticSinks.EfActivityObserver(); + using var refused = await SendAsync(client, token, TenantAuthenticationHttpRequest.PublicPath); + await FixedUnauthorizedAsync(refused); + var response = await refused.Content.ReadAsStringAsync(); + source.Failure.Should().NotBeNull("the real application-role binding SELECT must reach the provider fault"); + source.Failure!.SqlState.Should().Be(sqlState); + source.Failure.MessageText.Should().Be(payload, + "the failing RLS function receives the actual retained provider subject, including neutral and nested values"); + source.Commands.Should().Be(1); + var serializedLogs = logs.Serialize(); + var exportedSpans = string.Join('\n', spans.Items.Select(span => span.Json)); + var efErrors = spans.Items.Where(span => span.Source == "OpenTelemetry.Instrumentation.EntityFrameworkCore" + && span.Status == ActivityStatusCode.Error).ToArray(); + efActivities.AssertCompleteCoverage(spans.Items.Where(span => span.Source == IdentityDiagnosticSinks.EfSource) + .Select(span => span.Id)); + efErrors.Should().NotBeEmpty().And.OnlyContain(span => span.Description == "Identity storage command failed."); + serializedLogs.Should().Contain("binding_store_unavailable").And.Contain("IdentityStorageReadFailed") + .And.NotContain("QueryIterationFailed").And.NotContain(sqlState).And.NotContain("Npgsql.PostgresException"); + logs.Entries.Where(entry => entry.MessageTemplate.Text == "Identity storage read failed.") + .Should().ContainSingle().Which.Exception.Should().BeNull(); + serializedLogs.Should().NotContain("L1 exception handler captured", + "the actual reader returns a uniform binding refusal, not a fabricated L1 exception path"); + output.WriteLine(JsonSerializer.Serialize(new + { + SourceReached = source.Failure.MessageText == payload, + HttpStatus = (int)refused.StatusCode, + QueryIterationEvent = serializedLogs.Contains("QueryIterationFailed", StringComparison.Ordinal), + LogContainsCanary = canaries.Any(serializedLogs.Contains), + TraceContainsCanary = canaries.Any(exportedSpans.Contains), + ResponseContainsCanary = canaries.Any(response.Contains), + ExportedSpans = spans.Items.Count, + IdentityErrorSpans = efErrors.Length, + })); + foreach (var canary in canaries) + { + serializedLogs.Should().NotContain(canary); + exportedSpans.Should().NotContain(canary); + response.Should().NotContain(canary); + } + database.Observation.Reads.Should().Be(reads, "the refused binding never reaches the tenant reader"); + } + finally + { + await ExecuteOwnerAsync(database, """ + DROP POLICY identity_read_sink_fault ON public.users; + DROP FUNCTION public.identity_read_sink_fault(text); + """); + } + (await ReadFaultShapeAsync(database)).Should().Be(originalPolicies, + "the exact policy inventory is restored and the case-owned function is gone"); + (await ReadStoredSubjectAsync(database, subject)).Should().Be(payload); + using var restored = await SendAsync(client, token); + restored.StatusCode.Should().Be(HttpStatusCode.OK); + observation.Lookups.Should().Be(3); + observation.ClosedOwners.Should().Be(3); + } + + [Fact] + public async Task Sibling_query_failure_preserves_its_existing_EF_iteration_event_and_span_description() + { + using var sinks = new IdentityDiagnosticSinks(); + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(parent.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using var transaction = await app.BeginTransactionAsync(); + await SchemaQueries.SetTenantAsync(app, transaction, SeedData.English.TenantId.Value); + await using var db = new TenancyDbContext(new DbContextOptionsBuilder() + .UseNpgsql(app).UseLoggerFactory(sinks.Loggers).Options, + new StaticTenantContextAccessor(new SeedTenantContext(SeedData.English.TenantId, null))); + await db.Database.UseTransactionAsync(transaction); + var query = () => db.Database.SqlQueryRaw("SELECT CAST('sibling-query-control' AS integer) AS \"Value\"").SingleAsync(); + var failure = (await query.Should().ThrowAsync()).Which; + sinks.LogText.Should().Contain("QueryIterationFailed").And.NotContain("IdentityStorageReadFailed"); + sinks.AssertCompleteEfTraceCoverage(); + sinks.Traces.Where(trace => trace.Source == "OpenTelemetry.Instrumentation.EntityFrameworkCore" + && trace.Status == ActivityStatusCode.Error).Should().NotBeEmpty() + .And.OnlyContain(trace => trace.Description == failure.Message); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Identity_FromSql_failures_keep_a_fixed_read_signal_for_sync_and_async_commands(bool asynchronous) + { + const string value = "identity-fromsql-read-canary-4791"; + using var sinks = new IdentityDiagnosticSinks(); + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(parent.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using var transaction = await app.BeginTransactionAsync(); + await SchemaQueries.SetTenantAsync(app, transaction, SeedData.English.TenantId.Value); + await using var db = new IdentityDbContext(new DbContextOptionsBuilder() + .UseNpgsql(app).UseLoggerFactory(sinks.Loggers).Options, + new StaticTenantContextAccessor(new SeedTenantContext(SeedData.English.TenantId, null)), EmptyIdentityScope.Instance); + await db.Database.UseTransactionAsync(transaction); + var query = db.Database.SqlQuery($"SELECT CAST({value} AS integer) AS \"Value\""); + PostgresException failure; + if (asynchronous) + { + var read = () => query.SingleAsync(); + failure = (await read.Should().ThrowAsync()).Which; + } + else + { + var read = () => query.Single(); + failure = read.Should().Throw().Which; + } + failure.MessageText.Should().Contain(value, "the actual provider received the parameter in both execution modes"); + sinks.LogText.Should().Contain("IdentityStorageReadFailed").And.Contain("3192") + .And.NotContain("QueryIterationFailed").And.NotContain(value); + sinks.AssertCompleteEfTraceCoverage(); + sinks.Traces.Where(trace => trace.Source == "OpenTelemetry.Instrumentation.EntityFrameworkCore" + && trace.Status == ActivityStatusCode.Error).Should().NotBeEmpty() + .And.OnlyContain(trace => trace.Description == "Identity storage command failed."); + foreach (var trace in sinks.Traces) trace.Json.Should().NotContain(value); + } + + private static async Task ReadStoredSubjectAsync(IdentityPublicReadFixture database, GlobalIdentitySubject subject) + { + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await SchemaQueries.AssertApplicationRoleAsync(app); + await using var transaction = await app.BeginTransactionAsync(); + await AnnounceAsync(app, transaction, subject); + await using var command = new NpgsqlCommand("SELECT provider_subject FROM public.users WHERE id=@actor", app, transaction); + command.Parameters.AddWithValue("actor", Actor.Value); + return (string?)await command.ExecuteScalarAsync(); + } + + private static async Task<(string Policies, bool FunctionExists)> ReadFaultShapeAsync(IdentityPublicReadFixture database) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString); + await using var command = new NpgsqlCommand(""" + SELECT COALESCE(jsonb_agg(jsonb_build_object('name',polname,'permissive',polpermissive, + 'command',polcmd,'roles',polroles::text,'using',pg_get_expr(polqual,polrelid), + 'check',pg_get_expr(polwithcheck,polrelid)) ORDER BY polname),'[]'::jsonb)::text, + to_regprocedure('public.identity_read_sink_fault(text)') IS NOT NULL + FROM pg_policy WHERE polrelid='public.users'::regclass + """, owner); + await using var row = await command.ExecuteReaderAsync(); + (await row.ReadAsync()).Should().BeTrue(); + return (row.GetString(0), row.GetBoolean(1)); + } + + private sealed class ReadDiagnosticLogSink : ILogEventSink + { + internal ConcurrentQueue Entries { get; } = new(); + public void Emit(LogEvent logEvent) => Entries.Enqueue(logEvent); + internal string Serialize() + { + using var writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); + var formatter = new JsonFormatter(renderMessage: true, formatProvider: System.Globalization.CultureInfo.InvariantCulture); + foreach (var entry in Entries) formatter.Format(entry, writer); + return writer.ToString(); + } + } + + private sealed record ReadSpan(string Id, string Source, ActivityStatusCode Status, string? Description, string Json); + private sealed class ReadDiagnosticExporter : BaseExporter + { + internal ConcurrentQueue Items { get; } = new(); + public override ExportResult Export(in Batch batch) + { + foreach (var activity in batch) + Items.Enqueue(new(activity.Id!, activity.Source.Name, activity.Status, activity.StatusDescription, JsonSerializer.Serialize(new + { + activity.DisplayName, + activity.Id, + activity.ParentId, + activity.StatusDescription, + Status = activity.Status.ToString(), + Tags = activity.TagObjects.ToArray(), + Events = activity.Events.Select(item => new { item.Name, Tags = item.Tags.ToArray() }).ToArray(), + }))); + return ExportResult.Success; + } + } + + private sealed class ReadFailureWitness : IObserver, IObserver>, IDisposable + { + private readonly IDisposable _all; + private readonly List _subscriptions = []; + internal PostgresException? Failure { get; private set; } + internal int Commands { get; private set; } + internal ReadFailureWitness() => _all = DiagnosticListener.AllListeners.Subscribe(this); + public void OnNext(DiagnosticListener listener) + { + if (listener.Name == "Microsoft.EntityFrameworkCore") _subscriptions.Add(listener.Subscribe(this)); + } + public void OnNext(KeyValuePair value) + { + if (value.Key == "Microsoft.EntityFrameworkCore.Database.Command.CommandError" + && value.Value is CommandErrorEventData { Context: IdentityDbContext, Exception: PostgresException failure }) + { + Failure = failure; + Commands++; + } + } + public void OnError(Exception error) { } + public void OnCompleted() { } + public void Dispose() + { + _all.Dispose(); + foreach (var subscription in _subscriptions) subscription.Dispose(); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/TenantExistingBindingAdmissionTests.Observation.cs b/backend/tests/LearnStack.Tests.Integration/Database/TenantExistingBindingAdmissionTests.Observation.cs new file mode 100644 index 000000000..85eec1e12 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/TenantExistingBindingAdmissionTests.Observation.cs @@ -0,0 +1,291 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using FluentAssertions; +using LearnStack.Modules.Identity.Application.Abstractions; +using LearnStack.Modules.Identity.Application.Contracts.Bindings; +using LearnStack.Modules.Identity.Domain; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.Modules.Identity.Infrastructure.Persistence; +using LearnStack.SharedKernel.Audit; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.SharedKernel.Persistence; +using LearnStack.SharedKernel.Tenancy; +using Microsoft.EntityFrameworkCore.Diagnostics; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Npgsql; +using Serilog.Core; +using Serilog.Events; +using Serilog.Formatting.Json; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class TenantExistingBindingAdmissionTests +{ + private static void ObserveBindings(IServiceCollection services, BindingObservation observation) + { + services.AddSingleton(observation); + services.AddScoped(); + services.Replace(ServiceDescriptor.Scoped()); + services.Replace(ServiceDescriptor.Scoped()); + } + + private sealed class BindingObservation + { + private int _lookups; + private int _closed; + internal int Lookups => Volatile.Read(ref _lookups); + internal int ClosedOwners => Volatile.Read(ref _closed); + internal ConcurrentQueue BackendIds { get; } = new(); + internal Func? BeforeRead { get; set; } + internal Func? AfterRead { get; set; } + internal void Enter(int backend) + { + Interlocked.Increment(ref _lookups); + BackendIds.Enqueue(backend); + } + internal void Closed() => Interlocked.Increment(ref _closed); + } + + /// Observes the exact common owner, then delegates every read to the production store. + private sealed class ObservedBindingStore(UserBindingStore inner, IGlobalIdentityUnitOfWork unit, + ITenantContextAccessor tenant, BindingObservation observation) : IUserBindingStore + { + public async Task FindExactAsync(GlobalIdentitySubject subject, CancellationToken cancellationToken = default) + { + unit.Mode.Should().Be(TransactionMode.ReadOnly); + unit.IsGlobalIdentityTransaction.Should().BeTrue(); + (tenant.Current?.IsResolved ?? false).Should().BeFalse(); + unit.GetGlobalIdentityAnnouncement(unit.Transaction)!.Descriptor.Subject.Should().BeSameAs(subject); + await using (var command = new NpgsqlCommand(""" + SELECT current_user,rolsuper,rolbypassrls,current_setting('transaction_read_only'), + current_setting('app.identity_authority_id',true),current_setting('app.identity_subject_key',true), + COALESCE(current_setting('app.tenant_id',true),''),COALESCE(current_setting('app.organization_id',true),''), + pg_backend_pid() + FROM pg_roles WHERE rolname=current_user + """, (NpgsqlConnection)unit.Connection, (NpgsqlTransaction?)unit.Transaction)) + await using (var proof = await command.ExecuteReaderAsync(cancellationToken)) + { + (await proof.ReadAsync(cancellationToken)).Should().BeTrue(); + proof.GetString(0).Should().Be("learnstack_app"); + proof.GetBoolean(1).Should().BeFalse(); + proof.GetBoolean(2).Should().BeFalse(); + proof.GetString(3).Should().Be("on"); + (proof.GetString(4) == subject.AuthorityId.Value.ToString("D")).Should().BeTrue(); + (proof.GetString(5) == subject.SubjectKey.Hex).Should().BeTrue(); + proof.GetString(6).Should().BeEmpty(); + proof.GetString(7).Should().BeEmpty(); + observation.Enter(proof.GetInt32(8)); + } + if (observation.BeforeRead is { } before) await before(cancellationToken); + return await inner.FindExactAsync(subject, cancellationToken); + } + + public Task AddAsync(User user, CancellationToken cancellationToken = default) => inner.AddAsync(user, cancellationToken); + } + + /// The production reader has finished cleanup before its result reaches the API binding stage. + private sealed class ObservedBindingReader(GlobalIdentityBindingService inner, IGlobalIdentityUnitOfWork unit, + IGlobalIdentityScopeAccessor identity, ITenantContextAccessor tenant, IAuditStateCapture capture, + BindingObservation observation) : IIdentityBindingReader + { + public async Task ResolveExistingAsync(GlobalIdentitySubject subject, + UserId? claimedActor = null, CancellationToken cancellationToken = default) + { + try { return await inner.ResolveExistingAsync(subject, claimedActor, cancellationToken); } + finally + { + unit.HasActiveTransaction.Should().BeFalse(); + unit.IsGlobalIdentityTransaction.Should().BeFalse(); + identity.Current.Should().BeNull(); + (tenant.Current?.IsResolved ?? false).Should().BeFalse(); + capture.Intents.Should().BeEmpty(); + capture.Changes.Should().BeEmpty(); + capture.HasOpenFrame.Should().BeFalse(); + observation.Closed(); + if (observation.AfterRead is { } after) await after(cancellationToken); + } + } + } + + private sealed class BindingLogSink : ILogEventSink + { + private readonly ConcurrentQueue _entries = new(); + public void Emit(LogEvent logEvent) => _entries.Enqueue(logEvent); + internal void BeginFaultWindow() => _entries.Clear(); + internal void AssertUnavailable(params string[] privateValues) + { + var closed = _entries.Where(entry => entry.MessageTemplate.Text == "Tenant authentication stage {Stage} outcome {Reason}." + && entry.Properties.TryGetValue("Reason", out var reason) + && reason is ScalarValue { Value: "binding_store_unavailable" }).ToArray(); + closed.Should().ContainSingle(); + closed[0].Exception.Should().BeNull(); + closed[0].Properties["Stage"].Should().BeOfType().Which.Value.Should().Be("binding"); + using var serialized = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); + var formatter = new JsonFormatter(renderMessage: true, formatProvider: System.Globalization.CultureInfo.InvariantCulture); + foreach (var entry in _entries) formatter.Format(entry, serialized); + var exported = serialized.ToString(); + foreach (var privateValue in privateValues) + exported.Contains(privateValue, StringComparison.Ordinal).Should().BeFalse( + "the fault-window exported events, including structured properties and exceptions, must contain no provider subject, bearer or application actor"); + } + } + + private static async Task<(long Users, long Audits)> CountsAsync(IdentityPublicReadFixture database) + { + var subject = new GlobalIdentitySubject(database.Registration.AuthorityId, database.Registration.Issuer, Subject); + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString); + await using var transaction = await owner.BeginTransactionAsync(); + await AnnounceAsync(owner, transaction, subject); + await using var command = new NpgsqlCommand(""" + SELECT (SELECT count(*) FROM public.users), + (SELECT count(*) FROM public.audit_log WHERE operation='identity.user.create' + AND metadata->>'identity_subject_key'=@key) + """, owner, transaction); + command.Parameters.AddWithValue("key", subject.SubjectKey.Hex); + await using var rows = await command.ExecuteReaderAsync(); + (await rows.ReadAsync()).Should().BeTrue(); + return (rows.GetInt64(0), rows.GetInt64(1)); + } + + private static async Task AnnounceAsync(NpgsqlConnection connection, NpgsqlTransaction transaction, GlobalIdentitySubject subject) + { + await using var announce = new NpgsqlCommand(""" + SELECT set_config('app.identity_authority_id',@authority,true),set_config('app.identity_subject_key',@key,true) + """, connection, transaction); + announce.Parameters.AddWithValue("authority", subject.AuthorityId.Value.ToString("D")); + announce.Parameters.AddWithValue("key", subject.SubjectKey.Hex); + await announce.ExecuteNonQueryAsync(); + } + + private static async Task ExecuteOwnerAsync(IdentityPublicReadFixture database, string sql) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString); + await using var command = new NpgsqlCommand(sql, owner); + await command.ExecuteNonQueryAsync(); + } + + private static async Task SetBindingStateAsync(IdentityPublicReadFixture database, string state, + string? subjectDigestDefinition = null) + { + 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 + // 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. + await using (var setup = new NpgsqlCommand(""" + CREATE POLICY fixture_binding_update ON public.users FOR UPDATE TO learnstack_migration USING(true) WITH CHECK(true); + ALTER TABLE public.users DISABLE TRIGGER tg_users_no_update; + """, owner, transaction)) await setup.ExecuteNonQueryAsync(); + if (state == "Collision") + { + await AssertDigestRejectsMismatchAsync(owner, transaction); + await using var definition = new NpgsqlCommand(""" + SELECT pg_get_constraintdef(oid) FROM pg_constraint + WHERE conrelid='public.users'::regclass AND conname='ck_users_subject_digest' AND convalidated + """, owner, transaction); + subjectDigestDefinition = (string?)await definition.ExecuteScalarAsync(); + subjectDigestDefinition.Should().NotBeNullOrWhiteSpace(); + await using var remove = new NpgsqlCommand("ALTER TABLE public.users DROP CONSTRAINT ck_users_subject_digest", owner, transaction); + await remove.ExecuteNonQueryAsync(); + } + await using (var update = new NpgsqlCommand(""" + UPDATE public.users SET status=@status,provider_subject=@subject WHERE id=@actor + """, owner, transaction)) + { + update.Parameters.AddWithValue("status", state == "Collision" ? "Active" : state); + update.Parameters.AddWithValue("subject", state == "Closed" ? DBNull.Value + : state == "Collision" ? "different-retained-subject-canary" : Subject); + update.Parameters.AddWithValue("actor", Actor.Value); + (await update.ExecuteNonQueryAsync()).Should().Be(1); + } + if (state == "Active" && subjectDigestDefinition is not null) + { + // The definition came from this database's exact named catalog row, + // never caller input or a copied canonical CHECK expression. + await using var restoreDigest = new NpgsqlCommand("ALTER TABLE public.users ADD CONSTRAINT ck_users_subject_digest " + + subjectDigestDefinition, owner, transaction); + await restoreDigest.ExecuteNonQueryAsync(); + await AssertDigestRejectsMismatchAsync(owner, transaction); + } + await using (var restore = new NpgsqlCommand(""" + ALTER TABLE public.users ENABLE TRIGGER tg_users_no_update; + DROP POLICY fixture_binding_update ON public.users; + """, owner, transaction)) await restore.ExecuteNonQueryAsync(); + await transaction.CommitAsync(); + return subjectDigestDefinition; + } + + private static async Task AssertDigestRejectsMismatchAsync(NpgsqlConnection owner, NpgsqlTransaction transaction) + { + await using (var savepoint = new NpgsqlCommand("SAVEPOINT fixture_digest_control", owner, transaction)) + await savepoint.ExecuteNonQueryAsync(); + await using var invalid = new NpgsqlCommand("UPDATE public.users SET provider_subject=@mismatch WHERE id=@actor", owner, transaction); + invalid.Parameters.AddWithValue("mismatch", "different-retained-subject-canary"); + invalid.Parameters.AddWithValue("actor", Actor.Value); + var failure = await FluentActions.Awaiting(async () => { await invalid.ExecuteNonQueryAsync(); }) + .Should().ThrowAsync(); + failure.Which.SqlState.Should().Be(PostgresErrorCodes.CheckViolation); + failure.Which.ConstraintName.Should().Be("ck_users_subject_digest"); + await using var rollback = new NpgsqlCommand("ROLLBACK TO SAVEPOINT fixture_digest_control", owner, transaction); + await rollback.ExecuteNonQueryAsync(); + } + + private static async Task AssertBindingGuardsRestoredAsync(IdentityPublicReadFixture database, string? subjectDigestDefinition) + { + await using var owner = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString); + await using var check = new NpgsqlCommand(""" + SELECT (SELECT tgenabled::text FROM pg_trigger WHERE tgrelid='public.users'::regclass AND tgname='tg_users_no_update'), + NOT EXISTS(SELECT 1 FROM pg_policy WHERE polrelid='public.users'::regclass AND polname='fixture_binding_update'), + NOT has_table_privilege('learnstack_app','public.users','UPDATE'), + (SELECT convalidated FROM pg_constraint WHERE conrelid='public.users'::regclass AND conname='ck_users_subject_digest'), + (SELECT pg_get_constraintdef(oid) FROM pg_constraint WHERE conrelid='public.users'::regclass AND conname='ck_users_subject_digest') + """, owner); + await using var row = await check.ExecuteReaderAsync(); + (await row.ReadAsync()).Should().BeTrue(); + row.GetString(0).Should().Be("O"); + row.GetBoolean(1).Should().BeTrue(); + row.GetBoolean(2).Should().BeTrue(); + row.GetBoolean(3).Should().BeTrue(); + if (subjectDigestDefinition is not null) row.GetString(4).Should().Be(subjectDigestDefinition); + } + + /// Copies the actual EF command solely for a later parameterized EXPLAIN; never emits SQL or values. + private sealed class BindingCommandObservation : IObserver, IObserver>, IDisposable + { + private readonly IDisposable _all; + private readonly List _subscriptions = []; + private int _commands; + internal int Commands => Volatile.Read(ref _commands); + internal string? Sql { get; private set; } + internal NpgsqlParameter[] Parameters { get; private set; } = []; + internal BindingCommandObservation() => _all = DiagnosticListener.AllListeners.Subscribe(this); + public void OnNext(DiagnosticListener listener) + { + if (listener.Name == "Microsoft.EntityFrameworkCore") + _subscriptions.Add(listener.Subscribe(this)); + } + public void OnNext(KeyValuePair value) + { + if (value.Key != "Microsoft.EntityFrameworkCore.Database.Command.CommandExecuting" + || value.Value is not CommandEventData { Context: IdentityDbContext } data) return; + Interlocked.Increment(ref _commands); + lock (_subscriptions) + { + Sql ??= data.Command.CommandText; + if (Parameters.Length == 0) + Parameters = data.Command.Parameters.Cast().Select(parameter => + new NpgsqlParameter(parameter.ParameterName, parameter.NpgsqlDbType) { Value = parameter.Value }).ToArray(); + } + } + public void OnError(Exception error) { } + public void OnCompleted() { } + public void Dispose() + { + _all.Dispose(); + foreach (var subscription in _subscriptions) subscription.Dispose(); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/TenantExistingBindingAdmissionTests.Resources.cs b/backend/tests/LearnStack.Tests.Integration/Database/TenantExistingBindingAdmissionTests.Resources.cs new file mode 100644 index 000000000..80086c384 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/TenantExistingBindingAdmissionTests.Resources.cs @@ -0,0 +1,352 @@ +using System.Diagnostics; +using System.Net; +using System.Net.Http.Headers; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Api.Authentication; +using LearnStack.Infrastructure.Persistence; +using LearnStack.Modules.Identity.Application.Contracts.Bindings; +using LearnStack.Modules.Identity.Infrastructure.Bindings; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.SharedKernel.Identity; +using LearnStack.Tools.Seeder; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Npgsql; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class TenantExistingBindingAdmissionTests +{ + [Fact] + public async Task Completed_binding_returns_the_connector_before_its_HTTP_scope_dispatches_tenant_work() + { + await using var issuer = await TenantAuthenticationIssuer.StartAsync(); + await using var database = await DatabaseAsync(issuer); + var application = "binding-dispatch-" + Guid.NewGuid().ToString("N"); + await using var source = ApplicationDataSource.Build(PoolConnection(database, application, maximum: 1)); + var observation = new BindingObservation(); + using var client = Client(database, observation, services => UseSource(services, source)); + var token = Token(issuer, includeActor: false); + using (var warm = await SendAsync(client, token)) warm.StatusCode.Should().Be(HttpStatusCode.OK); + var backend = observation.BackendIds.Last(); + var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var reads = 0; + observation.AfterRead = async cancellationToken => + { + if (Interlocked.Increment(ref reads) != 1) return; + entered.TrySetResult(); + await release.Task.WaitAsync(cancellationToken); + }; + var heldRequest = SendAsync(client, token); + try + { + await entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); + // The first request still owns its DI scope but has completed only + // the global read. A second real binding and tenant read must fit + // through the one-slot pool without releasing the first request. + using var concurrent = await SendAsync(client, token).WaitAsync(TimeSpan.FromSeconds(10)); + concurrent.StatusCode.Should().Be(HttpStatusCode.OK); + heldRequest.IsCompleted.Should().BeFalse(); + observation.BackendIds.Last().Should().Be(backend); + } + finally { release.TrySetResult(); } + using var completed = await heldRequest.WaitAsync(TimeSpan.FromSeconds(10)); + completed.StatusCode.Should().Be(HttpStatusCode.OK, "the original scoped unit must reopen for its tenant owner"); + observation.ClosedOwners.Should().Be(3); + await WaitForPoolAsync(database, application, state => state.InTransactions == 0 && state.Active == 0); + } + + [Fact] + public async Task Small_real_HTTP_sample_reports_lookup_plan_statement_cost_and_bounded_concurrent_pool_occupancy() + { + await using var issuer = await TenantAuthenticationIssuer.StartAsync(); + await using var database = await DatabaseAsync(issuer); + // These are actual globally audited bindings, not rows inserted around the + // permanent creation/audit guards. This is a bounded local sample only. + const int population = 32; + for (var index = 1; index < population; index++) + await database.AdoptAsync(UserId.From(Guid.CreateVersion7()), "sample-subject-" + index); + await ExecuteOwnerAsync(database, "ANALYZE public.users"); + var application = "binding-sample-" + Guid.NewGuid().ToString("N"); + using var statements = new BindingStatementCounter(); + using var loggers = LoggerFactory.Create(builder => builder.SetMinimumLevel(LogLevel.Trace).AddProvider(statements)); + await using var source = ApplicationDataSource.Build(PoolConnection(database, application, maximum: 4), loggers); + var expected = new VerifiedProviderSubject(issuer.Issuer, Subject, null, SeedData.English.TenantId, null); + var counterfactual = await WitnessCounterfactualAsync(database, source, expected); + var controlApplication = "binding-control-" + Guid.NewGuid().ToString("N"); + using var controlStatements = new BindingStatementCounter(); + using var controlLoggers = LoggerFactory.Create(builder => builder.SetMinimumLevel(LogLevel.Trace).AddProvider(controlStatements)); + await using var controlSource = ApplicationDataSource.Build(PoolConnection(database, controlApplication, maximum: 4), controlLoggers); + var observation = new BindingObservation(); + var controlObservation = new BindingObservation(); + using var commands = new BindingCommandObservation(); + using var client = Client(database, observation, services => UseSource(services, source)); + using var controlClient = Client(database, controlObservation, services => + { + UseSource(services, controlSource); + services.Replace(ServiceDescriptor.Singleton(counterfactual)); + }); + var token = Token(issuer, includeActor: false); + using (var warm = await SendAsync(client, token, TenantAuthenticationHttpRequest.PublicPath)) + warm.StatusCode.Should().Be(HttpStatusCode.OK); + using (var warm = await SendAsync(controlClient, token, TenantAuthenticationHttpRequest.PublicPath)) + warm.StatusCode.Should().Be(HttpStatusCode.OK); + + const int samples = 12; + var anonymous = new List(); + var control = new List(); + var bound = new List(); + var before = statements.Statements; + var beforeBindings = commands.Commands; + for (var index = 0; index < samples; index++) + anonymous.Add(await TimedReadAsync(client, null)); + var anonymousStatements = statements.Statements - before; + commands.Commands.Should().Be(beforeBindings, "the anonymous comparison performs no global lookup"); + before = statements.Statements; + var beforeControlStatements = controlStatements.Statements; + var beforeControlCalls = counterfactual.Calls; + for (var index = 0; index < samples; index++) + { + // Alternate order to reduce a simple first/last-lane bias. Both + // requests carry the same compact token and traverse stock validation, + // subject quota and the same real public tenant reader. + if (index % 2 == 0) control.Add(await TimedReadAsync(controlClient, token)); + bound.Add(await TimedReadAsync(client, token)); + if (index % 2 != 0) control.Add(await TimedReadAsync(controlClient, token)); + } + var boundStatements = statements.Statements - before; + var counterfactualStatements = controlStatements.Statements - beforeControlStatements; + (commands.Commands - beforeBindings).Should().Be(samples, "every authenticated sample reads committed binding state once"); + (counterfactual.Calls - beforeControlCalls).Should().Be(samples); + controlObservation.Lookups.Should().Be(0, "the current-code counterfactual omits only the binding resolver's database read"); + await WaitForPoolAsync(database, controlApplication, state => state.InTransactions == 0 && state.Active == 0); + + var held = 0; + var allOccupied = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + observation.BeforeRead = async cancellationToken => + { + if (Interlocked.Increment(ref held) == 4) allOccupied.TrySetResult(); + await release.Task.WaitAsync(cancellationToken); + }; + var concurrent = Enumerable.Range(0, 8).Select(_ => TimedReadAsync(client, token)).ToArray(); + PoolObservation peak; + try + { + await allOccupied.Task.WaitAsync(TimeSpan.FromSeconds(10)); + peak = await PoolAsync(database, application); + peak.Connections.Should().Be(4); + peak.InTransactions.Should().Be(4, "four real global owners occupy the four-connection source while other callers await checkout"); + concurrent.Count(task => !task.IsCompleted).Should().Be(8); + } + finally { release.TrySetResult(); } + await Task.WhenAll(concurrent).WaitAsync(TimeSpan.FromSeconds(15)); + observation.BeforeRead = null; + await WaitForPoolAsync(database, application, state => state.InTransactions == 0 && state.Active == 0); + var plan = await ExplainActualLookupAsync(database, commands); + observation.ClosedOwners.Should().Be(observation.Lookups); + + output.WriteLine("Local observational sample. The authenticated current-code counterfactual returns one previously witnessed Existing binding for the exact verified input; it is neither a historical nor a security-qualified baseline. No production percentile guarantee."); + output.WriteLine("Bindings={0}; same authenticated public GET samples per lane={1}, interleaved after warmup; counterfactual median/range ms={2:F2}/{3:F2}-{4:F2}; production binding median/range ms={5:F2}/{6:F2}-{7:F2}; median difference ms={8:F2}.", + population, samples, Median(control), control.Min(), control.Max(), Median(bound), bound.Min(), bound.Max(), Median(bound) - Median(control)); + output.WriteLine("Anonymous contextual comparison median/range ms={0:F2}/{1:F2}-{2:F2}; driver SQL statements anonymous/counterfactual/production={3}/{4}/{5}; actual production binding SELECTs={6}; counterfactual binding SELECTs=0; observer adds one role/GUC proof SELECT per production lookup.", + Median(anonymous), anonymous.Min(), anonymous.Max(), anonymousStatements, counterfactualStatements, boundStatements, samples); + output.WriteLine("Default planner nodes={0}; actual rows={1}; planning/execution ms={2:F3}/{3:F3}; concurrent HTTP=8; pool maximum/observed occupied=4/{4}; remaining active/transaction owners=0.", + plan.Nodes, plan.Rows, plan.PlanningMilliseconds, plan.ExecutionMilliseconds, peak.InTransactions); + } + + [Fact] + public async Task Real_blocked_lookup_cancellation_releases_the_owner_and_reuses_one_clean_physical_connector() + { + await using var issuer = await TenantAuthenticationIssuer.StartAsync(); + await using var database = await DatabaseAsync(issuer); + var application = "binding-cancellation-" + Guid.NewGuid().ToString("N"); + await using var source = ApplicationDataSource.Build(PoolConnection(database, application, maximum: 1)); + var observation = new BindingObservation(); + using var client = Client(database, observation, services => UseSource(services, source)); + var token = Token(issuer, includeActor: false); + using (var warm = await SendAsync(client, token)) warm.StatusCode.Should().Be(HttpStatusCode.OK); + var originalBackend = observation.BackendIds.Last(); + var counts = await CountsAsync(database); + await using var blocker = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.MigrationConnectionString); + await using var held = await blocker.BeginTransactionAsync(); + await using (var command = new NpgsqlCommand("LOCK TABLE public.users IN ACCESS EXCLUSIVE MODE", blocker, held)) + await command.ExecuteNonQueryAsync(); + using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(12)); + using var request = new HttpRequestMessage(HttpMethod.Get, TenantAuthenticationHttpRequest.AccountPath); + request.Headers.Host = SeedData.English.Host; + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + var blocked = client.SendAsync(request, cancellation.Token); + try + { + await WaitForPoolAsync(database, application, state => state.LockWaiters == 1); + blocked.IsCompleted.Should().BeFalse("the real users SELECT must be blocked before cancellation is issued"); + cancellation.Cancel(); + await Assert.ThrowsAnyAsync(() => blocked); + // Keep the real blocker held: only cancellation/cleanup can free this + // owner. Releasing the lock first would make the proof vacuous. + await WaitForPoolAsync(database, application, state => state.LockWaiters == 0 && state.InTransactions == 0 && state.Active == 0); + } + finally { await held.RollbackAsync(); } + + await using (var reused = await source.OpenConnectionAsync()) + await using (var transaction = await reused.BeginTransactionAsync()) + await using (var proof = new NpgsqlCommand(""" + SELECT pg_backend_pid(),current_setting('transaction_read_only'), + COALESCE(current_setting('app.identity_authority_id',true),''), + COALESCE(current_setting('app.identity_subject_key',true),''), + COALESCE(current_setting('app.tenant_id',true),''),COALESCE(current_setting('app.organization_id',true),'') + """, reused, transaction)) + await using (var row = await proof.ExecuteReaderAsync()) + { + (await row.ReadAsync()).Should().BeTrue(); + row.GetInt32(0).Should().Be(originalBackend, "ordinary cancellation must return the same connector cleanly to the one-slot pool"); + row.GetString(1).Should().Be("off"); + for (var field = 2; field < 6; field++) row.GetString(field).Should().BeEmpty(); + } + using var restored = await SendAsync(client, token); + restored.StatusCode.Should().Be(HttpStatusCode.OK); + observation.ClosedOwners.Should().Be(3); + (await CountsAsync(database)).Should().Be(counts); + output.WriteLine("One-slot real pool: observed blocked users SELECT, cancelled while blocker remained held, zero surviving transaction/lock owners, same physical connector reused with cleared identity/tenant GUCs."); + } + + private static string PoolConnection(IdentityPublicReadFixture database, string application, int maximum) => + new NpgsqlConnectionStringBuilder(database.AppConnectionString) + { + Pooling = true, + MaxPoolSize = maximum, + MinPoolSize = 0, + Timeout = 10, + CommandTimeout = 10, + ApplicationName = application, + }.ConnectionString; + + private static void UseSource(IServiceCollection services, NpgsqlDataSource source) => + services.Replace(ServiceDescriptor.Singleton(new Lazy(() => source))); + + private static async Task WitnessCounterfactualAsync( + IdentityPublicReadFixture database, NpgsqlDataSource source, VerifiedProviderSubject expected) + { + await using var provider = SeedComposition.Build(source, null, NullLoggerFactory.Instance, + identityAuthority: database.Registration); + await provider.GetRequiredService().QualifyAsync(); + await using var scope = provider.CreateAsyncScope(); + var witnessed = await scope.ServiceProvider.GetRequiredService().ResolveExistingAsync( + new GlobalIdentitySubject(database.Registration.AuthorityId, expected.Issuer, expected.Subject), expected.ClaimedActor); + witnessed.Outcome.Should().Be(IdentityBindingOutcome.Existing); + witnessed.Actor.Should().Be(Actor); + return new(expected, witnessed); + } + + private static async Task TimedReadAsync(HttpClient client, string? token) + { + var started = Stopwatch.GetTimestamp(); + using var response = await SendAsync(client, token, TenantAuthenticationHttpRequest.PublicPath); + response.StatusCode.Should().Be(HttpStatusCode.OK); + await response.Content.ReadAsByteArrayAsync(); + return Stopwatch.GetElapsedTime(started).TotalMilliseconds; + } + + private static double Median(List observations) + { + var ordered = observations.Order().ToArray(); + return (ordered[(ordered.Length - 1) / 2] + ordered[ordered.Length / 2]) / 2; + } + + private static async Task PoolAsync(IdentityPublicReadFixture database, string application) + { + // Same login as the observed source, so pg_stat_activity exposes actual + // state without granting fixture-only pg_monitor or privileged app roles. + await using var observer = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await using var query = new NpgsqlCommand(""" + SELECT count(*)::integer,count(*) FILTER(WHERE state='active')::integer, + count(*) FILTER(WHERE xact_start IS NOT NULL)::integer, + count(*) FILTER(WHERE wait_event_type='Lock' AND query LIKE '%users%')::integer + FROM pg_stat_activity WHERE datname=current_database() AND usename=current_user AND application_name=@application + """, observer); + query.Parameters.AddWithValue("application", application); + await using var row = await query.ExecuteReaderAsync(); + (await row.ReadAsync()).Should().BeTrue(); + return new(row.GetInt32(0), row.GetInt32(1), row.GetInt32(2), row.GetInt32(3)); + } + + private static async Task WaitForPoolAsync(IdentityPublicReadFixture database, string application, + Func predicate) + { + using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(8)); + while (!predicate(await PoolAsync(database, application))) await Task.Delay(15, deadline.Token); + } + + private static async Task ExplainActualLookupAsync(IdentityPublicReadFixture database, + BindingCommandObservation observation) + { + observation.Sql.Should().NotBeNullOrWhiteSpace("a real production EF binding SELECT must have executed"); + await using var app = (NpgsqlConnection)await PostgresFixture.OpenAsync(database.AppConnectionString); + await using var transaction = await app.BeginTransactionAsync(); + await using (var readOnly = new NpgsqlCommand("SET TRANSACTION READ ONLY", app, transaction)) + await readOnly.ExecuteNonQueryAsync(); + await AnnounceAsync(app, transaction, new GlobalIdentitySubject(database.Registration.AuthorityId, + database.Registration.Issuer, Subject)); + await using var explain = new NpgsqlCommand("EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) " + observation.Sql, app, transaction); + foreach (var parameter in observation.Parameters) + explain.Parameters.Add(new NpgsqlParameter(parameter.ParameterName, parameter.NpgsqlDbType) { Value = parameter.Value }); + using var document = JsonDocument.Parse((string)(await explain.ExecuteScalarAsync())!); + var root = document.RootElement[0]; + var plan = root.GetProperty("Plan"); + var actualRows = plan.GetProperty("Actual Rows").GetDouble(); + actualRows.Should().Be(1); + var nodes = new List(); + AddNodes(plan, nodes); + return new(string.Join('/', nodes), actualRows, + root.GetProperty("Planning Time").GetDouble(), root.GetProperty("Execution Time").GetDouble()); + } + + private static void AddNodes(JsonElement plan, List nodes) + { + nodes.Add(plan.GetProperty("Node Type").GetString()!); + if (plan.TryGetProperty("Plans", out var children)) + foreach (var child in children.EnumerateArray()) AddNodes(child, nodes); + } + + private sealed record PoolObservation(int Connections, int Active, int InTransactions, int LockWaiters); + private sealed record LookupPlan(string Nodes, double Rows, double PlanningMilliseconds, double ExecutionMilliseconds); + + /// Measurement-only current-code counterfactual; it qualifies no authentication or persistence boundary. + private sealed class WitnessedCounterfactualBindingResolver(VerifiedProviderSubject expected, IdentityBindingResult witnessed) + : ITenantIdentityBindingResolver + { + private int _calls; + internal int Calls => Volatile.Read(ref _calls); + public Task ResolveExistingAsync(VerifiedProviderSubject subject, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + Interlocked.Increment(ref _calls); + // Record equality includes issuer, opaque subject, optional actor and + // both scope claims. Every other input receives no binding authority. + return Task.FromResult(subject == expected ? witnessed : IdentityBindingResult.Refused(IdentityBindingOutcome.AdmissionDenied)); + } + } + + private sealed class BindingStatementCounter : ILoggerProvider, ILogger + { + private int _statements; + internal int Statements => Volatile.Read(ref _statements); + public ILogger CreateLogger(string categoryName) => this; + 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) + { + if (formatter(state, exception).StartsWith("Executing command: ", StringComparison.Ordinal)) + Interlocked.Increment(ref _statements); + } + public void Dispose() { } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/TenantExistingBindingAdmissionTests.Startup.cs b/backend/tests/LearnStack.Tests.Integration/Database/TenantExistingBindingAdmissionTests.Startup.cs new file mode 100644 index 000000000..e066f4781 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/TenantExistingBindingAdmissionTests.Startup.cs @@ -0,0 +1,67 @@ +using System.Net; +using FluentAssertions; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.Hosting; +using Xunit; + +namespace LearnStack.Tests.Integration.Database; + +public sealed partial class TenantExistingBindingAdmissionTests +{ + [Fact] + public async Task Actual_host_startup_requires_the_installed_authority_exact_configuration_and_application_role() + { + await using var issuer = await TenantAuthenticationIssuer.StartAsync(); + await using var database = await DatabaseAsync(issuer); + var authority = database.Registration.AuthorityId.Value.ToString("D"); + await using (var control = new QualifiedStartupFactory(database.AppConnectionString, issuer.Issuer, authority)) + { + using var client = control.CreateClient(); + using var healthy = await client.GetAsync("/healthz"); + healthy.StatusCode.Should().Be(HttpStatusCode.OK); + } + var counts = await CountsAsync(database); + await using var missing = await DisposableSchemaDatabase.CreateAsync(parent.Postgres); + foreach (var variant in new[] + { + new StartupVariant("missing anchor", missing.AppConnectionString, issuer.Issuer, authority), + new StartupVariant("mismatched authority", database.AppConnectionString, issuer.Issuer, Guid.NewGuid().ToString("D")), + new StartupVariant("mismatched issuer", database.AppConnectionString, + issuer.Issuer.Replace("/realms/", "/different/realms/", StringComparison.Ordinal), authority), + new StartupVariant("missing configured authority", database.AppConnectionString, issuer.Issuer, null), + new StartupVariant("wrong runtime role", database.MigrationConnectionString, issuer.Issuer, authority), + }) + { + await using var factory = new QualifiedStartupFactory(variant.Connection, variant.Issuer, variant.Authority); + Action start = () => { using var client = factory.CreateClient(); }; + var failure = start.Should().Throw(variant.Name).Which; + if (variant.Name == "wrong runtime role") + failure.Message.StartsWith("ConnectionStrings:Default names Username='learnstack_migration'", StringComparison.Ordinal) + .Should().BeTrue("the full production composition must reject an owner credential before qualification"); + else if (variant.Name == "missing configured authority") + failure.Message.Should().Be("Identity:AuthorityId requires an explicit nonempty authority UUID.", + "invalid deployment configuration refuses before the startup database qualifier"); + else + failure.Message.Should().Be("Identity authority startup qualification is unavailable or does not match deployment configuration."); + } + (await CountsAsync(database)).Should().Be(counts, "startup refusal must not install a replacement authority or allocate a binding"); + await using var restored = new QualifiedStartupFactory(database.AppConnectionString, issuer.Issuer, authority); + using var restoredClient = restored.CreateClient(); + using var restoredHealth = await restoredClient.GetAsync("/healthz"); + restoredHealth.StatusCode.Should().Be(HttpStatusCode.OK); + } + + private sealed record StartupVariant(string Name, string Connection, string Issuer, string? Authority); + + private sealed class QualifiedStartupFactory(string connection, string issuer, string? authority) : ConstructionOnlyApiFactory + { + protected override bool RetainIdentityQualification => true; + protected override void ConfigureTestHost(IWebHostBuilder builder) + { + builder.UseEnvironment(Environments.Development); + builder.UseSetting("ConnectionStrings:Default", connection); + builder.UseSetting("Authentication:Tenant:Issuer", issuer); + builder.UseSetting("Identity:AuthorityId", authority); + } + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/Database/TenantExistingBindingAdmissionTests.cs b/backend/tests/LearnStack.Tests.Integration/Database/TenantExistingBindingAdmissionTests.cs new file mode 100644 index 000000000..aae4d3bf4 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/Database/TenantExistingBindingAdmissionTests.cs @@ -0,0 +1,210 @@ +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using FluentAssertions; +using LearnStack.Api.Authentication; +using LearnStack.SharedKernel.Identifiers; +using LearnStack.Tools.Seeder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Serilog.Core; +using Xunit; +using Xunit.Abstractions; + +namespace LearnStack.Tests.Integration.Database; + +/// Ordinary HTTP admission through the real application-role global self reader. +[Collection(PublicReadTestGroup.Name)] +[Trait(RequiresDocker.Key, RequiresDocker.Value)] +public sealed partial class TenantExistingBindingAdmissionTests(PublicReadFixture parent, ITestOutputHelper output) +{ + private const string Subject = "binding-http-private-subject-canary"; + private static UserId Actor => UserId.From(TenantAuthenticationIssuer.Actor); + + [Fact] + public async Task Actorless_and_equal_evidence_resolve_the_stored_actor_before_the_real_tenant_read() + { + await using var issuer = await TenantAuthenticationIssuer.StartAsync(); + await using var database = await DatabaseAsync(issuer); + var observation = new BindingObservation(); + using var client = Client(database, observation); + var counts = await CountsAsync(database); + var reads = database.Observation.Reads; + + foreach (var includeActor in new[] { false, true }) + { + using var response = await SendAsync(client, Token(issuer, includeActor: includeActor)); + response.StatusCode.Should().Be(HttpStatusCode.OK); + TenantAuthenticationHttpTests.NoStore(response); + var account = await response.Content.ReadFromJsonAsync(); + account.GetProperty("actorId").GetGuid().Should().Be(Actor.Value); + account.GetProperty("tenantId").GetGuid().Should().Be(SeedData.English.TenantId.Value); + } + + using var publicResponse = await SendAsync(client, Token(issuer, includeActor: false), + TenantAuthenticationHttpRequest.PublicPath); + publicResponse.StatusCode.Should().Be(HttpStatusCode.OK); + database.Observation.Reads.Should().Be(reads + 3, + "the existing reader independently verifies the actual tenant transaction is read-only and application-role"); + observation.Lookups.Should().Be(3); + observation.ClosedOwners.Should().Be(3, + "normalization must return with no global owner, capture or resolved tenant context before tenant reconciliation"); + (await CountsAsync(database)).Should().Be(counts, "ordinary admission allocates no User and writes no creation audit"); + } + + [Fact] + public async Task Unknown_and_conflicting_bindings_refuse_even_public_reads_without_allocation_or_adoption() + { + await using var issuer = await TenantAuthenticationIssuer.StartAsync(); + await using var database = await DatabaseAsync(issuer); + var observation = new BindingObservation(); + using var client = Client(database, observation); + var counts = await CountsAsync(database); + using (var control = await SendAsync(client, Token(issuer))) control.StatusCode.Should().Be(HttpStatusCode.OK); + var reads = database.Observation.Reads; + + foreach (var path in new[] { TenantAuthenticationHttpRequest.AccountPath, TenantAuthenticationHttpRequest.PublicPath }) + foreach (var token in new[] + { + Token(issuer, subject: "unbound-private-subject-canary", includeActor: false), + Token(issuer, subject: "unbound-private-subject-canary"), + Token(issuer, actor: Guid.CreateVersion7()), + }) + { + using var response = await SendAsync(client, token, path); + await FixedUnauthorizedAsync(response); + } + + observation.Lookups.Should().Be(7); + observation.ClosedOwners.Should().Be(7); + database.Observation.Reads.Should().Be(reads); + (await CountsAsync(database)).Should().Be(counts); + } + + [Theory] + [InlineData("Closing")] + [InlineData("Closed")] + [InlineData("Collision")] + public async Task Committed_nonadmitting_or_collision_state_is_rechecked_without_an_identity_cache(string state) + { + await using var issuer = await TenantAuthenticationIssuer.StartAsync(); + await using var database = await DatabaseAsync(issuer); + var observation = new BindingObservation(); + using var client = Client(database, observation); + var token = Token(issuer, includeActor: false); + using (var control = await SendAsync(client, token)) control.StatusCode.Should().Be(HttpStatusCode.OK); + var counts = await CountsAsync(database); + var subjectDigestDefinition = await SetBindingStateAsync(database, state); + try + { + foreach (var path in new[] { TenantAuthenticationHttpRequest.AccountPath, TenantAuthenticationHttpRequest.PublicPath }) + { + using var refused = await SendAsync(client, token, path); + await FixedUnauthorizedAsync(refused); + } + observation.Lookups.Should().Be(3); + (await CountsAsync(database)).Should().Be(counts); + } + finally { await SetBindingStateAsync(database, "Active", subjectDigestDefinition); } + using var restored = await SendAsync(client, token); + restored.StatusCode.Should().Be(HttpStatusCode.OK); + await AssertBindingGuardsRestoredAsync(database, subjectDigestDefinition); + } + + [Fact] + public async Task Anonymous_and_earlier_refusals_do_no_binding_work_and_exhausted_subject_quota_precedes_SQL() + { + await using var issuer = await TenantAuthenticationIssuer.StartAsync(); + await using var database = await DatabaseAsync(issuer); + var observation = new BindingObservation(); + using var limiter = new TenantSubjectRateLimiter(); + using var client = Client(database, observation, services => + services.Replace(ServiceDescriptor.Singleton(limiter))); + using (var anonymous = await SendAsync(client, null, TenantAuthenticationHttpRequest.PublicPath)) + anonymous.StatusCode.Should().Be(HttpStatusCode.OK); + using (var absent = await SendAsync(client, null)) absent.StatusCode.Should().Be(HttpStatusCode.NotFound); + using (var invalid = await SendAsync(client, "not-a-bearer-token")) await FixedUnauthorizedAsync(invalid); + using (var unknownHost = await TenantAuthenticationHttpRequest.Send(client, "unmapped.invalid", + TenantAuthenticationHttpRequest.PublicPath, Token(issuer))) unknownHost.StatusCode.Should().Be(HttpStatusCode.NotFound); + observation.Lookups.Should().Be(0); + + using (var control = await SendAsync(client, Token(issuer, includeActor: false))) + control.StatusCode.Should().Be(HttpStatusCode.OK); + // Prime the unchanged production registry directly, avoiding 599 redundant + // database reads. The final permit and its HTTP refusal use the same issuer/sub key. + var verified = new VerifiedProviderSubject(issuer.Issuer, Subject, null, null, null); + for (var permit = 1; permit < TenantSubjectRateLimiter.PermitPerWindow; permit++) + limiter.AttemptAcquire(verified).IsAcquired.Should().BeTrue(); + using var exhausted = await SendAsync(client, Token(issuer, actor: Guid.CreateVersion7()), + TenantAuthenticationHttpRequest.PublicPath); + exhausted.StatusCode.Should().Be(HttpStatusCode.TooManyRequests); + exhausted.Headers.RetryAfter.Should().NotBeNull(); + TenantAuthenticationHttpTests.NoStore(exhausted); + observation.Lookups.Should().Be(1, "changed actor evidence does not bypass the issuer/subject budget or reach binding SQL"); + } + + [Fact] + public async Task Actual_store_permission_fault_is_uniform_401_with_a_fixed_private_diagnostic_and_recovers() + { + await using var issuer = await TenantAuthenticationIssuer.StartAsync(); + await using var database = await DatabaseAsync(issuer); + var observation = new BindingObservation(); + var logs = new BindingLogSink(); + using var client = Client(database, observation, services => services.AddSingleton(logs)); + var token = Token(issuer, includeActor: false); + using (var control = await SendAsync(client, token)) control.StatusCode.Should().Be(HttpStatusCode.OK); + var counts = await CountsAsync(database); + logs.BeginFaultWindow(); + await ExecuteOwnerAsync(database, "REVOKE SELECT ON public.users FROM learnstack_app"); + try + { + using var unavailable = await SendAsync(client, token, TenantAuthenticationHttpRequest.PublicPath); + await FixedUnauthorizedAsync(unavailable); + logs.AssertUnavailable(Subject, token, Actor.Value.ToString("D")); + (await CountsAsync(database)).Should().Be(counts); + } + finally { await ExecuteOwnerAsync(database, "GRANT SELECT ON public.users TO learnstack_app"); } + using var restored = await SendAsync(client, token); + restored.StatusCode.Should().Be(HttpStatusCode.OK); + observation.Lookups.Should().Be(3, "the planted SQL fault must be reached between two actual positive reads"); + observation.ClosedOwners.Should().Be(3); + } + + private Task DatabaseAsync(TenantAuthenticationIssuer issuer) => + IdentityPublicReadFixture.CreateAsync(parent, issuer.Issuer, new Dictionary { [Actor] = Subject }); + + private static HttpClient Client(IdentityPublicReadFixture database, BindingObservation observation, + Action? configure = null) => database.ClientFor(SeedData.English.Host, services => + { + ObserveBindings(services, observation); + configure?.Invoke(services); + }, builder => builder.UseSetting("Serilog:MinimumLevel:Default", "Debug")); + + private static string Token(TenantAuthenticationIssuer issuer, string subject = Subject, bool includeActor = true, + Guid? actor = null) + { + var payload = AccountSiteHttpTests.Token(issuer, SeedData.English, subject: subject, actor: actor); + if (includeActor) return payload; + // AccountSiteHttpTests.Token returns the compact token; recreate its payload + // through the issuer to exercise genuinely absent compatibility evidence. + using var document = JsonDocument.Parse(issuer.Payload( + ("sub", subject), ("tenant_id", SeedData.English.TenantId.Value.ToString("D")))); + var withoutActor = "{" + string.Join(',', document.RootElement.EnumerateObject() + .Where(property => !property.NameEquals("user_id") && !property.NameEquals("organization_id")) + .Select(property => JsonSerializer.Serialize(property.Name) + ":" + property.Value.GetRawText())) + "}"; + return issuer.Token(withoutActor); + } + + private static Task SendAsync(HttpClient client, string? token, + string path = TenantAuthenticationHttpRequest.AccountPath) => + TenantAuthenticationHttpRequest.Send(client, SeedData.English.Host, path, token); + + private static async Task FixedUnauthorizedAsync(HttpResponseMessage response) + { + await TenantAuthenticationHttpTests.Problem(response, HttpStatusCode.Unauthorized, "unauthorized"); + TenantAuthenticationHttpTests.NoStore(response); + response.Headers.WwwAuthenticate.Should().ContainSingle().Which.ToString().Should().Be("Bearer"); + (await response.Content.ReadAsStringAsync()).Should().NotContain(Subject).And.NotContain("binding_store_unavailable"); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/FixtureTenantIdentityBindingResolver.cs b/backend/tests/LearnStack.Tests.Integration/FixtureTenantIdentityBindingResolver.cs new file mode 100644 index 000000000..0640edc36 --- /dev/null +++ b/backend/tests/LearnStack.Tests.Integration/FixtureTenantIdentityBindingResolver.cs @@ -0,0 +1,25 @@ +using LearnStack.Api.Authentication; +using LearnStack.Modules.Identity.Application.Contracts.Bindings; +using LearnStack.SharedKernel.Identifiers; + +namespace LearnStack.Tests.Integration; + +/// Exact fixture bindings for proofs whose owned subject is outside identity persistence. +internal sealed class FixtureTenantIdentityBindingResolver(string issuer, IEnumerable subjects, + UserId? actor = null) : ITenantIdentityBindingResolver +{ + private readonly HashSet _subjects = new(subjects, StringComparer.Ordinal); + private readonly UserId _actor = actor ?? UserId.From(TenantAuthenticationIssuer.Actor); + + public Task ResolveExistingAsync(VerifiedProviderSubject subject, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + var result = subject.Issuer != issuer || !_subjects.Contains(subject.Subject) + ? IdentityBindingResult.Refused(IdentityBindingOutcome.NotFound) + : subject.ClaimedActor is { } claimed && claimed != _actor + ? IdentityBindingResult.Refused(IdentityBindingOutcome.Conflict) + : IdentityBindingResult.Bound(_actor, created: false); + return Task.FromResult(result); + } +} diff --git a/backend/tests/LearnStack.Tests.Integration/LearnStack.Tests.Integration.csproj b/backend/tests/LearnStack.Tests.Integration/LearnStack.Tests.Integration.csproj index cc9fb7560..00e339184 100644 --- a/backend/tests/LearnStack.Tests.Integration/LearnStack.Tests.Integration.csproj +++ b/backend/tests/LearnStack.Tests.Integration/LearnStack.Tests.Integration.csproj @@ -18,6 +18,7 @@ + MA[Membership tenant=A role=learner] - U --> MB[Membership tenant=B role=instructor] - U --> MC[Membership tenant=C role=admin] + P[Verified provider subject in learnstack realm] --> U[Global User binding: typed UserId] + U --> MA[Membership tenant=A: contained Profile and assignments] + U --> MB[Membership tenant=B: contained Profile and assignments] + MA --> RA[Tenant A Role templates: scoped grants] + MB --> RB[Tenant B Role templates: scoped grants] ``` +Text fallback: the verified provider subject maps permanently to one global +User; contextual Memberships contain Profiles and assignments to tenant-owned +Role templates. Roles confer capability only through eligible assignments. + Two realm strategies were considered: - **Single tenant realm, scalar active scope** (chosen). The `learnstack` realm - is the required issuer for the ADR-0064 profile: opaque `sub`, stable UUID `user_id`, optional - scalar UUID `tenant_id` and optional scalar UUID `organization_id`. It carries + is the required issuer. The shipped P02b-5/P02b-6 profile requires opaque `sub` + and UUID `user_id`, with optional scalar UUID `tenant_id` / `organization_id`. + Accepted ADR-0072 makes API `user_id` optional at the verified-provider stage, + resolving the stored actor before normal identity admission. The complete native + BFF profile still requires actor/tenant and its AccountSite witness. It carries no authoritative membership array or application-role grant. P02b-6 supplies admin-controlled attributes/mappers and real issuance proof; the committed realm export issues that profile. Phase 03 owns live memberships. @@ -135,6 +146,36 @@ The separate `learnstack-hub` realm remains the operator boundary. Realm-per-ten is not part of the accepted API profile; a different issuer strategy needs a new decision before its first consumer. +### Application identity preparation + +Jointly Accepted [ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md) / +[ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md) +settle the P03-1 binding/storage contract. Internal binding/adoption and contextual +storage/seed and the ordinary API sequence below are implemented. The +[Phase 03 Status block](../roadmap/phase-03-identity-admin.md) owns qualification. +`VerifiedProviderSubject` carries verified issuer/sub and optional actor/scope +evidence. Subject quota precedes binding SQL; an uncached committed binding +lookup resolves the nonnullable actor in `ValidatedTenantIdentity`. Missing, +conflicting, Closing/Closed or unavailable bindings refuse ordinary admission +with the existing uniform 401; no lookup allocates, adopts or repairs a User. +Anonymous reads perform no identity lookup. This adds a binding-store dependency +to authenticated admission, separately from provider-key caching. + +P03-1 admits fixed witnessed seed creation/adoption and existing-session binding +only. It adds no POST, SDK operation or native no-session completion. P03-3 owns +new-user HTTP/BFF entry and independently validated orgless/branch reissue. The +shipped complete native profile and AccountSite host ceiling remain; optional API +actor evidence does not publish a tenantless native session. G2 execution remains +P03-2. G4 scope transitions remain P03-3; current provider user-global attributes +do not prove independent simultaneous session scopes. Ordinary refresh remains +scope-preserving until that bounded transition contract ships. + +No missing profile is repaired by email merging, a new per-login actor, a client +tenant selector or a permissive membership default. Existing seed/provider IDs +and credentials remain preserved. The first runtime provider adapter is separate +from development realm tooling; an actual SDK introduction triggers its catalogue +backfill, while direct HTTP alone does not. + ## Token Flow ```mermaid @@ -226,44 +267,63 @@ Roles live in LearnStack, not in Keycloak. Keycloak does not know what an "instr Mechanism: - `Membership` carries one or more `Role` references. -- `Role` carries `Permission`s (atomic capabilities like `course.publish`, `enrollment.create`). -- Resource-scoped checks (`course.edit` is allowed only when `course.owner_id == current_user.id`) live in policy classes, evaluated in the application layer. - -The API uses opaque `sub` for external identity/subject accounting and UUID -`user_id` for actor attribution, with scalar active-scope claims. Email and +- `Role` carries code-defined permissions from the + [closed key/action catalogue](../standards/19-permissions.md), such as + `education.course.write` and `education.course_publication.write`. +- Resource-scoped checks limit `education.course.write` to the actor's own course + where applicable; they live in application policy classes. + +The API uses opaque `sub` for verified-provider subject accounting and the +resolved typed UserId for actor attribution, checking any supplied UUID `user_id` +against that binding under ADR-0072. Scalar scope claims remain assertions. Email and realm/client roles grant no application authority. Phase 03 owns permission resolution; P02b-5 exposes only its closed nonsensitive read while application authorization is still pass-through. ## Invitations -Invitations are owned by LearnStack: +Invitations are owned by LearnStack. The target flow below needs +[Phase 03 G1/G8](../roadmap/phase-03-identity-admin.md#the-decision-register) +before its writers: actor bootstrap, verified current email, aggregate boundaries, +single-use acceptance, grant freshness and bounded delivery are not yet delivered. ```mermaid sequenceDiagram participant Admin + participant Web as Native BFF participant API - participant Email + participant Delivery as Bounded invitation delivery participant Invitee + participant KC as Keycloak - Admin->>API: POST /v1/invitations (email, role) - API->>API: create Invitation row, generate token - API->>Email: send templated email with link - Invitee->>API: GET /invite/accept?token=... - alt user does not exist in Keycloak - API->>API: redirect to Keycloak signup with prefilled email - else user exists - API->>API: redirect to Keycloak login - end - Invitee->>API: callback with KC tokens - API->>API: create Membership, mark Invitation accepted + Admin->>Web: Submit authorized invitation + Web->>API: Admitted invitation command + API->>API: Persist offer and durable delivery intent + API-->>Delivery: Execute the G8 delivery contract + Delivery-->>Invitee: Offer and permitted continuation + Invitee->>Web: GET inspects offer; no grant + Web->>KC: Approved sign-in/signup continuation + KC-->>Web: Bound callback under G1 bootstrap + Invitee->>Web: Confirm acceptance through admitted mutating act + Web->>API: Verify subject/email, offer and current delegation + API->>API: Reconcile membership grant and offer consumption under G8 ``` +Text fallback: an authorized admin creates a durable offer and delivery intent; +the invitee inspects it without a write, completes the approved identity flow and +confirms acceptance. The API verifies current identity/delegation and produces +the single authoritative grant/offer outcome. Exact routes and atomicity belong +to G8; this diagram admits no direct token callback to the API or multi-root write. + Edge cases: - **Invitee uses a different email at Keycloak signup.** The invitation token is bound to the email; mismatched signup is rejected. - **Invitation expires.** Default TTL 14 days, configurable per tenant. - **Invitation revoked.** Tenant admin can revoke; accepting a revoked invitation is rejected. +- **Races and delivery failure.** G8 specifies accept/revoke/expiry/resend and + existing-member outcomes, one-way token storage, provider idempotency/ + reconciliation and truthful delivery state. Full notification orchestration + remains Phase 08a; the usable Phase 03 handoff cannot depend on it silently. ## SSO and Federation @@ -271,10 +331,19 @@ Tenant-specific SSO is enabled per tenant. Implementation: - A tenant can configure a SAML or OIDC identity provider in Keycloak (admin API). - The tenant's public site shows "Sign in with {tenant}" on the login page. -- Users authenticating via tenant SSO land in the LearnStack realm; their Keycloak account is federated, and LearnStack creates or matches a `Membership` based on the email. +- Users authenticating through a broker land in the LearnStack realm. Broker + authentication or email equality alone grants no LearnStack membership, role or + global account link. Phase 03 G1/G8/G12 supply the trusted linking/admission + contract before any such writer. This does not require LearnStack code changes per tenant; it is a configuration in Keycloak that LearnStack exposes via a tenant-admin UI. +The UI needs a confined runtime adapter: tenant ownership of broker resources, +write-only secrets, bounded metadata/discovery egress, trusted verification/MFA, +test/activate/rollback and last-login recovery. G12 owns those decisions and their +real two-tenant provider proof; a realm-level Admin API credential is not tenant +authority. + ## MFA MFA is a Keycloak responsibility. Enforced for: @@ -305,7 +374,11 @@ Two audit streams: - **Keycloak audit** — login success/failure, password change, MFA enroll, account lock. Retained inside Keycloak. - **LearnStack `AuditLog`** — role change, permission change, invitation, tenant setting change, platform admin bypass. Owned by LearnStack. -Mirrored events (e.g. `user.created`) are propagated via Keycloak webhooks into LearnStack so cross-system queries are possible. +The mirror is a Phase 03 G10 target. That gate selects authenticated durable +provider listener/webhook or pull ingress, stable provider-event deduplication, +global/unknown/multi-membership attribution and retention. Approved facts enter +the tenant outbox and transport-owned Audit subscription; raw provider payloads +and a direct business `IEventBus.PublishAsync` are not the mirror contract. ## Local Development diff --git a/docs/architecture/23-data-protection.md b/docs/architecture/23-data-protection.md index fe3cb3139..f8e80b0ff 100644 --- a/docs/architecture/23-data-protection.md +++ b/docs/architecture/23-data-protection.md @@ -16,9 +16,103 @@ Every aggregate that may hold personal data must declare its PII category at des | **Payment** | Billing addresses, last-four card digits, invoice records | Retained 7 years for tax compliance (cannot be deleted on request); separate retention from other PII. | | **Audit** | Audit log entries referencing the user | Retained per [18-audit-coverage.md](../standards/18-audit-coverage.md); bounded redaction preserves the action record and immutable identifiers. See [erasure prerequisites](#erasure-authority-and-first-writer-prerequisites). | -Every aggregate's domain spec must record its PII categories. Phase 03 owns the +Every aggregate's domain spec must record its PII categories. +[Phase 03 G19](../roadmap/phase-03-identity-admin.md#the-decision-register) owns the classification census and planted missing-annotation control before its first -DSAR writer; no current CI check discovers every email/phone/address column. +identity PII writer; G9 extends it for custom-field revision history. The +implemented mapped-property census requires explicit semantics; it does not infer personal data from an email/phone/address name or arbitrary stored text. + + + +### Identity foundation and classification ownership + +**Classification implemented in P03-1 Step 2; global Identity storage/common +audit implemented in Step 3; contextual storage and diagnostic controls +implemented and independently reviewed in Step 4; +fulfillment remains with its named owners.** Jointly Accepted +[ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md) and +[ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md) +require these controls before the first identity writer. Step 3 adds 17 reviewed +global scalars; Step 4 adds 36 contextual scalars. The complete census covers six +contexts, 26 entities and 254 scalar properties. Neither classification nor +storage fulfills an erasure request. + +P03-1 Step 2 implements reviewed declarations in each module's EF mappings and +`PersonalDataModelCensus` in common Infrastructure. Each module owns declarations +for every property in its mapped models, including inherited references. The Infrastructure data-protection coordinator +and `DataProtectionConventionTests` compare those declarations with the complete, +nonempty EF property population before identity writes. +`Mapped_Properties_Have_Explicit_Personal_Data_Classification` is Implemented +in the [architecture catalogue](../standards/21-architecture-tests-catalogue.md), +with real production-model omission and positive controls. An +undeclared property fails; `None` requires an explicit nonpersonal purpose and is +never a default. Module audit specs own exact reference/payload paths and snapshot +redaction markers. The explicit common audit-column declarations live in +[AuditColumnMapping](../../backend/src/LearnStack.Infrastructure/Persistence/AuditColumnMapping.cs): +actor references are Identity, change timestamps Audit, and the technical +row-version counter explicitly None. Classification never reads row values or +replaces snapshot markers, disclosure authority or erasure/retention rules. SQL-only, control and vendor stores stay in their existing +inventories; this check creates no duplicate durable-store inventory. + +The Accepted User contract retains a stable authority identifier, subject key, actor and +admission lifecycle. Raw subject is required while Active, explicitly marked +`[PiiSensitive]` for snapshot capture, and nullable for removal at Closed by the +authorized P03-10 closure writer. No raw issuer is copied onto each User. The +platform-scoped, application-read-only `identity_authority` singleton owns the +stable authority UUID and current exact issuer URI. The deployment installer +creates it once with migration credentials before bootstrap; application code +cannot insert, update or automatically replace it. Configuration issuer drift +refuses identity admission. P03-9/G13 owns an approved issuer rebind before the +first change, proving provider continuity and freezing bootstrap and old grants +while preserving authority, keys, actors and closed tombstones. Until that owner +is implemented, issuer renaming is unsupported; aliases and email matching supply +no continuity proof. + +The subject key is SHA-256 over domain-separated, length-delimited stable +authority UUID and exact opaque subject, using the +[canonical Standard 05 encoding](../standards/05-database.md#proposed-p03-1-identity-storage-annex). +It supports +stable equality and audit linkage, not secrecy: low-entropy subjects remain +vulnerable to dictionary guessing, and no provider entropy guarantee is assumed. +HMAC is not selected; selecting it for secrecy would also require durable key +custody, rotation and restore decisions. Hash and actor linkage are PII-Identity, +retained under their declared purposes, not anonymous data. An Active key match +with a different raw subject refuses; a Closed key match always refuses admission +and never merges identities. The permanent key/actor tombstone prevents +recreation indefinitely; closure removes the raw subject rather than claiming +that the retained tombstone is erased. + +P03-1 adds no email/verification columns or claim processing. A first earlier +consumer or P03-6/G10 owns the minimum mirror fields and freshness contract before +their writer. Snapshot markers, diagnostic controls and semantic classification +remain separate requirements; none implies general exception-message scrubbing. + +`IdentityDiagnosticSinkTests` exercises real tracked profile writes and global +binding creation with provider-generated, value-bearing failures. Neutral, +nested and sensitive canaries reach PostgreSQL before exclusion is checked in +serialized Serilog, the local error archive, the real Sentry SDK envelope, +exported OpenTelemetry spans and L1 response bytes. Nonempty positive controls +qualify each output. Immediate and deferred profile failures, the global binding +boundary, real validator attempted values and sibling-module event confinement +are separate controls. `TenantExistingBindingAdmissionTests` additionally reaches +a value-bearing binding SELECT failure through actual HTTP: serialized Serilog, +exported traces and response bytes exclude the neutral/nested/sensitive values +while retaining fixed failure signals and a 401. This ordinary refusal does not +execute the L1 exception, local archive or Sentry path; those sinks retain their +separate writer-failure controls above. +Identity replaces only its EF save/query-failure events with fixed diagnostics; +unexpected contextual provider failures retain no original exception payload. +Its per-context interceptor records the exact caller before command creation +and marks only the validated EF spans created for that command. Multiple tracing +compositions can produce several such spans; the preexisting caller is excluded, +even when it is another real EF command. A named processor fixes only marked +Error descriptions before export, preserving error status, span metadata and +trace ancestry. Independent started/stopped activity IDs and two actual tracing +compositions qualify complete exporter coverage; a nested Tenancy command keeps +its original provider error. Ordinary command diagnostics, other +modules' EF failure events and unmarked span descriptions remain active. +These cases qualify the named Identity boundaries, not arbitrary exception text +throughout the application. ## Rights We Support @@ -35,6 +129,16 @@ Both KVKK Madde 11 ("kişisel verileri elde etme") and GDPR Article 15 require g - 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. +Tenant/org RLS is one boundary, not the subject predicate. Every participating +module additionally identifies the requested person and permitted recipient/ +purpose, including third-party references inside shared JSON/audit records. +[Phase 03 G15/G16](../roadmap/phase-03-identity-admin.md#the-decision-register) +settle self/admin/delegate and org scope, eligibility/holds, artifact retrieval +authorization/revocation, expiry, cleanup and durable progress before their first +writers. PII category alone does not decide disclosure. The private artifact needs +an explicit Phase 03 prerequisite slice or an approved replacement contract; the +full Phase 04 media and Phase 08a notification engines are not implicit blockers. + ### Right to Rectification Profile edit is the everyday path. The platform must accept name / email / phone updates via the user's own profile screen or via the tenant admin's user management screen. @@ -42,6 +146,12 @@ Profile edit is the everyday path. The platform must accept name / email / phone - Email change re-runs Keycloak's email verification. - Audit entries record the change. +This does not grant tenant admins a global identity editor. Provider canonical +email stays mirror-owned; contextual contact data stays membership-owned under +[Phase 03's ownership table](../roadmap/phase-03-identity-admin.md#tenant-data-ownership-dsar-boundary-and-pii-classification). +G1/G3 decide trusted mirror updates and self/admin field permissions before those +writers. A matching email never merges global identities or grants membership. + ### Right to Erasure (Right to be Forgotten) Both regimes recognise exceptions (legal obligation, contract performance). LearnStack distinguishes: @@ -71,12 +181,24 @@ that tenant. 2. The `Membership` and its `MembershipProfile` are removed. 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). -4. The `users` row survives for as long as any membership remains anywhere. Nothing in - this flow touches Keycloak. +4. This flow preserves the [permanent global binding/tombstone](#identity-foundation-and-classification-ownership). + Nothing in this flow touches Keycloak. + +G15 defines the authorized subject/org scope: an org admin cannot erase a person's +other branch, and the subject needs a request/status path without admin rights. +G16 retains sufficient workflow authority and a scoped status receipt after the +membership is removed; it settles the last-membership case without silently +turning tenant erasure into provider-account closure. **Global account closure.** A **platform-scoped** operation. There is no tenant-admin endpoint for it. +The person authorizes the account request through its separate surface; this +does not assign the person a Platform permission. Phase 03 G13/G16 distinguish +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). @@ -125,7 +247,7 @@ Exclusion from this asynchronous inventory is not an erasure exemption. Other module tables remain explicit scope exclusions, so a new table cannot -silently escape the five-chain migration census. Their own module specifications +silently escape the complete migration census. Their own module specifications govern personal data; exclusion here grants no erasure exemption. @@ -149,6 +271,13 @@ govern personal data; exclusion here grants no erasure exemption. | `course_translations` | Education localized content | | `lesson_translations` | Education localized content | | `audit_config` | Audit coverage configuration | +| `users` | Synchronous global identity binding/tombstone; retained raw subject, digest and creation-audit linkage follow the Identity contract and P03-10 closure owner | +| `identity_authority` | Deployment-owned stable authority registration, not a per-person profile; installation and rebind remain separately confined | +| `memberships` | Synchronous contextual identity relation; its lifecycle and personal linkage remain with Identity and P03-10 closure | +| `membership_profiles` | Synchronous tenant/organization personal profile; classification and fulfillment remain with Identity, without an asynchronous delivery copy | +| `membership_role_assignments` | Synchronous authorization links; exclusion from the asynchronous inventory grants no personal-data retention or erasure exemption | +| `roles` | Synchronous tenant-owned authority templates, not queued payloads | +| `role_permission_grants` | Synchronous explicit authority definitions, not delivery or diagnostic copies | LearnStack job-table no-delete triggers also bind the owner; BYPASSRLS is not @@ -191,6 +320,15 @@ The inventory also covers these distinct copies and custody boundaries: | Native BFF session custody | `InMemoryBffSessionStore` is volatile process-local custody under ADR-0070, not a durable ledger. Local invalidation does not erase provider events or diagnostic archives | +ADR-0072/0073 add identity linkage to the existing `audit_log` boundary above, +not another physical store or custody owner. The implemented global branch uses +these linkages: +`metadata.identity_subject_key` carries the stable binding key, including failed +attempts without a User; proposed target and action references remain personal +data. Existing SecurityEvent retention applies, and metadata stays outside the +six-column UPDATE grant. P03-10 locates and reports retained linkage under the +same inventory boundary. + ### Erasure authority and first-writer prerequisites - [Phase 03](../roadmap/phase-03-identity-admin.md#tenant-data-ownership-dsar-boundary-and-pii-classification) @@ -222,9 +360,28 @@ The inventory also covers these distinct copies and custody boundaries: causal metadata before its redaction/erasure handler lands; this inventory does not claim that complete anonymisation already 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 +`IUserReferenceLocator` to locate exact global failed-attempt paths by subject key +even when no User was committed, together with successful actor references. Its +request/result contract reports retained immutable linkage and the applicable +retention truthfully; it does not call the tombstone or subject key anonymous. +The key/actor tombstone serves indefinite anti-recreation, while audit copies +follow the SecurityEvent period in [Audit Coverage](../standards/18-audit-coverage.md#retention). +This foundation contract does not widen metadata UPDATE grants. P03-10 settles exact +principal, minimum grants and participant completion before its first writer; +Phase 11 owns later purge, backup and retained-copy reconciliation operations. + ### Right to Restriction of Processing -A learner can request that processing be paused while a dispute is resolved. Implementation: a tenant-scoped flag on the user that gates analytics ingestion and notifications. Reads continue (the user can still log in and see their own data) but no new events are processed. +A learner can request that processing be paused while a dispute is resolved. +The restriction belongs to the tenant/membership context, never a tenant-authored +column on global `User`. [Phase 03 G3/G15/G16](../roadmap/phase-03-identity-admin.md#the-decision-register) +settle its storage, authority and fulfillment before the writer. The intended +restriction gates analytics ingestion and notifications while preserving the +person's authorized access to their data; this paragraph claims no implemented +restriction mechanism. ### Right to Object diff --git a/docs/architecture/28-platform-tenant-organization.md b/docs/architecture/28-platform-tenant-organization.md index 1d8a7ce10..c44e3b116 100644 --- a/docs/architecture/28-platform-tenant-organization.md +++ b/docs/architecture/28-platform-tenant-organization.md @@ -138,7 +138,7 @@ erDiagram Tenant ||--o{ TenantScoringRule : "defines" Tenant ||--o{ CustomDomain : "has 0..N" Tenant ||--|| TenantPlan : "subscribed to (via Hub)" - Organization ||--o{ User : "has members" + Organization ||--o{ Membership : "scopes organization memberships" Organization ||--o{ Course : "owns 0..N (or tenant-wide)" Course ||--|{ CourseVersion : "versioned" CourseVersion ||--|{ Module : "contains" @@ -147,7 +147,7 @@ erDiagram Tenant ||--o{ Course : "owns 0..N (tenant-wide)" Tenant ||--o{ Page : "owns 0..N" User ||--o{ Membership : "has (per tenant+org)" - Membership }o--|| Role : "has" + Membership }o--o{ Role : "holds scoped grants" Tenant { uuid id PK @@ -167,18 +167,24 @@ erDiagram } User { uuid id PK - string keycloak_user_id - string email } Membership { uuid id PK uuid user_id FK - uuid tenant_id FK - uuid organization_id FK - uuid role_id FK + uuid tenant_id + uuid organization_id } ``` +Text fallback: a global user has memberships in tenant/optional-organization +contexts and may hold multiple scoped role grants. Organization remains Tenancy's +aggregate; Membership holds its ID by value, with no cross-module FK or join. +This is a conceptual relationship diagram. The implemented binding, nullable +keys, profile and Role shapes follow the [Identity contract](../modules/identity/README.md); +[Database Standards](../standards/05-database.md#identity-storage-contract) owns +actual columns and policies. The [Phase 03 Status block](../roadmap/phase-03-identity-admin.md) +owns current qualification state. + ## 4. What customers can do — what LearnStack core does for them LearnStack core provides the **same set of generic capabilities** to every tenant. The diff --git a/docs/architecture/30-api-gateway.md b/docs/architecture/30-api-gateway.md index 10e50fcbc..6369e82e8 100644 --- a/docs/architecture/30-api-gateway.md +++ b/docs/architecture/30-api-gateway.md @@ -263,10 +263,12 @@ backend admission or turn caller-supplied tenant ids into authority. Route 100 previously carried `client_secret_ref: vault://learnstack/hub/internal-api-hmac-key`. That path is the -**Hub internal API HMAC body-signing key** — a credential from an entirely different -trust domain, whose possession lets the holder forge a signed entitlement push for **any -tenant**. Handing it to the edge gateway as an OIDC client secret placed the platform's -highest-value secret on its most exposed component. +**Hub internal API HMAC body-signing key**, from a different trust domain. +Possession permits forged body signatures for arbitrary tenant pushes; successful +internal admission still independently requires accepted mTLS and a valid service +JWT under [Security Standards](../standards/11-security.md#hub-contract-surface). +Giving that secret to the gateway compromises the body-signature boundary even +when the other two controls continue to hold. The line is **deleted**, and no substitute is needed: the route is `bearer_only: true`, which means APISIX validates a presented bearer token against the realm's public JWKS and @@ -391,11 +393,13 @@ routes: upstream: { type: roundrobin, nodes: { "learnstack-hub:5000": 1 } } ``` -The corrections in Rules 1–3 land in the shipped `infra/apisix/apisix.yaml` in -[Phase 03](../roadmap/phase-03-identity-admin.md). The `openid-connect` block stays -disabled until its qualification and gateway activation in Phase 11. APISIX -becomes a real -gateway — TLS termination, consumer-keyed limits, WAF — in +The corrections in Rules 1–3 land in the committed `infra/apisix/apisix.yaml` +scaffold under [Phase 03 G18](../roadmap/phase-03-identity-admin.md#the-decision-register). +That file already has priorities and no Hub-secret reference; its remaining +version-wildcard correction must preserve disabled `openid-connect`. Phase 03 +does not copy this complete target example into live routes. The reviewed +per-public-read allowlist, route lint, OIDC/TLS/provenance qualification and +gateway activation remain [Phase 11](../roadmap/phase-11-production-hardening.md). ## 5. Defense-in-depth: JWT validated twice diff --git a/docs/architecture/31-audit-subsystem.md b/docs/architecture/31-audit-subsystem.md index 86659b70d..e69b85cc5 100644 --- a/docs/architecture/31-audit-subsystem.md +++ b/docs/architecture/31-audit-subsystem.md @@ -110,6 +110,51 @@ Redaction, projection and external fan-out happen after the commit, reading the row; none of them updates it. ADR-0016's "audit never blocks business logic" is preserved for that second stage and withdrawn for the first. +### Accepted global identity audit extension + +Jointly Accepted [ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md) / +[ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md) +extend the common owner in P03-1 Step 3. `IAuditStore` exposes eight implemented +writes: pending, standalone, best-effort, platform scope, event terminal, job +terminal, `WriteGlobalIdentityPending` and `ReconcileGlobalIdentity`. Exact +method/call-site controls and actual app-role positive/planted proofs qualify +the global extension. The [Phase 03 Status block](../roadmap/phase-03-identity-admin.md) +owns current qualification and review state. + +`PreparedGlobalIdentityOwner` binds the verified authority/subject, source and +physical connection/transaction/generation under a distinct global authority +kind. It serializes and freshly checks the subject before allocation or an +audit intent; an existing binding returns without a mutation intent. Only +serialized absence enters the common typed audit/capture entry. The single-use +`GlobalIdentityCreationReference` supplies the exact audit key to the deferred +User handler; the common transaction owner consumes the prepared handle and +reports the actual commit boundary. No tenant/global joining, synthetic tenant +context, private Identity writer or handler-owned capture manipulation is admitted. + +The typed global creation attribution flows through `AuditIntent`, captured +attribution and `AuditDraftComposer`. Central composition supplies immutable +metadata and exact creation references for success and non-success; callers +receive no arbitrary metadata/draft writer. Reciprocal User/success witnesses +are forced before commit; evidence APIs return only an exact Boolean match, and +a duplicate-key error proves neither matching evidence nor business commitment. +Unknown acknowledgement keeps the possible indeterminate pair and independent +bounded reconciliation. A non-success row proves only its own durability, never +User absence or business success. Bootstrap actor is NULL, seed adoption uses +SystemActor, and proposed target remains distinct. + +The sentinel global class is exactly `identity.user.create`, MUST/SecurityEvent, +with NULL organization and closed source; it never announces a tenant sentinel. +Classification uses the central baseline directly, without tenant overrides or +assertion suppression. The [Database standard](../standards/05-database.md#proposed-global-central-audit-branch) +alone owns canonical typed fields, metadata, grants, policy/function/evidence +predicates and global writer signatures. The [Identity matrix](../modules/identity/audit.md) +owns the one operation row. Subject keys/targets remain linkable personal data; +P03-10 owns locators and truthful retained-copy fulfillment, not this schema step. +`Global_Identity_Creation_Uses_The_Common_Audit_Owner` is implemented in +`IdentityAuditConventionTests` / `GlobalIdentityBootstrapTests`. Physical +COMMIT fault twins, reciprocal preflight refusal and exact duplicate evidence +remain separate from source inspection. + ### Confined event-terminal audit **ADR-0046 fifth seam implemented in P02b-2 Step 2; both review rounds complete.** @@ -213,8 +258,9 @@ Five components, separated concerns: `platform.admin_scope.enter` through `IAuditStore.WritePlatformScopeAsync`, on the scope's own platform-role connection and transaction, **before** the operation runs (§ 7 and [ADR-0044 § 10](../decisions/0044-audit-write-path.md)). It is not four - components but five, and this one is listed here because it is the only class of row - carrying `TenantId.PlatformSentinel`. + components but five in the shipped tenant/platform lifecycle. This platform + population carries `TenantId.PlatformSentinel`; the separately accepted global + identity population uses its qualified prepared owner in Step 3 above. ## 3. The interceptor @@ -752,9 +798,10 @@ and wrote both columns `NULL` on every successful row principal the request carried, or `NULL` when it carried none: a handler's `UserId ?? UserId.SystemActor` for `created_by` attributes the aggregate and is not the audit actor, and an execution that acts as the system carries `UserId.SystemActor` in its own -context. `actor_email` stays `NULL` until the `users` table lands in -[Phase 03](../roadmap/phase-03-identity-admin.md); there is no `users` row to read it from -and `actor_user_id` carries no foreign key. `ip_address` and `user_agent` need HTTP-layer +context. `actor_email` stays `NULL`: the global User foundation stores no email +mirror. [Phase 03 G10](../roadmap/phase-03-identity-admin.md#the-decision-register), +or an earlier proven consumer, must decide its first source/freshness contract; +`actor_user_id` carries no foreign key. `ip_address` and `user_agent` need HTTP-layer enrichment `LearnStack.Application` cannot see — that project references no `Microsoft.AspNetCore.*` package, and must not begin to — so they stay `NULL` until [Phase 03](../roadmap/phase-03-identity-admin.md) adds the request-context port that @@ -1184,14 +1231,11 @@ CREATE INDEX ix_audit_log_correlation_id CREATE INDEX ix_audit_log_module_operation_timestamp ON audit_log (module, operation, timestamp DESC); --- Row security is NOT written here. audit_log carries organization_id, so it is a --- tenant-owned, ORG-SCOPED table and takes the canonical template unmodified: ENABLE --- *and* FORCE, one AND-ed permissive policy with an explicit WITH CHECK, and the two --- AS RESTRICTIVE write guards. That template lives in exactly one document — --- Database Standards § Tenant-Owned and Organization-Scoped Tables — and the last --- time it was copied it shipped broken into four files at once. --- Cross-tenant reads run as learnstack_platform, entered through the audited --- EnterPlatformAdminScope(reason) path. +-- Row security is NOT written here. Database Standards owns the ordinary +-- tenant-owned, ORG-SCOPED template and ADR-0072's accepted exact global-identity +-- insertion/evidence departure. Do not copy either +-- policy here. Ordinary cross-tenant reads retain the audited platform path; +-- the global branch adds only its exact confined owner evidence functions. ``` **Four indexes, and deliberately not the org-scoped template's fifth.** The canonical @@ -1224,8 +1268,10 @@ Accepted records fix a name. The three `CHECK`s and the four indexes take the st the only other divergence on this table is `audit_log_append_only_guard`, which two Accepted records fix in the same way. -The policy shape is [Database Standards § Table classes](../standards/05-database.md)'s, -which also carries `audit_log`'s GRANT-matrix row and the class it belongs to. Two +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) +names the implemented additional exact insertion/evidence arms; +the standard also owns `audit_log`'s grants and class. Two departures from the surrounding tables are stated there and repeated here because a reader of this section will look for them: `audit_log` carries **no foreign key** to `tenants` — the platform-scope row's sentinel tenant deliberately has no `tenants` row, @@ -1246,19 +1292,22 @@ never *authorised by* the payload it describes. See [Database Standards](../standards/05-database.md) for the template and [ADR-0033](../decisions/0033-audit-durability-model.md) for the durability rule. -**Which tenant and organization a row carries**, per +**Which tenant and organization a row carries.** Ordinary tenant rows follow [ADR-0044 § 2](../decisions/0044-audit-write-path.md) and -[Amendment 3 § 2](../decisions/0044-audit-write-path.md). The values are always the ones -the ambient transaction **announced**, because those are the only ones its own `WITH CHECK` -accepts, and they travel on the `AuditIntent` (§ 4) so that the in-transaction write and -its standalone replacement cannot disagree: +[Amendment 3 § 2](../decisions/0044-audit-write-path.md): their scope is the ambient +tenant transaction's announcement, carried on `AuditIntent` (§ 4). Platform rows +retain the separately admitted standalone scope below. +ADR-0072 separately admits the typed global row below; sentinel attribution +never comes from announcing tenant context. Its exact discriminator and owner +guards are specified only in the Database standard: | Request shape | `tenant_id` on the row | `organization_id` on the row | |---|---|---| | Resolved context | `ITenantContext.TenantId` | `ITenantContext.OrganizationId` — `NULL` when the request targets a tenant-wide resource, which is what makes the row's scope follow the resource's | | `IProvisionsTenant` under an unresolved context | `IProvisionsTenant.ProvisioningTenantId` — the value the common transaction coordinator announced | `NULL`, and not by choice: `SetProvisioningTenantContextAsync` announces `app.organization_id` as the empty string, so any other value fails the org-scoped `WITH CHECK` | | No transaction and no resolvable tenant (`EnterPlatformAdminScope`) | `TenantId.PlatformSentinel` | `NULL` — the sentinel has no organizations | -| Unresolved context, not provisioning | no row — there is no tenant whose admin could read it | — | +| Admitted global identity creation/reconciliation owner (implemented in Step 3) | `TenantId.PlatformSentinel`, fixed by central typed composition, never a tenant announcement | `NULL`; exact `identity.user.create` discriminator | +| Ordinary unresolved context, not provisioning/global identity | no row — there is no admitted attribution owner | — | **The third row has exactly one user in Packet 9**: entry into `EnterPlatformAdminScope(reason)` itself, which is not a MediatR request and writes its own @@ -1288,8 +1337,11 @@ already sets, and **not** the nil UUID: all-zero is what three shipped mechanism *no tenant* — `NpgsqlUnitOfWork.SetTenantContextAsync` maps it to the empty string, `SetProvisioningTenantContextAsync` throws on it, and `TenantOwnership.EnsureRealTenant` refuses it in every aggregate factory — and `StronglyTypedId.IsAssigned` reports it -unassigned. Its rows are invisible to every tenant policy and readable only through -`learnstack_platform`. +unassigned. Both named sentinel populations are invisible to ordinary tenant +readers. Platform-scope access remains its separate platform path; global +identity evidence is exposed only through the exact owner functions, with no +app self-audit read or user/tenant endpoint. These global additions are +implemented in Step 3; the tenant announcement guards remain in force. **The sentinel's invariant has an enforcer, and it is not the CHECK.** Packet 9 puts the guard where the value enters: `SetProvisioningTenantContextAsync` refuses @@ -1578,8 +1630,10 @@ the [erasure first-writer prerequisites](23-data-protection.md#erasure-authority before its redaction handler ships. Every module that stores user references in audit payloads registers an -`IUserReferenceLocator`. It lands in [Phase 03](../roadmap/phase-03-identity-admin.md) -with the handler above and the `users` table both depend on, and +`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. @@ -1743,8 +1797,8 @@ update it constrains. `Every_PII_Module_RegistersUserReferenceLocator` is registered in the catalogue against [Phase 03](../roadmap/phase-03-identity-admin.md) and is deliberately **unasserted** until -then: `IUserReferenceLocator` and the `users` table land there with the erasure handler, -and a rule naming types no phase has built could only fail. It is absent from the Packet 9 +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. diff --git a/docs/architecture/32-tenant-customization-model.md b/docs/architecture/32-tenant-customization-model.md index 3593e0d54..ca2b44c54 100644 --- a/docs/architecture/32-tenant-customization-model.md +++ b/docs/architecture/32-tenant-customization-model.md @@ -45,7 +45,7 @@ erDiagram | `tenant_level_taxonomies` | Level/grade/tier flat lists (CEFR, difficulty, kyu/dan, …) | List of items with metadata | | `tenant_scoring_rules` | Assessment scoring expressions | Sandboxed expression DSL | | `tenant_completion_rules` | Lesson / module / course completion logic | Boolean expression DSL | -| `tenant_custom_field_defs` | Extra fields on built-in entities (User, Course, Enrollment) | JSON Schema | +| `tenant_custom_field_defs` | Extra fields on tenant-owned entities (Membership, Course, Enrollment) | Versioned field definitions and JSON Schema | | `tenant_template_library` | Notification templates (email, SMS, WhatsApp, in-app) | Liquid / Handlebars | All eight tables are tenant-owned with RLS isolation (ADR-0003); some are also @@ -382,51 +382,34 @@ sets the rule for page blocks; this document extends it to all customization sur ## 5. Custom fields on built-in entities Tenant-defined custom fields attach to **tenant-owned** entities: `Membership`, -`Course`, `Enrollment`, `LiveSession`, `Lesson`. `target_entity = "User"` resolves to -`membership_profiles` — never to `users`, which is global, carries no `tenant_id`, and -therefore has no query filter and no Row Level Security policy. A tenant-authored -column on a global table is a cross-tenant read by construction -([Phase 03 § Tenant Data Ownership](../roadmap/phase-03-identity-admin.md)). - -```sql -CREATE TABLE tenant_custom_field_defs ( - id uuid PRIMARY KEY, - tenant_id uuid NOT NULL, - target_entity text NOT NULL, -- "Membership", "Course", "Enrollment", …; never "User" - pii_category text NOT NULL, -- PII-Identity | PII-Behaviour | PII-Sensitive | None; no default, see Phase 03 - key text NOT NULL, -- e.g. "preferred_practice_time" - display_name text NOT NULL, - json_schema jsonb NOT NULL, -- field definition - is_required boolean NOT NULL DEFAULT false, - sort int NOT NULL DEFAULT 0, - created_at timestamptz NOT NULL DEFAULT now(), - UNIQUE (tenant_id, target_entity, key) -); -``` - -Values stored on the entity as a JSONB column: - -```sql --- Values live on the tenant-owned row, never on a global one. -ALTER TABLE membership_profiles ADD COLUMN custom_fields jsonb NOT NULL DEFAULT '{}'; -ALTER TABLE courses ADD COLUMN custom_fields jsonb NOT NULL DEFAULT '{}'; --- Every table above is [TenantOwned] and carries the canonical RLS policy from --- Database Standards; `users` is not in this list and never will be. --- etc. -``` - -Query helpers: - -```csharp -public static class CustomFieldExtensions -{ - public static T? GetCustomField(this User user, string key) - => user.CustomFields.TryGetProperty(key, out var v) ? v.Deserialize() : default; - - public static void SetCustomField(this User user, string key, T value) - => user.CustomFields = JsonExtensions.Set(user.CustomFields, key, value); -} -``` +`Course`, `Enrollment`, `LiveSession`, `Lesson`. Phase 03 admits `Membership` +first, storing values in `membership_profiles.custom_fields`, never global +`users`. A tenant-authored column on a global table has no tenant isolation +([Phase 03 § Tenant Data Ownership](../roadmap/phase-03-identity-admin.md#tenant-data-ownership-dsar-boundary-and-pii-classification)). +`User` is not a new-write target; any legacy label/migration input requires an +explicit bounded decision before admission. + +Customization owns the definition aggregate; the target module owns its values +and consumes definitions through an application contract. The definition holds +target/key, required PII category, schema, localized label and required/sort +metadata. Its revision and value-pin shape follows the immutable-version boundary +in § 4 and closes in +[Phase 03 G9](../roadmap/phase-03-identity-admin.md#the-decision-register) before +the first migration. An unversioned tenant/target/key uniqueness constraint cannot +stand in for definition history or the single-active-definition constraint. + +G9 decides required-field introduction, unknown/null/default values, retirement, +key reuse, classification changes, nested values and sensitive-consent evidence. +Retiring a definition cannot leave stored PII invisible to export/redaction. Field +schema admission also reconciles scalar types with the existing nonempty +root-properties profile; it never bypasses `IJsonSchemaValidator`. + +Readers and writes use the target module's authorized membership/entity contract. +A generic `SetCustomField(User, ...)` helper is not a write path: it would restore +global storage and skip schema, scope, concurrency and audit admission. Canonical +DDL lands with its owning module migration under +[Database Standards](../standards/05-database.md); no illustrative DDL here grants +permission to omit version pins, audit columns or isolation. Custom fields are rendered in the same primitive-composing way: the field's `json_schema` maps to a primitive, the entity's Admin Studio detail page composes a form, the entity's diff --git a/docs/architecture/33-cross-cutting-concerns.md b/docs/architecture/33-cross-cutting-concerns.md index 6245b4cd0..af6a64603 100644 --- a/docs/architecture/33-cross-cutting-concerns.md +++ b/docs/architecture/33-cross-cutting-concerns.md @@ -6,6 +6,8 @@ [ADR-0044](../decisions/0044-audit-write-path.md), [ADR-0065](../decisions/0065-bounded-tenant-assertion-diagnostics.md), [ADR-0066](../decisions/0066-bounded-tenant-subject-admission.md), +[ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md), +[ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md), [ADR-0020](../decisions/0020-triple-deployment-hybrid-license.md). For the day-to-day rules read [09-error-handling.md](../standards/09-error-handling.md), [10-observability.md](../standards/10-observability.md), and @@ -132,8 +134,19 @@ endpoint and structural dispatch/Off/persistence controls; Education eligibility and contract proof remain Steps 3–4. The eight-stage order, normal writer ownership and independent rejected-assertion audits are unchanged. +Accepted ADR-0072/0073 add a common prepared global-identity owner in P03-1 +Step 3. It uses distinct authority-kind +enrollment, serializes the subject before a typed creation intent and consumes +one prepared physical owner through the common transaction/capture coordinator. +Global and tenant owners cannot join or retarget one another. The central audit +composer alone emits the typed global metadata/creation reference; successful +User/audit reciprocity and exact non-success evidence use the canonical +[Database contract](../standards/05-database.md#proposed-global-central-audit-branch). +This extension adds no MediatR stage or HTTP/new-user BFF route. P03-3 owns that +activation; the current complete native profile and ordinary pipeline remain. + [ADR-0032 § Sub-decision 2](../decisions/0032-exception-handling-logging-and-observability.md) -binds the order. Reading bottom-most as innermost: +binds the ordinary pipeline order. Reading bottom-most as innermost: ```text Request @@ -227,9 +240,11 @@ Why this order: asserts, or, for a provisioning request, from the request itself — which is safe for that reason rather than in spite of it: it is the same value that drove the session variable, so the database refuses the write when the two disagree. - [ADR-0044 § 2](../decisions/0044-audit-write-path.md) tabulates all four shapes, - including the platform-scope row's `TenantId.PlatformSentinel` and the unresolved - non-provisioning request, which writes no row at all. `TenantContextBehavior` + [ADR-0044 § 2](../decisions/0044-audit-write-path.md) tabulates the four original shapes, + including the platform-scope row's `TenantId.PlatformSentinel` and the ordinary + unresolved non-provisioning request, which writes no row. The separately + admitted global creation owner carries typed attribution under ADR-0072, + never a synthetic tenant context or ordinary sentinel writer. `TenantContextBehavior` *only* validates the context — it asserts the middleware populated it. It does **not** set the PostgreSQL session variables: `SET LOCAL` is transaction-local and step 4 runs before any transaction exists, so the diff --git a/docs/decisions/0003-tenant-isolation-defense-in-depth.md b/docs/decisions/0003-tenant-isolation-defense-in-depth.md index a1356c539..9b2afff89 100644 --- a/docs/decisions/0003-tenant-isolation-defense-in-depth.md +++ b/docs/decisions/0003-tenant-isolation-defense-in-depth.md @@ -503,3 +503,24 @@ inventory reader. Canonical SQL/grants remain in Database Standards at implement this disclosure copies none. Tenant/org RLS, FORCE, exact grant confinement and platform-admin entry/pre-entry audit retain their contracts. P02b-4 implementation and role/storage proofs remain pending. + +## Amendment 9 — Global self-identity isolation (2026-10-25) + +**Status: Accepted.** Joint acceptance of +[ADR-0072](0072-application-owned-identity-bootstrap.md) and +[ADR-0073](0073-scoped-membership-and-identity-data-foundation.md) adds global +self-identity as a seventh table class and its platform-scoped authority anchor. +[Database Standards](../standards/05-database.md) owns the canonical FORCE-RLS +policy arms, immutable binding guards, same-module tenant-to-global User reference +and exactly five confined owner functions. + +The global class and central audit extension use one permissive isolation policy +per relation with role-qualified USING arms and explicit WITH CHECK. Those arms +are not SELECT-only policies; command grants and the named mutation/DELETE/ +TRUNCATE guards supply their separate bounds. The functions add explicit runtime +owner execution under FORCE RLS without a runtime migration credential. The +ordinary tenant/org template and four login roles remain unchanged. + +This is a bounded extension of this ADR's table/role model, not a correction of +its historical body. Authority is accepted; P03-1 Steps 3/4 still own applied +schema, owner-function and real app-role isolation proofs. diff --git a/docs/decisions/0010-cross-module-communication.md b/docs/decisions/0010-cross-module-communication.md index 01f945b7c..87a6729d2 100644 --- a/docs/decisions/0010-cross-module-communication.md +++ b/docs/decisions/0010-cross-module-communication.md @@ -182,3 +182,22 @@ The four cross-module mechanisms and own-module scheduling boundary remain. Validated tenant/org context precedes business construction/execution. The named submission/restoration catalogue replacements and their enforcement land in P02b-4; this acceptance claims no runtime or test delivery. + +## Amendment 5 — Confined identity creation witness SQL (2026-10-25) + +**Status: Accepted.** [ADR-0072](0072-application-owned-identity-bootstrap.md) +admits the enumerated `IdentityCreationWitnessInstaller` persistence contract: +reciprocal User/central-audit creation guards and exact evidence reads over the +declared creation-key and discriminator fields. Its canonical boundary is in +[Database Standards](../standards/05-database.md). + +Central infrastructure contains that fixed SQL without module entity or assembly +imports. The Identity migration invokes the central installer without copying +audit SQL into Identity migration or handler source. This is the only new +structural SQL exception to the Decision's cross-module SQL prohibition; +business cross-module joins and a fifth application communication mechanism +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. diff --git a/docs/decisions/0017-tenant-organization-hierarchy.md b/docs/decisions/0017-tenant-organization-hierarchy.md index c432466d4..c816fd549 100644 --- a/docs/decisions/0017-tenant-organization-hierarchy.md +++ b/docs/decisions/0017-tenant-organization-hierarchy.md @@ -437,3 +437,21 @@ TenantWide retains a NULL organization, Organization retains its exact organizat and neither grants all-organization or platform authority. The hierarchy, normal composite point lookups and canonical tenant/org RLS remain. P02b-4 implementation and isolation proofs remain pending. + +### Amendment 4 — Membership roots and scoped capability templates (2026-10-25) + +**Status: Accepted.** [ADR-0073](0073-scoped-membership-and-identity-data-foundation.md) +defines Membership as the root of one scoped profile and its assignments, and +Role as a tenant-wide capability template. The +[Identity specification](../modules/identity/README.md) owns the model; +[Permission Standards](../standards/19-permissions.md) owns scope compatibility. + +Organization grants apply only through an exact Organization Membership. +Tenant-wide storage of a template confers neither cross-branch authority nor +authoring rights. Effective tenant grants plus matching-organization grants +retain this ADR's hierarchy; another organization's grants do not contribute. +Tenancy continues to own Organization lifecycle. + +Joint ADR-0072/0073 approval accepts the foundation contract. P03-1 Step 4 owns +schema, seed, lifecycle and scope proofs; P03-2 owns live membership/permission +consumption. This amendment supplies no evidence of those runtime deliveries. diff --git a/docs/decisions/0033-audit-durability-model.md b/docs/decisions/0033-audit-durability-model.md index 25eb03e66..e2d86af08 100644 --- a/docs/decisions/0033-audit-durability-model.md +++ b/docs/decisions/0033-audit-durability-model.md @@ -801,3 +801,30 @@ The two closed callers are app-role failure finalization and confined bypass terminalization. Uncertain COMMIT is durably reconciled before retry. Existing five write contracts, standalone restrictions, MUST durability and classification remain. P02b-4 implements/proves the seam; acceptance claims no terminal-audit runtime. + +## Amendment 11 — Prepared global identity audit ownership (2026-10-25) + +**Status: Accepted.** [ADR-0072](0072-application-owned-identity-bootstrap.md) +extends central MUST creation and reconciliation to exact prepared global +identity owners without a resolved tenant context. This population does not +inherit the ordinary unresolved path's silent no-intent outcome. The canonical +owner, capture and creation-reference contract is in +[Database Standards](../standards/05-database.md). + +Serialized subject lookup precedes allocation and intent declaration. Only +absence opens the common audit frame and its immutable creation-reference +handoff; an existing binding returns without a creation intent. The original +prepared owner completes the User and central success audit on one transaction. +The common coordinator and composer own captured global attribution and every +outcome; no Identity-owned audit writer or provider transaction is added. + +After final writes, precommit constraint validation precedes commit admission. +Known precommit refusal follows rollback and failed reconciliation; a lost +physical COMMIT acknowledgement remains uncertain. Non-success reconciliation +preserves captured attribution and intent ID with a fresh standalone timestamp. +It requires no User witness and proves neither User absence nor business success. +Existing MUST durability, refusal posture and independently owned cleanup remain. + +Joint ADR-0072/0073 acceptance grants this bounded authority. P03-1 Step 3 still +must prove same-transaction success, precommit refusal, unknown COMMIT and exact +evidence under the actual app role. diff --git a/docs/decisions/0036-tenant-resolution-trusted-inputs.md b/docs/decisions/0036-tenant-resolution-trusted-inputs.md index 19ac6c0c0..1bf954883 100644 --- a/docs/decisions/0036-tenant-resolution-trusted-inputs.md +++ b/docs/decisions/0036-tenant-resolution-trusted-inputs.md @@ -1263,3 +1263,24 @@ owns subsequent implementation and proof status; acceptance does not deliver it. - [architecture/13 Identity and Auth](../architecture/13-identity-and-auth.md) - [architecture/14 Frontend Architecture](../architecture/14-frontend-architecture.md) - [architecture/30 API Gateway](../architecture/30-api-gateway.md) + +### Amendment 15 — Existing-binding admission before tenant resolution (2026-10-25) + +**Status: Accepted.** [ADR-0072](0072-application-owned-identity-bootstrap.md) +inserts quota-before-binding and route-independent existing-binding normalization +before ordinary tenant reconciliation. Verified provider-subject admission does +not itself supply a tenant context or permission. No new HTTP endpoint, context +writer or unresolved-context marker is admitted by this change. + +[ADR-0073](0073-scoped-membership-and-identity-data-foundation.md) separately names +`PreContextIdentityAuthorizationReader`: a short physically READ ONLY app-role +candidate read with no `ITenantContext`. Its exact candidate tenant/organization, +HostScope restrictions and claim-only mismatch evidence follow the canonical +[Security Standards](../standards/11-security.md) contract. Live decision-table +rows and this reader's execution remain P03-2 work; registration does not make +them delivered. + +Joint approval accepts these bounded contracts while preserving route invariance, +host authority and the existing resolution matrix. P03-1 Step 5 owns actual +existing-binding admission proofs. New-user HTTP/BFF entry remains subject to +P03-3 acceptance and activation. diff --git a/docs/decisions/0040-ambient-unit-of-work.md b/docs/decisions/0040-ambient-unit-of-work.md index a95b901b4..e054e97fd 100644 --- a/docs/decisions/0040-ambient-unit-of-work.md +++ b/docs/decisions/0040-ambient-unit-of-work.md @@ -767,3 +767,28 @@ The original body, metadata and prior amendments remain verbatim. Updated acceptance carriers are this amendment, ADR-0052's own amendment and Standards 11; ADR-0064 and the package own the full register. Implementation/proofs remain P02b-5, including physical write refusal on the authenticated query's actual path. + +### Amendment 14 — Prepared global owners and candidate-reader registration (2026-10-25) + +**Status: Accepted.** [ADR-0072](0072-application-owned-identity-bootstrap.md) +adds common global read, prepared creation, fixed seed-adoption and reconciliation +owners. Exact identity announcements bind the real connection, transaction and +generation; one-shot prepared completion retains the original physical owner. +The common audit/capture and transaction coordinators own those lifetimes. + +Tenant/global authority kinds cannot join or retarget, including same +ReadOnly/ReadWrite modes. The new transaction-local +`app.identity_authority_id` and `app.identity_subject_key` form a separate +identity-announcement census; neither is a sentinel tenant announcement. +[Database Standards](../standards/05-database.md) owns preparation, declaration, +completion and cleanup ordering. + +[ADR-0073](0073-scoped-membership-and-identity-data-foundation.md) registers the +planned ninth logical tenant setter, `PreContextIdentityAuthorizationReader`. +It executes only with the P03-2 live candidate reader: exact candidate tenant/org, +a fresh physically READ ONLY app transaction and no ambient `ITenantContext`. +The current eight tenant setters are not made nine implemented setters by this +registration. [Security Standards](../standards/11-security.md) owns that census. + +Joint approval accepts the authority. P03-1 Steps 3/5 retain the global owner and +existing-binding runtime proofs; P03-2 retains the ninth setter's live proofs. diff --git a/docs/decisions/0044-audit-write-path.md b/docs/decisions/0044-audit-write-path.md index 5822227bf..e5a04f735 100644 --- a/docs/decisions/0044-audit-write-path.md +++ b/docs/decisions/0044-audit-write-path.md @@ -1232,3 +1232,33 @@ Existing five write contracts and MUST same-transaction durability remain. The conditional routing/status exemption is held by ADR-0047, not a general background or privileged exemption. P02b-4 implements/proves the seam, exclusions and catalogue registration; acceptance claims none delivered. + +## Amendment 14 — Global identity attribution and central write seams (2026-10-25) + +**Status: Accepted.** [ADR-0072](0072-application-owned-identity-bootstrap.md) +narrowly extends §§ 1/2/3/5/9/10 with a second sentinel attribution population: +`identity.user.create`, MUST/SecurityEvent, carrying typed captured global +identity attribution. `TenantId.PlatformSentinel` remains storage attribution, +never tenant authority. [Database Standards](../standards/05-database.md) owns +its complete discriminator, prepared owner and shared composer contract. + +`WriteGlobalIdentityPending` and `ReconcileGlobalIdentity` extend the existing +six central audit write seams to eight. Ordinary pending, standalone, +best-effort and tenant entry refuse this population; platform entry rejects its +identity discriminator. The pending path gains an explicit refusal before SQL; +this is a required implementation change, not a claim that its current guard +already exists. No handler supplies arbitrary audit metadata or a private writer. + +Global success requires reciprocal User/audit creation evidence and constraint +validation before commit admission. Known precommit refusal differs from unknown +physical COMMIT. For this population, `23505` alone proves no outcome: evidence +must match the exact composite key, source, subject, target, discriminator and +outcome. A fresh non-success row proves only its own durability, without a User +witness or a claim of User absence/success. This rule does not generalize the +ordinary standalone path's existing duplicate shortcut to global identity. + +Fixed central witness SQL receives only +[ADR-0010 Amendment 5](0010-cross-module-communication.md#amendment-5--confined-identity-creation-witness-sql-2026-10-25)'s +installer/evidence exception. Existing append-only, redaction and retention +authority remains unchanged. Joint ADR-0072/0073 approval accepts these bounds; +P03-1 Step 3 still owns the actual writer, mode-refusal, guard and evidence proofs. diff --git a/docs/decisions/0062-native-crash-proof-ci-provisioning.md b/docs/decisions/0062-native-crash-proof-ci-provisioning.md index caf286803..fa691f9e9 100644 --- a/docs/decisions/0062-native-crash-proof-ci-provisioning.md +++ b/docs/decisions/0062-native-crash-proof-ci-provisioning.md @@ -325,6 +325,24 @@ owns progress and actual final-source qualification; the ordinary membership-I/O fault remains independent corrective work under this record. This amendment rewrites none of the Accepted body, date or acceptance metadata above. +### Amendment 2 — Ordinary Docker execution window (2026-10-27) + +Accepted [ADR-0075](0075-ordinary-ci-job-window.md) supplies an +ordinary-only exception to Amendment 1's statement, “All execution jobs keep twenty-minute ceilings”. Verified +ordinary Docker producers have a twenty-five-minute whole-job ceiling; +native, base and Architecture execution retain twenty minutes. +[ADR-0063](0063-complete-bounded-ci-test-shards.md) receives its own dated amendment for the same bounded change. + +Native collector authority, excluded-host rules, process/Docker ownership, +unchanged cleanup/export/upload reserve, complete result requirements and +the other decisions above remain intact. Expected verified producer identity +controls the longer observation/whole-job window; no receipt chooses it. +Acceptance is not implementation or actual hosted fit. ADR-0075 and the +[Phase 03 delivery log](../roadmap/phase-03-delivery-log.md#adr-0075-acceptance-and-step-1-2026-10-27) +own the dependent implementation and fresh two-layout qualification receipts. The historical text, metadata and Amendment 1 are +retained without rewriting. This is a bounded decision change, not an +ADR-0041 factual correction. + ## References - [ADR-0060](0060-fatal-hangfire-startup-and-unsafe-unwind.md#diagnostics-dumps-and-durable-consequences). diff --git a/docs/decisions/0063-complete-bounded-ci-test-shards.md b/docs/decisions/0063-complete-bounded-ci-test-shards.md index b9e799737..d5899e2b6 100644 --- a/docs/decisions/0063-complete-bounded-ci-test-shards.md +++ b/docs/decisions/0063-complete-bounded-ci-test-shards.md @@ -453,6 +453,32 @@ an initial 30-second allocation for the new offline controls is a proposed budge not a measured increment. Remove no existing check and claim no fit until actual final-source meta passes with the new controls. +## Amendments + +### Amendment 1 — Ordinary Docker whole-job window (2026-10-27) + +Accepted [ADR-0075](0075-ordinary-ci-job-window.md) supplies an +ordinary-only exception to the Decision's “Each execution keeps its twenty-minute whole-job ceiling” and the rule, +“Keep each twenty-minute ceiling and a finite cleanup/upload reserve.” +Verified ordinary Docker producers instead have a twenty-five-minute +whole-job ceiling. This also qualifies the inherited ordinary requirement +in the Exact relationship to ADR-0062 section; +[ADR-0062](0062-native-crash-proof-ci-provisioning.md) receives its own dated +amendment. Native, base and Architecture retain twenty minutes. +The plan's prohibition on unapproved ceiling increases keeps only this +explicitly approved ordinary exception. + +All other decisions remain in force: producer count ranges and the +twenty-VM cap, selector ownership and two-layout qualification, +algorithm/salt/weights/filters, resource ownership/accounting, the +unchanged cleanup/export/upload reserve, other job ceilings and the +seven required names. Expected verified producer identity controls the +longer enclosing interval; a receipt cannot choose it. Actual operation +deadlines remain unchanged. Acceptance authorizes dependent work, not +actual hosted fit; the +[Phase 03 delivery log](../roadmap/phase-03-delivery-log.md#adr-0075-acceptance-and-step-1-2026-10-27) +owns its implementation and qualification receipts. Historical text and metadata remain intact. + ## References - [ADR-0062](0062-native-crash-proof-ci-provisioning.md). diff --git a/docs/decisions/0064-tenant-api-authentication-boundary.md b/docs/decisions/0064-tenant-api-authentication-boundary.md index 6e7e26f8f..5fe176292 100644 --- a/docs/decisions/0064-tenant-api-authentication-boundary.md +++ b/docs/decisions/0064-tenant-api-authentication-boundary.md @@ -598,3 +598,23 @@ This clarification preserves the original Status, Decision, date, deciders and rationale. The [decision index](README.md) links this clarification; the [systematic correction record](../roadmap/phase-02b-delivery-log.md#p02b-5-systematic-proof-and-document-corrections-2026-10-20) owns the associated mutable-carrier reconciliation. No decision changes. + +### Amendment 4 — Verified subjects and existing application bindings (2026-10-25) + +**Status: Accepted.** [ADR-0072](0072-application-owned-identity-bootstrap.md) +replaces required API wire `user_id` with stock-verified provider-subject admission +followed by existing-binding normalization. An optional wire actor is consistency +evidence; a conflicting, malformed or reserved actor refuses. Credential +enforcement recognizes the verified stage, and the unchanged issuer/sub quota +precedes binding SQL. + +Unknown, conflicting, Closing/Closed or unavailable bindings uniformly return +401 without allocation. Remaining token checks, route invariance, the closed +GET/HEAD surface, public anonymity and AccountSite's absent-token 404/valid-token +wrong-method 405 remain. No optional API actor claim weakens the native complete +identity or AccountSite publication witness. + +Joint ADR-0072/0073 approval accepts this bounded authentication change. P03-1 +Step 5 owns provider/app-role admission, lookup load, pool, cancellation and +store-failure proofs. P03-3 needs separate acceptance before new-user HTTP/BFF +activation; no new endpoint is authorized here. diff --git a/docs/decisions/0065-bounded-tenant-assertion-diagnostics.md b/docs/decisions/0065-bounded-tenant-assertion-diagnostics.md index c61effb16..95b145bb8 100644 --- a/docs/decisions/0065-bounded-tenant-assertion-diagnostics.md +++ b/docs/decisions/0065-bounded-tenant-assertion-diagnostics.md @@ -366,3 +366,15 @@ The [decision index](README.md), [glossary](../glossary.md), Standards [Tenancy audit matrix](../modules/tenancy/audit.md) now state delivered status and distinguish separate admitted rows from suppressed occurrences. This changes no allowance, audit classification, signal vocabulary or HTTP disposition. + +### Amendment 4 — Global creation remains outside mismatch allowances (2026-10-25) + +**Status: Accepted.** This is navigation to jointly accepted +[ADR-0072](0072-application-owned-identity-bootstrap.md) and its central global +MUST identity creation contract. That population receives no host-tenant mismatch +allowance or suppression. The independently defended-host admission key, budget, +failed-attempt accounting and refusal behavior in this ADR remain unchanged. + +P03-1 Step 3 owns the new global audit proofs and Step 5 its admission integration; +joint authority acceptance supplies neither runtime evidence nor an expanded +mismatch budget. diff --git a/docs/decisions/0066-bounded-tenant-subject-admission.md b/docs/decisions/0066-bounded-tenant-subject-admission.md index 5c72d8425..93862dc46 100644 --- a/docs/decisions/0066-bounded-tenant-subject-admission.md +++ b/docs/decisions/0066-bounded-tenant-subject-admission.md @@ -384,3 +384,20 @@ Original Accepted body and metadata remain intact. The decision index, - [Current limiter](../../backend/src/LearnStack.Api/Authentication/TenantSubjectRateLimiter.cs) and [middleware](../../backend/src/LearnStack.Api/Authentication/TenantSubjectAdmissionMiddleware.cs); [Common 503 retry policy](../../backend/src/LearnStack.Api/Common/RetryAfter.cs). + +### Amendment 3 — Verified-subject input before application binding (2026-10-25) + +**Status: Accepted.** [ADR-0072](0072-application-owned-identity-bootstrap.md) +changes the input stage to admit stock-verified provider subjects before +application-binding access. The population can include a subject with no wire +actor or existing User; passing quota establishes neither binding nor permission. + +The issuer/sub key, numeric bounds, once-per-request debit, reexecution behavior, +cleanup/fault ownership and non-reset contract remain unchanged. The registry +bounds retained limiter state; it bounds neither permanent Users nor audit rows. +No binding lookup or allocation resets a subject's allowance. New-user HTTP +creation is not activated by this broader admission population. + +Joint ADR-0072/0073 approval accepts this input-stage change. P03-1 Step 5 retains +actual admission, failure, cancellation and load qualification; prior limiter +proofs do not establish the new integration by themselves. diff --git a/docs/decisions/0070-owned-tenant-bff-sessions.md b/docs/decisions/0070-owned-tenant-bff-sessions.md index 3521355a6..135d58cf3 100644 --- a/docs/decisions/0070-owned-tenant-bff-sessions.md +++ b/docs/decisions/0070-owned-tenant-bff-sessions.md @@ -548,3 +548,19 @@ This HTTP presentation does not alter publication, grant replay or revocation. The earlier Registered-until-shipped wording records acceptance-time status; the [catalogue](../standards/21-architecture-tests-catalogue.md#p02b-7-tenant-bff-obligations) owns current control status. + +### Amendment 4 — Existing-session identity foundation navigation (2026-10-25) + +**Status: Accepted.** Jointly accepted +[ADR-0072](0072-application-owned-identity-bootstrap.md) preserves P03-1's complete +native identity, ID-token/AccountSite association and publication/refresh fences. +Native opaque-subject validation aligns with the API's 255-character bound, +without trimming or case folding. Optional API wire-actor evidence does not make +a tenantless or actorless native session complete. + +The current native operations and authenticated AccountSite seam remain. An +optional pre-session identity, new-user bootstrap association and truthful +no-session completion remain unaccepted P03-3 changes; no new HTTP/BFF operation +is activated here. P03-1 Step 5 still owns the subject-bound and existing-session +integration proofs. This navigation and bounded validation alignment supply no +new session authority or runtime receipt. diff --git a/docs/decisions/0071-uncertain-account-site-refusals.md b/docs/decisions/0071-uncertain-account-site-refusals.md index 390325b62..efde0133f 100644 --- a/docs/decisions/0071-uncertain-account-site-refusals.md +++ b/docs/decisions/0071-uncertain-account-site-refusals.md @@ -246,3 +246,15 @@ The current public/protected API discovery-failure control is `Discovery_failure_on_actual_public_and_account_routes_is_401_and_never_anonymous` in the [HTTP tests](../../backend/tests/LearnStack.Tests.Integration/TenantAuthenticationHttpTests.cs). The original decision, metadata and source observations remain historical. + +### Amendment 2 — Binding uncertainty preserves ordinary read refusals (2026-10-25) + +**Status: Accepted.** This is navigation to jointly accepted +[ADR-0072](0072-application-owned-identity-bootstrap.md). Its additional +binding-store uncertainty source preserves this ADR's ordinary-read refusal +table: an ordinary 401 remains identity-indeterminate and supplies no +identity-refusal witness. + +No automatic retry, refresh, bearer substitution or changed AccountSite outcome +mapping follows. P03-1 Step 5 must prove the new binding failure reaches the +existing refusal contract; acceptance does not claim that integration delivered. diff --git a/docs/decisions/0072-application-owned-identity-bootstrap.md b/docs/decisions/0072-application-owned-identity-bootstrap.md new file mode 100644 index 000000000..86c6b72a8 --- /dev/null +++ b/docs/decisions/0072-application-owned-identity-bootstrap.md @@ -0,0 +1,321 @@ +# ADR-0072: Application-Owned Identity Bootstrap + +## Status + +Accepted — jointly with ADR-0073 on 2026-10-25. Runtime qualification remains +pending the six implementation steps. + +**Date:** 2026-10-25 +**Deciders:** @cemil + +**Bounded supersession:** The carrier table identifies each changed rule. This +is a new decision, not an ADR-0041 factual correction. Joint acceptance replaces +only the named rules through dated Amendments pointing here. +Existing Accepted bodies, statuses and dates remain historical. + +## Decision Drivers + +- New provider accounts have no application actor. Requiring `user_id` before + allocating it creates a cycle that seed attributes cannot solve. +- One application database can allocate actor and central MUST audit without + provider plugins, administrator credentials or cross-system identity writes. +- Global identity needs explicit self-confined SQL/audit authority; a missing + tenant, marker or SystemActor supplies none. +- The first schema must preserve continuity, deny post-closure recreation, + minimize raw identity and refuse accidental issuer replacement. +- Success, failure and unknown COMMIT need executable write/evidence-read + contracts under FORCE RLS before migration. + +## Considered Options + +1. **Application binding and exact self bootstrap** (chosen). One verified + subject receives one actor; ordinary reads never allocate. P03-1 implements + storage/common creation authority and fixed seed adoption. P03-3 decides and + activates new-user HTTP/BFF entry with its usable membership journey. +2. **Provider allocator or runtime Admin API/reissue** (rejected). Adds provider + machinery, credentials and recovery merely to establish application identity. +3. **Invitation-only provisioning** (not selected). An enrollment policy rather + than a complete identity mechanism. P03-4 owns its separate verified-email act. +4. **AllowsUnresolvedTenantContext alone** (rejected). It authorizes no provider + credential, subject quota handoff, global SQL owner or global audit. Use a + separate exact global-self descriptor; keep the provisioning marker closed. +5. **Separate global attribution UUID/audit table** (rejected). Another UUID adds + permanent reservations and token/context/event/job guards without solving SQL + authority. Another table splits central audit ownership. Instead explicitly + extend PlatformSentinel with two distinguished populations and exact seams. +6. **Admission projection or fifth minimal role** (not selected). A projection + needs atomic state synchronization/recovery; another role adds credentials and + pools. Select enumerated owner functions, accepting their execution privilege. +7. **HMAC lookup or permanent raw subject** (not selected). HMAC adds key custody, + rotation and restore; it does not anonymise linkage. Raw subject need not + survive closure. Use an access-controlled digest with guessing risk explicit. +8. **503/refusal witness on all binding outages** (not selected). Preserve the + ADR-0064/0071 uniform ordinary 401 contract. Bootstrap has its separate typed + storage-failure result; this is not evidence of invalid credentials. + +## Decision + +- LearnStack binds one verified provider subject to one stable UUIDv7 actor. + `user_id` becomes optional consistency evidence; present conflict/malformed + values refuse. Only an admitted creation owner creates a binding; P03-1 exposes + that authority to the fixed seed owner, not an HTTP operation. +- A deployment-pinned authority and permanent digest preserve identity independently + of issuer URL. Active accounts retain exact subject for collision checking; + authorized closure removes it and retains the nonauthorizing tombstone. +- One global-self transaction and central MUST audit commit together. Narrow + success/reconcile seams and evidence functions extend central durability; + PlatformSentinel gains a second, explicitly distinguished row class. +- Verified provider-subject admission precedes binding access. Bootstrap supplies + no tenant context, membership, Platform permission or tenant BFF session. + +## Context + +### Source and credential handoff + +At `92117893`, TenantTokenProfile requires actor; ValidatedTenantIdentity has a +nonnullable actor; quota consumes that type through TenantCredentialFeature. +Its key is issuer/sub, but the shipped path cannot accept actorless tokens. +Identity remains scaffolded at that source. The following is the accepted +replacement contract; implementation and database qualification are pending. + +New API-owned `VerifiedProviderSubject` contains the stock-verified issuer/sub, +optional actor and optional scalar tenant/org claims. TenantCredentialFeature +carries this stage separately from normalized ValidatedTenantIdentity. Only +existing-binding resolution creates the latter. Quota consumes the former +before **any** authenticated request's binding SQL. Preserve 600/minute, 4096-entry +ownership/fault protocol, visitor/peer floors, once-per-request debit and +reexecution behavior. No request payload selects a subject or resets its quota. + +All remaining JOSE/signature/purpose/audience/time/security-property checks stay. +API and native ID-token validation use exact ordinal opaque sub, bounded to 255 +characters, without trimming/case folding. The native profile still requires +actor/tenant and the existing AccountSite witness in P03-1. Optional API actor +evidence does not make a tenantless native session valid. + +| Verified subject / binding | Ordinary API | Internal creation owner | +|---|---|---| +| Active; actor absent/equal | Resolve stored actor | Return stored actor | +| Actor conflict/malformed/reserved | 401, no mutation | Typed identity refusal; no mutation | +| Unknown; actor absent | 401, no mutation | Serialize and allocate once when independently admitted | +| Unknown; actor present | 401, no adoption | Only fixed, separately witnessed seed adoption may preserve its actor | +| Closing/Closed | 401, no recreation | Typed nonadmitting-binding refusal; no recreation | +| Binding unavailable | Uniform 401 | Typed storage failure, no asserted success | + +No P03-1 identity/eligibility cache is installed. Each authenticated admission +reads committed binding state; provider key caching remains separate. Anonymous +public reads do no identity lookup. Closed diagnostic reasons distinguish +binding storage/authority faults without enriching the 401 body/challenge. +Internal creation explicitly translates storage/audit failures to bounded typed +results. Its future HTTP mapping is a P03-3 decision. Preserve already refused, +cancelled and uncertain outcomes. + +### Activation boundary + +The maintainer selects P03-3 for new-user HTTP bootstrap and BFF entry. P03-1 adds +no POST, SDK operation, endpoint-dependent resolver, global MediatR marker or +native no-session completion. AllowsUnresolvedTenantContext and its provisioning +allowlist remain closed. Current public/AccountSite routes, missing-token rules, +wrong-method outcomes and complete native identity remain unchanged. + +P03-1's actual consumers are fixed seed adoption and existing-session admission. +Its common creation/audit contract receives real PostgreSQL/provider proofs, +without exposing a new creation route. Every ordinary request follows one +route-independent credential/quota/binding sequence, canonically owned by +[Security](../standards/11-security.md#proposed-p03-1-identity-admission-annex). + +P03-3/G1/G6 must decide provider registration and durable creation budgets before +activation, explicitly supersede ADR-0064's route-invariance prohibition if a +global operation needs it, and define its own API/native outcome table. It must +distinguish session publication from identity-created-without-session, including +cookie/transaction cleanup, and prove grant/issuer/subject association. No retry +may infer rollback from a missing response. Those are future acceptance gates, +not an approved transport design hidden in this foundation ADR. ADR-0053/0070 +caller and publication changes wait for that package. Refresh never allocates. + +### Authority, retention and concurrency + +[Database Standards](../standards/05-database.md#proposed-p03-1-identity-storage-annex) +is the canonical owner of columns, GUCs, digest encoding, grants, +policy/function signatures, lock deadlines and evidence predicates. Do not copy SQL. + +`identity_authority` is a singleton platform-scoped registration installed once +by deployment/migration tooling before bootstrap. Stable AuthorityId names the +exact issuer. Runtime app reads but cannot install/replace/edit it. Missing or +mismatched registration refuses before allocation. P03-9/G13 owns a frozen- +admission, privileged issuer rebind after proven provider continuity, preserving +AuthorityId, actors, keys and closed tombstones. Until it ships, rename is +unsupported; a changed URL never silently allocates a new identity domain. + +User lookup is AuthorityId plus canonical subject digest. Active requires raw +subject; Closing keeps it only while fulfillment needs it; Closed removes it. +Active digest/raw mismatch refuses, never aliases. A closed matched key always +denies, including a hypothetical collision. Inherited soft-delete fields stay +NULL: closure is lifecycle, not recycling. No email/verification or unused global +profile fields land here. P03-6/G10, or an earlier proven consumer, owns the first +mirror schema/source/freshness decision. + +The common prepared global owner acquires subject serialization and freshly +checks the binding before handler construction or intent declaration. Only +serialized absence opens the common audit frame and allocates a target plus +creation-audit reference. Ordinary AuditLog-before-Transaction execution cannot +supply that order unchanged; Standard 05 names the prepared-owner extension, +central attribution/key port and precommit constraint validation. Existing +bindings return without a mutation intent. Genuine failures/unknown COMMIT retain +central reconciliation. No unrestricted new-subject route is activated here; +the 4096 retained limiter partitions never bound permanent User cardinality. + +Creation, reactivation and all assignment additions use the canonical User fence. +Standard 05 alone owns lock keys, shared/exclusive tenant modes, fresh reads and +deadlines; handlers and database guards must implement the same contract. +Unknown and nonadmitting ids produce the same false result. No function projects +a profile. Later closure/status writers share the tenant invariant locks before +making an administrator ineligible; their workflow remains P03-10. + +### Audit and owner privilege + +PlatformSentinel ceases to identify operator events uniquely. Operation/source +distinguishes platform-scope standalone rows from `identity.user.create` global +MUST SecurityEvent. No tenant setter announces the sentinel. Ordinary audit +methods must reject it explicitly before SQL; current WritePendingAsync lacks +that check and must gain it before the new policy branch is admitted. Only the +named global pending/reconcile seams gain permission; platform entry rejects the +new identity discriminator. Existing sentinel announcement guards remain. + +The audit isolation policy explicitly departs from the unmodified template: +retain its tenant/org branch, add a guarded global INSERT branch, and add +owner-qualified evidence-read authority. App SELECT gains no global/self-audit +branch. Fixed evidence functions make reciprocal creation and duplicate checks +possible under FORCE RLS. Function execution under table-owner privilege is a +new capability, despite no migration credential in runtime configuration. + +The prior host-lookup definer rejection remains true for its old policies. +Here role-qualified USING arms in single policies plus fixed functions are chosen. +Those arms are not command-specific SELECT policies. Explicit User DELETE and +TRUNCATE guards protect the permanent binding, including owner execution. +No BYPASSRLS, fifth role, PUBLIC execution, dynamic SQL, generic target projection +or mutable search path is allowed. Migrations own installation; runtime call +sites and policy/function bodies have positive and dirty controls. + +User and success audit share one commit. Deferred reciprocity is forced IMMEDIATE +after all writes and before commit admission; it is not a permanent cross-module +FK blocking audit purge. A known precommit guard refusal rolls back; a missing +physical COMMIT acknowledgement remains uncertain. Central non-success +reconciliation uses the captured subject, fresh standalone timestamp and existing +possible indeterminate pair. Non-success evidence requires no User witness and +proves no business outcome; it may coexist with a committed success after an +unknown acknowledgement. Exact duplicate checking includes outcome; a unique +error alone is insufficient. Before binding, actor is NULL and proposed target +is distinct. +Seed adoption attributes SystemActor and its adopted subject. Catalogue baseline +is MUST; no tenant override or suppression allowance applies. Preserve existing +Critical/health, refusal and cancellation-independent joined cleanup semantics. +A timeout is neither no-COMMIT evidence nor a reason to allocate another actor. + +Audit `metadata.identity_subject_key` uses the stable binding key, not raw +provider values. It remains immutable linkable PII, potentially guessable for +low-entropy subjects; SHA-256 provides no secrecy/anonymisation promise. Existing +security retention applies even without User. P03-10's Identity closure coordinator +and Audit participant locate successful/failed attempts by this key and report +retained immutable linkage. No metadata UPDATE grant is widened. Phase 11 owns +purge/backup operations; it does not own missing Phase 03 fulfillment. + +### Acceptance vehicle and carriers + +Both ADRs are accepted together. The +[revised package](../roadmap/phase-03-delivery-log.md#p03-1-second-maintainer-review-and-revised-package-2026-10-25) +records the approved scope, Amendment texts and proof owners. The dated +Amendments and canonical contract adoption accompany acceptance; they do not +claim that schema, runtime grants or their proofs are implemented. + +| Carrier / clause | Named adoption instrument | +|---|---| +| ADR-0003; Standard 05 six classes/unmodified audit/global unique exceptions | Dated bounded Amendment for new class and exact audit/owner-policy departure; ordinary template unchanged | +| ADR-0010; Standard 01 cross-module SQL | Dated bounded Amendment for enumerated central persistence-witness guard SQL only; no module business join or fifth application mechanism | +| ADR-0033 including Amendment 5 | Dated Amendment extending central success/reconcile to the named global population, preserving durability | +| ADR-0036 pre-context identity read | Dated Amendment for route-independent binding normalization and future candidate reader; no new HTTP surface or TenantContext writer | +| ADR-0040 owners/nesting/setters | Dated Amendment for subject owners and separately registered candidate reader; no tenant/global join | +| ADR-0044 §§1/2/3/5/9/10 | Dated bounded Amendment for second sentinel population, prepared global declaration, app INSERT/evidence, exact duplicate proof and new central seams | +| ADR-0064 actor/projection/pipeline | Dated bounded Amendment for optional API wire actor, verified-subject quota and existing-binding normalization; route invariance/census preserved | +| ADR-0066 subject admission population | Dated clarification for verified-subject input before binding; numeric/ownership/fault semantics unchanged | +| ADR-0065 and ADR-0070 | Dated navigation only: host mismatch allowance never covers global MUST; native complete identity/AccountSite publication remain unchanged | +| ADR-0071 | Dated navigation Amendment only; ordinary-read status table unchanged | +| Standards 04/05/07/10/11/18/19/21; Architecture 09/13/23/31/33 | Adopt the approved canonical contracts and authority headers; no duplicate SQL | +| CLAUDE, glossary, IAuditStore/PostgresAuditStore XML and guard census | Reconcile sole-population/writer and method-count claims before dependent code; default refusal stays | + +Reopen before issuer rebind, another producer, global profile disclosure, +digest/HMAC change, tombstone retirement or changed closure authority. No dormant +writer preempts P03-9 rebind/privileged reads or P03-10 retained-reference workflow. + +## Consequences + +### Positive + +- One database owns allocation/audit without provider machinery. +- Serialization avoids benign racing failed audits. Stable authority/key supports + approved URL migration; closure need not retain raw subject. + +### Negative + +- API/BFF claim and global audit authority deliberately change. Authenticated + admission gains an uncached store dependency; anonymous reads do not. +- Authority installation is mandatory; unsupported issuer change fails closed. +- Fixed owner SQL/policies are load-bearing runtime privilege, without an owner + password. They require independent controls and genuine database proof. +- Durable actors can lack membership/session. HTTP creation and its registration/ + capacity policy are withheld until P03-3, not solved by in-memory subject caps. +- Permanent digest/actor and retained failed-attempt keys remain personal data. + Offline guessing and immutable retained copies are explicit accepted costs. + +### Neutral + +- No provider SDK, new login, Hub crossing, live permission enforcement or session + database is introduced. No erasure/production-readiness proof follows. + +## Implementation Notes + +The revised package owns six steps, exact proof/status and required controls. +Acceptance authorizes these authorities; it does not implement them. Four seed actors, +provider subjects and credentials survive; ordinary HTTP cannot invoke adoption. + +## References + +- [ADR-0010](0010-cross-module-communication.md), + [ADR-0033](0033-audit-durability-model.md), [ADR-0036](0036-tenant-resolution-trusted-inputs.md), + [ADR-0040](0040-ambient-unit-of-work.md), [ADR-0044](0044-audit-write-path.md), + [ADR-0053](0053-trusted-public-server-rendering.md), + [ADR-0064](0064-tenant-api-authentication-boundary.md), + [ADR-0065](0065-bounded-tenant-assertion-diagnostics.md), + [ADR-0066](0066-bounded-tenant-subject-admission.md), + [ADR-0070](0070-owned-tenant-bff-sessions.md), + [ADR-0071](0071-uncertain-account-site-refusals.md). +- [ADR-0073](0073-scoped-membership-and-identity-data-foundation.md), + [Identity spec](../modules/identity/README.md), + [Data Protection](../architecture/23-data-protection.md). +- [PostgreSQL 18 policies](https://www.postgresql.org/docs/18/sql-createpolicy.html), + [functions](https://www.postgresql.org/docs/18/sql-createfunction.html), + [isolation](https://www.postgresql.org/docs/18/transaction-iso.html), + [function snapshots](https://www.postgresql.org/docs/18/xfunc-volatility.html). +- [PostgreSQL 18 constraint timing](https://www.postgresql.org/docs/18/sql-set-constraints.html). + +## Amendments + +### Amendment 1 — Ordered Membership admission timing (2026-10-26) + +[ADR-0074](0074-membership-admission-under-ordered-locks.md) owns the bounded +canonical Membership eligibility-read timing change in +[Standard 05](../standards/05-database.md#lock-snapshot-and-adoption-conditions). +This is navigation to that change: this ADR delegates the algorithm and its +decision remains unchanged. +Creation, Suspended-to-Active and every assignment addition acquire the actual +target's exclusive User fence before tenant fences and retain the transaction +hold through completion. The actual mutation trigger must freshly verify that +target's eligibility even when the complete ordered plan is preheld. No missing +User key is first acquired beneath tenant authority. + +P03-10's separately admitted closure/status owner must acquire the same User +fence, then all affected exclusive Tenant keys in canonical order, before making +the User nonadmitting. The final-admin recovery/termination gate remains. The +global subject owner, five-function confinement, absence of a generic User +reader and all other decisions remain unchanged. The Accepted body, status and +date above remain historical; ADR-0074 and Standard 05 own the current timing +contract and its pending Step 4 proofs. diff --git a/docs/decisions/0073-scoped-membership-and-identity-data-foundation.md b/docs/decisions/0073-scoped-membership-and-identity-data-foundation.md new file mode 100644 index 000000000..c0fcb3b76 --- /dev/null +++ b/docs/decisions/0073-scoped-membership-and-identity-data-foundation.md @@ -0,0 +1,247 @@ +# ADR-0073: Scoped Membership and Identity Data Foundation + +## Status + +Accepted — jointly with ADR-0072 on 2026-10-25. Implementation and runtime +qualification remain pending. + +**Date:** 2026-10-25 +**Deciders:** @cemil + +**Relationship:** Joint acceptance with [ADR-0072](0072-application-owned-identity-bootstrap.md) +is complete. The decisions cover G3/G19 and the foundation portions of +G2/G4/G5/G8/G16; later execution gates remain Open. This record and its accepted +module contract authorize implementation, not current runtime capability. + +## Decision Drivers + +- Membership/profile/assignment changes need one aggregate boundary; nullable + scope, revoked successors and direct database writes need independent controls. +- Permission identity is `(scope, key)`. Capability scope must not accidentally + dictate Role storage scope or template-authoring authority. +- The product needs exact-organization assignments, not independently configured + copies of each built-in Role in every branch. +- Initial grants, later additions and the Tenant Admin minimum need finite + manifests, with an explicit first-admin and concurrent final-admin contract. +- Personal-data classification and safe diagnostics precede personal-data writes. + +## Considered Options + +1. **Contained Membership state, tenant-wide Role templates and code-owned scoped + grants** (chosen). An Organization-capability template derives its effective + organization only from the Membership assignment. +2. **Independent profile/assignment roots** (rejected). Atomic membership changes + would require another multi-root exception without a benefit here. +3. **Independent Role definitions per organization** (rejected). No selected product + requirement needs branch-specific built-in Role configuration. It adds + organization-initialization/reconciliation writes and a lifecycle dependency + on Tenancy; tenant-wide templates remove both without widening assignments. +4. **A shared global or tenant profile for all branches** (rejected). It collapses + contextual ownership; canonical RLS exposes NULL-org data across branches. +5. **Custom roles, wildcard administrators or automatic new-key grants** (rejected). + These broaden the closed model or silently increase existing authority. +6. **Only active uniqueness or recycled User bindings** (rejected). Suspended + duplicates complicate resumption; recycled subjects can resurrect closed accounts. +7. **PII/name heuristics alone** (rejected). Snapshot markers and LS0002 do not + classify neutral-name properties or prevent value-bearing diagnostics. + +## Decision + +Membership owns one contextual Profile and its Role assignments. Active and +Suspended rows occupy the same null-safe natural key; Revoked rows are retired +and rejoin creates a successor with fresh assignments. User remains global under +ADR-0072, without tenant-authored fields or an active-session selector. + +Role is a **tenant-wide template**, carrying `TenantId`, a closed built-in key +and capability `PermissionScope`, but no `OrganizationId`. Grants are contained +Role children. Tenant Admin alone edits templates; an Organization-capability +template becomes effective only through an exact-organization Membership +assignment. Organization creation writes no Identity rows. Learner has Tenant +and Organization variants: an explicit scope extension, not a new role name. + +The [permission contract](../standards/19-permissions.md#proposed-identity-foundation-contract) +owns the exact five foundation permission pairs, version-1 grant manifest and +two-pair immutable Tenant Admin kernel. One versioned compiled manifest generates +the SQL guard artifact, checked for equivalence; Role data cannot redefine it. +New keys stay disabled for existing Roles until an explicit grant change. + +Every Membership mutation leaves an Active, globally eligible, tenant-wide +Tenant Admin. The first Membership therefore establishes that administrator; +later mutations cannot remove the final one. Role roots initialize in separate +transactions beforehand. Completed foundation is the verified required templates +plus the actual eligible admin, without a bootstrap table or writable flag. + +This preserves administration for Trial, Active and Suspended tenants. Archived +termination/global closure needs a separately admitted G13/G16 exception before +its writer; foundation guards infer none from status. Future global closure +cannot make the final administrator ineligible before that authority/guard +contract ships. Creation, reactivation and **all** assignment additions recheck +the User fence, including currently empty/inactive templates. Profile/nonadmin/ +organization mutations use shared tenant invariant mode; first-admin and tenant- +admin eligibility/assignment/kernel transitions use exclusive mode. Actual rows +bind the mode before acquisition, with no lock upgrade. Both modes preserve the +total invariant, not merely the administrator count before the mutation. +[Standard 05](../standards/05-database.md#proposed-lock-snapshot-and-adoption-conditions) +alone owns lock ordering, snapshots, deadlines and direct-write guards. + +The [Identity module contract](../modules/identity/README.md) owns exact tables, +guards, seed sequence and execution/proof owners. Seed-only commands have a +closed admission capability, default-denied in the API, with no live route. +G19 adds semantic property classification and fixed diagnostics before PII +writes. Live authorization remains P03-2; retained linkage remains pseudonymous. +P03-1 supplies storage/audit/seed and existing-session binding only; HTTP/new-user +BFF activation belongs to P03-3 under its separately Accepted contract. + +## Context + +At `92117893`, Identity's four packages contain assembly markers only. No +Identity schema, registry or grants exist. Tenant filters do not exclude deleted +rows or carry `app.scope`; OrganizationScopeValidator proves belonging and +nondeletion, not lifecycle eligibility. Tenant creation starts Trial; public +eligibility admits Trial and Active. These facts are inputs, not Identity proof. + +SeedData declares four authentication actors, two tenants and two organizations +per tenant, without application memberships. The accepted [seed sequence](../modules/identity/README.md#first-admin-and-seed-sequence) +preserves bindings/credentials and declares exact assignments. Role templates +are tenant-wide even for Organization capabilities; only Membership/Profile/ +Assignment rows carry branch scope. Yoga admin keeps its provider branch claim; +its independently declared NULL-org seed target supplies the seed SQL scope. +The module contract owns that handoff and P03-3's explicit orgless reissue for +later tenant-wide writes. Additional cross-tenant/multi-org and same-tenant +proof populations are fixture-local, preserving the exact four-person manifest. + +### Boundaries and acceptance instruments + +| Authority | Exact relationship | Acceptance instrument / owner | +|---|---|---| +| ADR-0072 | Required global identity, admission fence, confined owner reads and global audit contract | Joint acceptance; P03-1 Steps 1/3; no independent global SQL or retention variant here | +| ADR-0017 | Preserve tenant grants plus matching-org grants; clarify contained Membership data and tenant-wide Role storage | Dated clarification on acceptance, preserving Accepted body; P03-1 Step 1 | +| ADR-0042 | Preserve its only exception: Tenancy's Tenant/default Organization pair | No replacement or new exception; external seed owner commits Role/Membership commands separately | +| ADR-0040 / Security 11 | Candidate reader needs an explicitly enumerated owner/setter | Dated Amendment and exact registration before execution; P03-1 contract, P03-2 adapter | +| Standard 19 | Resolve scoped identity, stored templates versus assignments and finite initial/upgrade grants; extend Learner capability scope | Jointly adopted canonical replacements; P03-1 Step 1, live enforcement/grant adoption P03-2 | +| ADR-0044 / Standards 18/21 | Child capture, personal-data declarations and actual proof subjects need named owners | Applicable dated navigation/registered extensions, then actual backfill; P03-1 Steps 1–4 | + +Earlier Accepted bodies remain historical; dated Amendments disclose the bounded +authority changes. No runtime surface is activated by acceptance. The [revised P03-1 package](../roadmap/phase-03-delivery-log.md#p03-1-second-maintainer-review-and-revised-package-2026-10-25) +owns authorized implementation sequencing. Its exact manifest and module +contracts are part of this joint acceptance. + +### Later execution boundaries + +- **G2 / P03-2:** qualify the app-role candidate reader, step-5/6 handoff, consistent + EF/RLS read scope and independent HostScope ceiling. The current DenyAll reader, + HTTP surface and unset `app.scope` stay until then. Successful claim-only header + mismatch evidence needs separate G2/G7 authority before activation. +- **G3 / P03-1:** supply the bounded Tenancy lifecycle port/result/freshness + contract and implementation named in the module specification. Live admission + execution remains P03-2; lifecycle/archive/last-default-org races remain P03-3 + before their endpoints. Foundation acceptance does not close those later proofs. +- **G4 / P03-3:** scope discovery/issuance is per session. No global User selector + or provider user-global attribute proves independent simultaneous A/B refresh. +- **G8 / P03-4:** invitation acceptance/delivery needs its own accepted atomicity/ + reconciliation vehicle. No Invitation table or multi-root exception lands here. +- **G13 / P03-9:** production first-admin/provisioning admission and exceptional + recovery close before their production provisioner; the fixed seed capability + grants no operator or SystemActor bypass. +- **G16 / P03-10:** closure authority, participants, retained-copy transformations, + artifacts/jobs and provider finalization remain mandatory. Tenant erasure or + Membership removal never implicitly closes the global provider account. +- **G19 / P03-1 Step 2:** classify every mapped subject/property, including + inherited actor references and ADR-0072 audit linkage, in closed categories or + explicit None with purpose. Compare the actual nonempty models, not sensitive + names. SQL-only/control/vendor inventory stays with Data Protection. Translate + new Identity conflicts/failures to fixed bounded descriptors before sinks; + never retain input-bearing DTO/token/body/provider/database exception text, + including inner payloads. Unexpected paths retain fixed operational signals. + P03-5 extends revision-aware dynamic values; P03-10 completes reference locators. + LS0001/LS0002 remain Warning until P03-11. + +P03-1 stores no optional token-derived canonical email/verification mirror. +Its first consumer, currently P03-6/G10, decides the later writer/freshness +contract. A token snapshot is not current verified email for invitation acceptance. +Snapshot redaction and diagnostics remain distinct; no global exception scrubber, +global-profile editor, dormant custom-fields blob or retention change is implied. + +## Consequences + +### Positive + +- One Membership transaction owns contextual state and accurate child audit. +- Tenant-wide templates remove per-branch initialization/configuration drift. +- Finite manifests make grants, kernel safety and no-write reruns inspectable. +- A semantic property census detects omissions even when names look harmless. + +### Negative + +- Branch-specific Role configuration reopens this decision. +- Tenant-wide profiles remain branch-visible; private data needs org Membership. +- New capabilities require explicit grant adoption; seed drift refuses repair. +- Administration mutations serialize. Revoked successors and retained linkage + still need later privacy fulfillment. +- Semantic classification needs maintenance and cannot infer arbitrary text's PII. + +### Neutral + +- No Platform grant, Hub crossing, production first-admin provisioner, invitation, + dynamic-field/DSAR workflow, live authorization or UI is activated. +- Table/proof declarations are planned contracts, not executable controls. + +## Implementation Notes + +The accepted [module specification](../modules/identity/README.md), [permissions](../modules/identity/permissions.md) +and [audit matrix](../modules/identity/audit.md) assign current/planned subjects +without calling an empty census implemented. Do not copy canonical tenant RLS +or ADR-0072's global SQL into this ADR. + +Reopen for independent branch configuration, custom roles, different profile +granularity, changed lifecycle/admin invariants, automatic grant expansion, +global canonical-profile disclosure or dynamic-field diagnostic capture. + +## Architecture Tests + +Existing canonical controls retain their current implementation status; Identity +extensions await subjects/backfill. Planned coverage includes marker/filter/RLS, +tenant-composite FK/mirror/unique/aggregate/audit rules and nonempty scoped +definitions. The semantic property census is Registered as +`Mapped_Properties_Have_Explicit_Personal_Data_Classification`, with implementation +and a planted unclassified neutral-name property required in Step 2. + +## Behavioral Proofs + +- Real app-role PostgreSQL uniqueness/lifecycle/scope controls, first/final-admin + races, fresh post-wait competing commits, isolation refusal and closure versus + creation/reactivation/assignment additions, with independent dirty controls. +- Exact manifests, separate root transactions, interrupted seed resume, fixed + drift refusal, disabled new-key grants and complete no-write rerun. +- All four preserved provider/actor identities, Organization Learner branch denial + and explicit cross-tenant/multi-org/same-tenant-second-person subjects. +- Child audit/forced MUST rollback and per-sink sensitive/neutral-key nested + canaries with positive received events; preserve TenantSetting redaction. + +## References + +- [ADR-0003](0003-tenant-isolation-defense-in-depth.md), [ADR-0017](0017-tenant-organization-hierarchy.md), + [ADR-0032](0032-exception-handling-logging-and-observability.md), + [ADR-0042](0042-tenant-provisioning-cross-aggregate-transaction.md), + [ADR-0044](0044-audit-write-path.md), [ADR-0072](0072-application-owned-identity-bootstrap.md). +- [Permissions](../standards/19-permissions.md), [Database](../standards/05-database.md), + [Data Protection](../architecture/23-data-protection.md), [Phase 03](../roadmap/phase-03-identity-admin.md). + +## Amendments + +### Amendment 1 — Ordered Membership admission timing (2026-10-26) + +[ADR-0074](0074-membership-admission-under-ordered-locks.md) owns the bounded +canonical Membership eligibility-read timing change. This is navigation to the +delegated algorithm, without changing this ADR's decision. Complete Membership/child +plans retain User-before-tenant acquisition, actual-row classification, +strongest pre-mutation tenant mode, no upgrades and the total eligible-admin +invariant. Creation, Suspended-to-Active and every assignment addition require +the actual target's exclusive User fence. The actual mutation trigger must +freshly verify target eligibility even when the complete ordered plan is +preheld; it cannot first acquire a missing User key beneath tenant authority. + +[Standard 05](../standards/05-database.md#lock-snapshot-and-adoption-conditions) +owns the current algorithm, heldness limits and pending Step 4 proofs. No new +scope, grant, Role variant, generic User reader or live endpoint follows. All +other decisions and the Accepted body, status and date above remain unchanged. diff --git a/docs/decisions/0074-membership-admission-under-ordered-locks.md b/docs/decisions/0074-membership-admission-under-ordered-locks.md new file mode 100644 index 000000000..c3942f1a4 --- /dev/null +++ b/docs/decisions/0074-membership-admission-under-ordered-locks.md @@ -0,0 +1,230 @@ +# ADR-0074: Membership Admission Under Ordered Locks + +## Status + +Accepted — 2026-10-26, after the maintainer's conditional authorization and +verified review corrections. Dependent Membership implementation/proofs remain +P03-1 Step 4; acceptance alone installs no contextual function or writer. + +**Date:** 2026-10-26 +**Deciders:** @cemil +**Canonical contract change:** Membership eligibility-read timing in Standard 05, +whose algorithm is delegated by +[ADR-0072](0072-application-owned-identity-bootstrap.md) and +[ADR-0073](0073-scoped-membership-and-identity-data-foundation.md). +The conflicting clause is in Standard 05; those ADRs delegate its algorithm. +Their dated Amendments are navigation, preserving their decisions and bodies. +User-before-tenant lock acquisition and the five-owner-function set remain unchanged. + +## Decision Drivers + +- A Membership and its assignments need their strongest complete lock set before + mutation; a new Tenant Admin assignment requires exclusive tenant mode. +- The admitted User eligibility reader is a real BEFORE trigger. A new parent + row alone cannot reveal its not-yet-persisted child assignments. +- Nonadministrator writes retain shared tenant mode; unconditional exclusive + locking or shared-to-exclusive upgrades would change the approved contract. +- An additional callable User reader would enlarge owner execution and expose + another global-state probe. The existing five functions should suffice. + +## Considered Options + +1. **Prehold User fences, then tenant fences; check eligibility in the actual + admission trigger before mutation** (chosen). Stable User ownership permits + the fresh check after tenant acquisition without another reader capability. +2. **Add a callable pre-mutation User eligibility reader** (rejected). It makes + the original read timing implementable but adds a capability/signature and + caller/projection/privacy controls; the actual trigger supplies the required + admission check without that additional global-state probe. +3. **Let the parent trigger acquire all locks before planning children** + (rejected). The parent cannot infer a future administrator assignment. Always + selecting exclusive mode loses the adopted nonadministrator concurrency; + selecting shared mode can require a forbidden upgrade. +4. **Write the graph before locking, or use a synthetic trigger probe** + (rejected). The first changes the pre-mutation guarantee; the second adds an + unadmitted preparation mode instead of checking the real mutation. + +## Decision + +Membership creation, Suspended-to-Active transitions and every assignment addition +acquire their required exclusive User fences before their complete strongest +tenant fences and before data-mutating statements. The actual admission trigger +verifies the actual target's currently held exclusive fence and freshly checks +eligibility before permitting mutation; the eligibility read can follow tenant +acquisition. Missing ownership refuses without acquiring a User key in the +trigger. Other Membership mutations retain Standard 05's existing lock requirements. + +## Context + +Verified against `111ca113`: global storage is implemented; contextual writers +and the two Membership owner functions remain P03-1 Step 4. The canonical +[function contract](../standards/05-database.md#confined-owner-functions) says the +Membership trigger locks/rechecks User before tenant locking. The +[ordered-lock contract](../standards/05-database.md#lock-snapshot-and-adoption-conditions) +also requires the complete strongest lock set before mutation and derives mode +from actual transitions/protected capabilities, not caller labels. + +The admitted `CreateFirstSeedAdminMembership` command creates a Membership and +contained administrator assignment under the +[finite manifest](../standards/19-permissions.md#exact-foundation-registry-and-operation-owners). +Its absence-of-history condition permits an exclusive first-admin plan. A second +administrator is a fixture-only proof subject, outside the four-person seed +manifest; no second-admin production command is added by this decision. +That case exposes the general parent/child issue: the application can plan its +graph from actual referenced Role rows, but the parent trigger cannot read an +assignment that is not stored yet. Locking the +User and exclusive tenant first meets the complete-plan rule, while the first +permitted global eligibility read then occurs in the trigger. Entering the +trigger first cannot generically choose the future child plan's tenant mode. +The five owner functions supply no ordinary pre-mutation User reader. +`fn_identity_admin_admission_state` only checks a stored candidate Membership in +an admitted final-admin evaluation and takes no User lock; using it for arbitrary +new targets would broaden that contract. + +The proposal separates acquisition order from check timing. The transaction holds +the target's exclusive admission fence continuously through check and commit. +A cooperating closure writer either commits before that fence is acquired or +waits until this transaction ends. The fresh trigger read therefore observes a +nonadmitting predecessor or a state protected against that concurrent writer. +This is a design argument; no contextual implementation/race proof exists yet. + +PostgreSQL's transaction advisory locks end with their transaction. READ COMMITTED +and fresh queries inside VOLATILE functions support the required post-wait +observation. These primitives do not prove the application's correct plan/body. +See the PostgreSQL 18 +[advisory-lock documentation](https://www.postgresql.org/docs/18/explicit-locking.html#ADVISORY-LOCKS) +and [function-snapshot documentation](https://www.postgresql.org/docs/18/xfunc-volatility.html). + +The trigger uses the exact current-backend/database exclusive bigint-key +observation in [Standard 05](../standards/05-database.md#membership-fence-checks), +through `pg_catalog.pg_locks`; it uses no acquisition or try-lock function to +test ownership. The view cannot distinguish session from transaction ownership, +earlier acquisition order or future lifetime. Session-only ownership can satisfy +that SQL observation; it is not an admitted writer replacement. Transaction-only +acquisition and retention are separate caller/source/receipt and completion-test +obligations. Nor does the view authenticate a CLR caller or freeze the entire +cluster. These limits and collection costs are documented by +[PostgreSQL](https://www.postgresql.org/docs/18/view-pg-locks.html). + +Exclusive User mode preserves the already approved per-User admission +serialization. Shared ownership could exclude an exclusive closure writer, but +this decision does not change the stronger existing contract. A change to shared +admission would need its own contention/duplicate-plan decision and proofs. + +Reopen if a real operation cannot determine its complete target family before +mutation, needs a new global reader, or cannot retain the User fence through +completion. A closure writer that ignores this fence is not made safe by the +read's timing; P03-10 must implement and prove its side before activation. + +## Consequences + +### Positive + +- Complete root/child plans and shared nonadministrator concurrency coexist with + the existing trigger-only eligibility authority. +- No new definer function, grant, table, User projection or HTTP surface follows. +- The trigger checks the actual target and refuses unknown/nonadmitting targets + uniformly before they can mutate Membership state. + +### Negative + +- An ineligible target may hold a tenant fence until the fresh trigger check + refuses. That cost moves after tenant acquisition; existing deadlines remain. +- Each admission row observes `pg_locks`; repeated collection can contend with + PostgreSQL's lock manager. Step 4 measures actual trigger-path/query/pool cost + within the existing write-p95 budget, including representative contention. + This document supplies no latency or production-capacity result. +- Correctness depends on the complete plan, real exclusive User ownership and + continuous transaction lifetime. Reentrant acquisition is not proof of the + original order; source/caller and race controls remain necessary. + +### Neutral + +- Shared/exclusive classification, no upgrades, fresh post-wait reads, total-admin + invariants, User lifecycle, privacy and seed-only authority are unchanged. +- Step 3's subject-key global owner is unaffected. P03-2/3 live/HTTP activation + and P03-9/10 operational/closure ownership remain separate deliveries. + +## Implementation Notes + +Acceptance appends dated navigation Amendments to ADR-0072/0073, preserving their +bodies/status/dates. Standard 05 replaces the conflicting function-row timing, +owns the exact observation/refusal/lock/proof clauses and adds this ADR to its +derivation header. Standards 10/11/21 and Identity's specification carry their +signal/security/proof references. The catalogue extends Source/Asserts while +retaining Registered; the decision index moves this ADR to Active, and Phase 03's +Status/G3 plus delivery log record acceptance before dependent code. No prior +proposal/review record is rewritten. + +Step 4 checks closed seed authority and scope lifecycle before lock acquisition; +P03-2 owns live permission enforcement. It uses an announced READ COMMITTED owner, +a plan derived from actual Role/parent facts and intended changes, sorted required +User acquisition for the admission operations above, then sorted +strongest tenant acquisition. A separate post-wait read revalidates classification; +changed/ambiguous plans refuse without upgrading. The existing real mutation +trigger verifies its actual target/fence and eligibility before permitting the +write. Complete-graph/admin validation and central MUST audit precede commit. +No precheck Boolean or caller-supplied scope label substitutes for these checks. + +A missing/wrong/shared-only/foreign fence is a fixed internal plan fault; an +unknown/Closing/Closed target is an expected admission refusal. Both yield the +same fixed outward refusal without User-existence details. Only plan faults use +the existing lock-refusal `fault` signal; expected target refusal does not invent +an acquisition failure. Canonical classification belongs to Standard 05 and +finite, identity-free signal dimensions to Standard 10. + +## Tests and Proofs + +These extend the already Registered +`Identity_Membership_Invariants_Use_Fresh_Ordered_Locks`; acceptance is not an +Implemented status. Step 4's `IdentityMembershipTests` owns real app-role proofs: + +- Hold the User fence, start a competing closure transition, observe its lock + wait, commit Membership, then allow the fixture-only competitor to proceed. +- Commit a nonadmitting transition while a creator waits for the User fence; + its later trigger check must freshly refuse. Retain an admitting clean twin. +- Exercise the actual first-seed-admin command and complete contained graph; + keep second-admin subjects fixture-local. +- Create a second Tenant Admin and contained assignments under a preheld exclusive + plan; create a learner under a shared plan. Missing/wrong/shared-only User + fences under tenant authority refuse without acquiring a missing key. +- Observe a correct key held only by another backend, a two-integer namespace, + signed keys and session-only ownership. The session control demonstrates the + view's limit; source/caller controls reject session acquisition APIs and real + transaction-end tests prove release. C#/SQL User and Tenant vectors agree. +- Profile changes and assignment removal acquire no automatic User fence. + Plan-fault and target-refusal diagnostics differ internally with identical + outward refusal and no identity-bearing metric dimensions. +- Preserve changed-classification, no-upgrade, two-admin retirement, shared/ + exclusive coexistence, incompatible-isolation, timeout/cancellation and MUST + rollback controls, with actual PostgreSQL lock-wait observations. +- Prove exact five-definer bodies/ACL/callers and clean/dirty controls. Neither + a generic User probe nor a synthetic trigger mode may appear. +- Measure actual per-row observation and mutation latency/p95, query/pool cost + and contended behavior; no empty-view microbenchmark establishes API capacity. +- Exercise immediate admission followed by complete-graph constraint validation + and failed MUST audit: neither admits a partial committed graph. + +Closure competitors use disposable databases only: preserve the applied guard +and policy, narrowly disable `tg_users_no_update` and add a migration-owner-only +fixture WITH CHECK arm. The fixture owner takes the same User then affected +exclusive tenant fences for its fixed status transition. Restore guard/policy in +`finally`; verify exact restored body/ACL/trigger/policy census and that owner +UPDATE again refuses. A separate dirty/clean control proves the fixture's +temporary accommodation was effective and fully removed. App-role Membership +operations remain the subjects; neither superuser nor BYPASSRLS proves isolation. +No production lifecycle writer, grant or closure fulfillment is introduced. + +## References + +- [ADR-0072](0072-application-owned-identity-bootstrap.md) +- [ADR-0073](0073-scoped-membership-and-identity-data-foundation.md) +- [ADR-0041](0041-correcting-false-statements-in-accepted-adrs.md) +- [Identity storage and lock contract](../standards/05-database.md#identity-storage-contract) +- [Identity specification](../modules/identity/README.md) +- [Identity foundation permissions](../standards/19-permissions.md#identity-foundation-contract) +- [Identity lock signals](../standards/10-observability.md#identity-lock-signals) +- [Identity admission security](../standards/11-security.md#identity-admission-contract) +- [Ordered-lock proof](../standards/21-architecture-tests-catalogue.md#identity_membership_invariants_use_fresh_ordered_locks) +- [Phase 03](../roadmap/phase-03-identity-admin.md) +- [Phase 03 delivery log](../roadmap/phase-03-delivery-log.md) diff --git a/docs/decisions/0075-ordinary-ci-job-window.md b/docs/decisions/0075-ordinary-ci-job-window.md new file mode 100644 index 000000000..e3d5edad5 --- /dev/null +++ b/docs/decisions/0075-ordinary-ci-job-window.md @@ -0,0 +1,305 @@ +# ADR-0075: Ordinary CI Job Window + +## Status + +Accepted — 2026-10-27. + +**Date:** 2026-10-26 +**Deciders:** @cemil +**Bounded supersession:** Only the twenty-minute ordinary Docker execution +clauses in ADR-0063 and the inherited requirement in ADR-0062 Amendment 1. + +**Maintainer acceptance — 2026-10-27.** The maintainer approves the revised ADR +and three-step plan at `c274fa6e` and authorizes dependent implementation on +`development`: only verified ordinary Docker producers receive the twenty-five-minute +whole-job window. ADR-0062 and ADR-0063 retain their Accepted bodies and metadata +with their own dated ordinary-only amendments; native, base and Architecture +execution retain twenty minutes. All other decisions and retained boundaries +remain in force. This is a bounded policy change, not an erratum. +Acceptance, implementation, two fresh independent review rounds per step and +fresh same-final-source hosted A/B qualification remain separate gates. The +[acceptance and Step 1 record][acceptance-record] owns the approval receipt and +dependent delivery evidence; acceptance claims no executable change or hosted fit. + +## Decision Drivers + +- Complete A passes, but complete B on the same source stops two ordinary + producers at their owner deadline. Six selected cases have no result; passing + completed cases and the preceding A cannot qualify B. +- The current six Architecture and twelve ordinary producers already use + ADR-0063's upper count bounds and twenty execution VMs. More ordinary VMs + change both the accepted count range and total cap. +- Repeated build, discovery and fixture startup consume real wall time that + summed case weights do not represent. Further lucky weight tuning does not + establish complete execution under both materially different assignments. +- Preserve complete case ownership, zero skips, natural disposal, resource + ownership/accounting, seven required check names and strict current-attempt + evidence. + +## Considered Options + +1. **Twenty-five minutes for ordinary producers only** (chosen). Add bounded + wall-time headroom without adding VMs or changing assignment. Hosted fit + remains a required proof, not a consequence of accepting the ceiling. + Acceptance selects five minutes of maintainer-judged headroom, not a + measured minimum. This selects the ordinary-only part of ADR-0063's + previously considered “Increase job ceilings” alternative. +2. **Keep twenty minutes and optimize fixtures/tests further** (valid, not + selected). This retains the policy but needs further test-only lifecycle + work and proof that sharing, startup or disposal changes preserve isolation + and assertions. No sufficient measured improvement is established here. +3. **Increase ordinary producers to fourteen or sixteen** (valid, not selected). + With the current six Architecture producers, this exceeds the accepted + eight–twelve ordinary range and twenty-VM cap, duplicates + build/discovery/fixture work and increases organization queue pressure. +4. **Adopt fixture-aware assignment** (valid, not selected). A new algorithm + needs instrumentation, versioning and independent A/B qualification. + Current fixture-start counts and startup costs are unobserved; case weights + cannot supply that missing measurement. +5. **Choose twenty-two or twenty-three minutes** (not selected). Censored tails + do not establish a measured minimum or prove either shorter window fits. + Twenty-five shares that uncertainty but gives more bounded headroom; the + maintainer's acceptance chooses that trade-off, not a proved safe margin. +6. **Drop/skip cases, ignore failed producers or combine attempts** (rejected). + These remove proof of the complete population and cannot qualify a release. + +## Decision + +LearnStack gives only the verified ordinary Docker producers a twenty-five-minute +(1,500-second) whole-job ceiling in place of twenty minutes (1,200 seconds). +The other job ceilings, 203-second cleanup/export/upload reserve, resource +ownership/accounting, assignment rule and complete two-layout qualification remain +unchanged. The longer window follows the verified expected producer identity +through a closed mode allowlist; no receipt, environment override or arbitrary +producer chooses it. + +## Context + +### Retained same-source evidence + +[Run 40382715371](https://github.com/HodeTech/LearnStack/actions/runs/40382715371) +uses PR head `7aabc6d8a3e2109a6e6dfa0c439442b0dcd008d9` and actual merge +checkout `2c692b51adc5feb7fb0c843d4124938a61775a7b`. Their tree is equal: +`217d237966b20215ed25a15d5440c4d05a18717c`. These are related source identities, +not interchangeable commit hashes. The retained plan digest is +`115e474202360d0d7d99e1a8c69a0b40f7eb84669364b23ce90c94341969113b`; +the full manifest digest is +`8d017042f7e439273a7164326d9a1ae7ef3ea4ea3dea9a1bfa4c315a133bef21`. + +Original metadata, ZIPs and extracted proof remain under +`artifacts/p031-step6/hosted/40382715371/{1,2}/`. Attempt 1 selects A; attempt 2 +selects B. The [Phase 03 delivery log](../roadmap/phase-03-delivery-log.md) +owns the dated execution and independent audit receipts. + +- **A:** All 27 jobs succeed. Exact unions contain 3,664 backend and 2,826 + Docker cases: 6,490 passes, zero skips. All 25 original ZIPs are retained and + independently audited, including twenty natural execution owners. The + maximum producer job wall is 920 seconds. +- **B:** Twenty-four jobs succeed. `ordinary-3`, `ordinary-7` and the dependent + integration aggregate fail; the backend aggregate and all Architecture + producers pass. All 24 available original ZIPs are retained. Completed + evidence contains 6,484 passing cases and six cases without results. +- **B ordinary-3:** 262 selected, 259 completed, all completed outcomes Passed. + Pre-owner work takes 255.148 seconds; discovery/selection takes 42.654. + The persona theory completes two of four rows and the historical-upgrade + Fact completes zero of one. +- **B ordinary-7:** 267 selected, 264 completed, all completed outcomes Passed. + Pre-owner work takes 256.526 seconds; discovery/selection takes 43.896. + The cross-tenant-token theory completes zero of two rows and the real + backchannel Fact completes zero of one. +- Both failed receipts report `deadline_exhausted`, `forcedCleanup: true` and + `dockerAbsent: false`. Cleanup ownership does not establish natural disposal. + They remain unqualified; no missing case becomes an assertion failure, + a skip or an inferred pass. + +The preceding [independent mutation collection change][mutation-collections] +moves nineteen method groups without changing runtime code or test bodies; +all 66 affected local cases pass. The 303-method Architecture census across +53 classes has a historical maximum complete-observation class envelope of +617 seconds. This diagnoses class serialization; it does not establish a future +wall bound. Current B now completes Architecture. Earlier ordinary weight-only +revisions did not qualify complete B, and further partition luck is not proof. + +### Budget arithmetic and uncertainty + +The current nominal owner window before pre-owner/discovery work is +`1,200 − 203 = 997` seconds. The proposal makes it +`1,500 − 203 = 1,297` seconds. With the two observed B pre-owner and discovery +intervals plus measured owner setup of 0.191/0.198 seconds +(`result.json.setupSeconds`), nominal remaining +test-process time changes from approximately 699/696 to 999/996 seconds. +This ledger excludes other overhead; it is not a prediction that the six +censored cases finish, a fixture profile or a future fit guarantee. + +The censored tails do not reveal their full duration or a precise necessary +ceiling. Twenty-five minutes adds five bounded minutes to an already measured +path while preserving topology. Actual final-source A/B execution decides +whether that choice suffices. Further exhaustion reopens the decision rather +than silently extending the window again. + +ADR-0063's “failure of both assignments” example is not the observed outcome: +A passes and B fails. Reopening here follows its separate finite-envelope +exhaustion clause and the requirement to qualify both layouts. It is an +explicit request to change that envelope, not a claim that both layouts fail. +Its prohibition on unapproved ceiling increases retains only this named +ordinary exception on acceptance. The dated amendments in both ADR-0063 and +ADR-0062 qualify the inherited twenty-minute requirement without rewriting it. + +### Boundaries retained + +- Current counts stay six Architecture and twelve ordinary; approved ranges + stay four–six and eight–twelve, with one base and one native VM and at most + twenty backend/test execution VMs. +- Algorithm/version, B salt, advisory weights, tie-breakers, filters, argument + bounds and the complete discovered case population stay unchanged. +- Existing child resource ownership and CPU/memory accounting stay unchanged; + these observations are not enforced numeric CPU or memory quotas. Native + collector authority, Docker/process ownership and the 203-second reserve stay + unchanged. + Every test-specific startup, operation, transport, cancellation and cleanup + deadline keeps its existing bound; this is only a whole-job policy change. +- Base, Architecture and native execution jobs retain twenty minutes. Both + aggregates and meta retain five minutes. Every other workflow job keeps its + existing ceiling, including any ceiling already below twenty minutes. +- All seven required names, strict protection, read-only evidence permissions, + natural disposal and exact current-attempt case/TRX/artifact validation stay + unchanged. No runner-tier or concurrency upgrade is included. +- No deployment/environment override or application authentication, token, + session, authorization or tenant-isolation change follows from this decision. + +## Consequences + +### Positive + +- Ordinary jobs gain 300 seconds of bounded headroom without additional VMs, + changed case ownership or weaker success evidence. +- Launcher deadlines, workflow configuration and independent validation have + one explicit policy boundary that can be tested against forged identities. + +### Negative + +- Each slow or hung ordinary producer can consume up to five additional running + minutes. Total workflow feedback delay depends on concurrency, queueing and + scheduling; five minutes is not an overall workflow-delay upper bound. +- The larger window guarantees neither runner availability nor hosted fit. It + repairs no assertion failure and changes no CPU/memory policy or runner tier. + +### Neutral + +- Queued time remains separate from running-job wall time. No current pricing, + billing or available organization concurrency is assumed by this proposal. +- Acceptance approves the policy and dependent work; implementation, review + and hosted qualification remain separate gates. + +## Implementation Notes + +Implementation starts only after maintainer acceptance and proceeds in three +reviewable steps. Each step is committed and receives two fresh independent +review rounds; verified findings are fixed, committed and revalidated before +the next step starts. The [revised Phase 03 package][revised-package] holds the +append-ready amendment texts and verified maintainer-review dispositions. + +1. **Acceptance carriers.** Mark this ADR Accepted with the maintainer receipt; + append a dated ordinary-only amendment to each of ADR-0063 and ADR-0062. + ADR-0062's amendment qualifies Amendment 1's inherited twenty-minute + statement and expressly keeps native execution at twenty minutes. Update + [Testing Standards § Complete bounded CI + assignments](../standards/06-testing.md#complete-bounded-ci-assignments) + and its derivation reference. Reconcile the corresponding twenty-minute + statement in [Infrastructure Stack Standards](../standards/20-infrastructure-stack.md) + through the same ordinary-only exception and reference. Extend the existing + [`CI_Test_Shards_Are_Complete_And_Bounded` catalogue entry][ci-rule] + with this source and the closed ordinary-budget assertion; its existing + Implemented status does not assert the extension is delivered. Move the + decision index row to Active and update Phase 03 status and the delivery + record. Do not rewrite either ADR's historical rationale, text or metadata. +2. **Closed budget implementation.** Change only ordinary whole-job policy in + the carriers below, preserve all retained boundaries, run the relevant + offline controls and obtain two fresh independent review rounds before + hosted qualification. Review findings receive fixes and fresh verification. +3. **Fresh hosted proof.** Run two full attempts, literal A and B, on the same + final source, plan, toolchain and case population. Each needs all 27 jobs, + all 6,490 cases with exact unions and zero skips, 25 original archives and + twenty natural owners, plus independent archive/API/case cross-audit. + Preserve each attempt before the next rerun. Historical A is context, never + replacement proof for the newly implemented source; failed-job reruns and + mixed-attempt unions remain refused. + +The source budget carriers are: + +- [`.github/workflows/ci.yml`](../../.github/workflows/ci.yml): only + `backend-integration-tests` changes to `timeout-minutes: 25`; literal indices, + clocks before checkout, uploads, other jobs and required names stay unchanged. +- [`scripts/ci-native-tests.py`](../../scripts/ci-native-tests.py): replace the + uniform `JOB_SECONDS` use at `deadlines()` for the execution owner and leaf + with one closed mode-to-window policy shared with fixture preparation and + result validation; do not maintain a second independent duration constant + in `ci-test-shard-results.py`. Validate the exact supported mode, + expected job and shard index before granting 1,500 seconds. Unknown modes, + prefix lookalikes and forged mode/job pairs refuse. Preserve every reserve + component and its failure-tail authority; no environment budget knob exists. +- [`scripts/ci-test-shard-results.py`](../../scripts/ci-test-shard-results.py): + align `workflow_topology`, `verify_jobs`, `finite_seconds` and + `verify_receipt` with the same expected-producer policy. Choose the receipt + interval ceiling from the independently expected/verified owner, never the + payload's self-declared `partition`. Bind the receipt to that owner before + applying any longer budget. `verify_jobs` chooses the API running-wall limit + from its expected owner in either aggregate scope; base/native/Architecture + stay at 1,200 seconds even inside the integration aggregate. Bind + `prepare_fixture_images` to verified + ordinary workflow identity and the same window; retain its 110-second total, + 55-second per-image limits and two-minute workflow step ceiling. Aggregate + acquisition/download/validation/upload allocations remain five-minute work. + +`finite_seconds` validates observations, not test-operation deadlines. Supply +the verified expected owner's ceiling explicitly for its receipt and +`measurements.json` workload/phase/project observations; never change the +helper's bound globally to 1,500. Only expected ordinary owners receive the +longer observational bound. `workloadSeconds` encloses the entire worker and +`testProcessSeconds` encloses an assembly invocation, so either can exceed +1,200 when pre-owner work is short while still fitting the 1,500-second job +and unchanged reserve. Keeping a separate 1,200-second ordinary measurement +cap would add another workload policy; this decision does not add it. The +four disjoint receipt intervals sum strictly below the owner's ceiling; +nested measurement intervals are not additional disjoint time. Existing +test/fixture operation limits retain their own unchanged constants. + +## Architecture Tests + +This ADR introduces no application architecture rule. Extend the existing +offline launcher/result/plan controls and workflow validation; do not invent a +second application-test catalogue name for a CI policy. + +- **Counterfactual controls:** ordinary API job walls above 1,200 through + 1,500 seconds can pass only with otherwise valid complete expected ordinary + identity/evidence. Individual receipt intervals remain finite and at most + 1,500; their sum stays strictly below 1,500. Above 1,500 refuses. Other + producer kinds retain the corresponding 1,200-second limits. + Include otherwise valid ordinary workload/assembly observations above 1,200 + inside the longer enclosing window, with nonordinary counterexamples that + refuse them. NaN, infinity, negative values and identity forgery still refuse; + unchanged test-operation caps cannot inherit the observation limit. +- **Identity controls:** unknown modes, out-of-range indices, prefix lookalikes, + forged receipt partitions and mode/job mismatches cannot acquire the longer + window. Launcher, image preparation and validator agree on the closed set. +- **Workflow controls:** reject any ordinary ceiling other than 25, any increase + elsewhere, changed counts/resource policy/reserve, bypassed identity or weakened + aggregate/meta allocations. Existing completeness and tamper controls remain. +- **Proof levels:** synthetic counterfactuals establish policy enforcement; + unit/offline controls establish bounded behavior; workflow checks establish + configuration agreement. Only complete final-source hosted A/B establishes + actual wall fit, natural lifecycle completion and the full artifact union. + +## References + +- [ADR-0063: Complete Bounded CI Test Shards](0063-complete-bounded-ci-test-shards.md). +- [ADR-0062: Native Crash Proof CI Provisioning][native-ci]. +- [Testing Standards](../standards/06-testing.md). +- [Documentation Standards](../standards/13-documentation.md). +- [Phase 03](../roadmap/phase-03-identity-admin.md). + +[mutation-collections]: ../roadmap/phase-03-delivery-log.md#p03-1-pr-38-independent-mutation-collections-2026-10-26 +[native-ci]: 0062-native-crash-proof-ci-provisioning.md +[ci-rule]: ../standards/21-architecture-tests-catalogue.md#ci_test_shards_are_complete_and_bounded +[revised-package]: ../roadmap/phase-03-delivery-log.md#adr-0075-maintainer-review-and-revised-package-2026-10-27 +[acceptance-record]: ../roadmap/phase-03-delivery-log.md#adr-0075-acceptance-and-step-1-2026-10-27 diff --git a/docs/decisions/README.md b/docs/decisions/README.md index 47ec0bb51..288a81c90 100644 --- a/docs/decisions/README.md +++ b/docs/decisions/README.md @@ -49,21 +49,21 @@ records hosted qualification. Phase 11 owns production qualification. |---|---|---| | 0001 | [Platform Name](0001-platform-name.md) | Name and naming conventions | | 0002 | [Initial Architecture](0002-initial-architecture.md) | .NET 10 + EF Core + PostgreSQL + Valkey + SeaweedFS + Next.js; modular monolith | -| 0003 | [Tenant Isolation Defense in Depth](0003-tenant-isolation-defense-in-depth.md) | Query filters + RLS + audit + architecture tests (Amendment 1: Organization scope, 2026-05-18; Amendment 2: identity row terminology, 2026-05-19; **Amendment 3: corrected RLS policy template + database role model, 2026-08-08**; [Amendment 4: stale Phase 02a table list, 2026-08-29](0003-tenant-isolation-defense-in-depth.md#amendment-4--the-phase-02a-table-list-has-gone-stale-2026-08-29); [Amendment 5: UPDATE/DELETE guards exclude organization-scoped sessions from tenant-wide rows, 2026-09-04](0003-tenant-isolation-defense-in-depth.md#amendment-5--the-write-guards-admitted-an-organization-scoped-session-to-tenant-wide-rows-2026-09-04); **[Amendment 6: exact INSERT scope, invoker parent-scope guards and no-id immutability, 2026-09-14](0003-tenant-isolation-defense-in-depth.md#amendment-6--insert-scope-and-parent-mirrors-2026-09-14)**) | +| 0003 | [Tenant Isolation Defense in Depth](0003-tenant-isolation-defense-in-depth.md) | Query filters + RLS + audit + architecture tests (Amendment 1: Organization scope, 2026-05-18; Amendment 2: identity row terminology, 2026-05-19; **Amendment 3: corrected RLS policy template + database role model, 2026-08-08**; [Amendment 4: stale Phase 02a table list, 2026-08-29](0003-tenant-isolation-defense-in-depth.md#amendment-4--the-phase-02a-table-list-has-gone-stale-2026-08-29); [Amendment 5: UPDATE/DELETE guards exclude organization-scoped sessions from tenant-wide rows, 2026-09-04](0003-tenant-isolation-defense-in-depth.md#amendment-5--the-write-guards-admitted-an-organization-scoped-session-to-tenant-wide-rows-2026-09-04); **[Amendment 6: exact INSERT scope, invoker parent-scope guards and no-id immutability, 2026-09-14](0003-tenant-isolation-defense-in-depth.md#amendment-6--insert-scope-and-parent-mirrors-2026-09-14)**) [Amendment 9: P03-1 identity authority](0003-tenant-isolation-defense-in-depth.md#amendment-9--global-self-identity-isolation-2026-10-25). | | 0004 | [Authentication Strategy](0004-authentication-strategy.md) | Off-the-shelf identity provider preferred over hand-rolled auth (Amendment 1: `learnstack-hub` realm, 2026-05-18) | | 0005 | [Live Classroom Media Stack](0005-live-classroom-media-stack.md) | LiveKit OSS self-hosted by default; LiveKit Cloud optional; no custom SFU | | 0006 | [Events and Outbox](0006-events-and-outbox.md) | Domain + integration events; outbox pattern; idempotent handlers (Amendment 1: Dapr pub/sub dispatch transport, 2026-05-18) | | 0007 | [Documentation Language and Conventions](0007-documentation-language-and-conventions.md) | English; Mermaid; ADR + standards split | | 0008 | [Localization Schema](0008-localization-schema.md) | Side translation tables vs JSONB localized fields | | 0009 | [Frontend — Single Next.js App First](0009-frontend-single-app-first.md) | One Next.js app with route segments; multi-app split deferred | -| 0010 | [Cross-Module Communication](0010-cross-module-communication.md) | Four sanctioned mechanisms, no fifth (Amendment 1: Dapr pub/sub backend, 2026-05-18) | +| 0010 | [Cross-Module Communication](0010-cross-module-communication.md) | Four sanctioned mechanisms, no fifth (Amendment 1: Dapr pub/sub backend, 2026-05-18) [Amendment 5: P03-1 identity authority](0010-cross-module-communication.md#amendment-5--confined-identity-creation-witness-sql-2026-10-25). | | 0011 | _Superseded — see below_ | Was: Vertical Extension Points | | 0012 | [Search Strategy](0012-search-strategy.md) | Meilisearch; one instance per env; index-per-(kind, locale); tenant_id as query filter | | 0013 | [Page Block Schema Versioning](0013-page-block-schema-versioning.md) | `(key, schemaVersion)` tuple; immutable schemas; lazy + bulk migration; placeholder on unknown version | | 0014 | _Superseded — see below_ | Was: Adopt Dapr for Cross-Cutting Infrastructure | | 0015 | [API Gateway with APISIX](0015-api-gateway-apisix.md) | APISIX standalone mode; JWT + rate limit + CORS + correlation-id at the edge; defense-in-depth | | 0016 | [Audit Log Subsystem](0016-audit-log-subsystem.md) | **Superseded by [ADR-0033](0033-audit-durability-model.md).** `LearnStack.Modules.Audit`; EF interceptor + `IAuditStateCapture` + `AuditLogBehavior`; partitioned `audit_log` table; retention. Read for context; ADR-0033 carries the binding durability rules | -| 0017 | [Tenant + Organization Hierarchy](0017-tenant-organization-hierarchy.md) | Two-level: Tenant → Organization; permission scope Platform / Tenant / Organization (Amendment 1: identity row terminology, 2026-05-19; **Amendment 2: the `Organization` aggregate is declared in `LearnStack.Modules.Tenancy.Domain`, 2026-08-10**) | +| 0017 | [Tenant + Organization Hierarchy](0017-tenant-organization-hierarchy.md) | Two-level: Tenant → Organization; permission scope Platform / Tenant / Organization (Amendment 1: identity row terminology, 2026-05-19; **Amendment 2: the `Organization` aggregate is declared in `LearnStack.Modules.Tenancy.Domain`, 2026-08-10**) [Amendment 4: P03-1 identity authority](0017-tenant-organization-hierarchy.md#amendment-4--membership-roots-and-scoped-capability-templates-2026-10-25). | | 0018 | [Tenant-Driven Customization Model](0018-tenant-driven-customization-model.md) | Generic-only core; tenants define content types, page blocks, scoring rules as **data**, not code (supersedes ADR-0011; Amendment 2026-08-08 draws the genericity boundary — stateful entitlement and external capability invocation are platform features, not customization; Amendment 2026-09-04: a customization key and an item key are lowercase slugs, with a 2026-09-07 erratum on three of its supporting statements; Amendment 2026-09-06: the aggregates ship phase by phase) | | 0019 | [LearnStack Hub](0019-learnstack-hub.md) | Separate codebase `learnstack-hub`; tenant lifecycle, plans, entitlements, billing, custom domain admin; mTLS internal API | | 0020 | [Triple Deployment + Hybrid License](0020-triple-deployment-hybrid-license.md) | SaaS / Dedicated / Self-Hosted from one codebase; phone-home + RSA-signed key + 30-day grace (Amendment 2026-09-07: the mode switch describes the **end state** — `NullEntitlementProvider` is the registered implementation in every mode until that mode's adapter exists, per ADR-0035's default-implementation gate) | @@ -77,18 +77,18 @@ records hosted qualification. Phase 11 owns production qualification. | 0030 | [Redis-compatible Store — Valkey](0030-redis-compatible-store-valkey.md) | Valkey (Linux Foundation, BSD-3-Clause) for the cache + Dapr state-store backend; RESP-protocol drop-in; partially supersedes ADR-0002's Redis row | | 0031 | [PostgreSQL — Start on 18.x](0031-postgresql-major-version.md) | Pin primary RDBMS major version to PostgreSQL 18; native `uuidv7()` + async I/O + longest LTS runway; partially supersedes ADR-0002's PostgreSQL row | | 0032 | [Exception Handling, Logging, and Observability](0032-exception-handling-logging-and-observability.md) | `IExceptionHandler` + 8-step MediatR pipeline + `Result.Fail`-only validation + `DomainException`-is-bug discipline + `IProviderResilience` (Polly v8) + Sentry vs OTel error capture boundary + Serilog primary + `TenantContextSpanProcessor` + `IErrorTrackingProvider` deployment-mode branching. [Amendment 4 (2026-10-12)](0032-exception-handling-logging-and-observability.md#amendment-4--bounded-producer-supersession-by-adr-0057-2026-10-12) discloses ADR-0057's bounded supersession of step-7 completion and the two separate `event_id` requirements; other clauses remain Accepted. [Amendment 5 (2026-10-15)](0032-exception-handling-logging-and-observability.md#amendment-5--trusted-job-origins-and-bounded-diagnostics-2026-10-15) adds trusted job origins and bounded diagnostics. [Amendment 6 (2026-10-25)](0032-exception-handling-logging-and-observability.md#amendment-6--sensitive-exception-message-diagnostic-2026-10-25) adds the bounded LS0002 contract and automatic production wiring; [Amendment 7](0032-exception-handling-logging-and-observability.md#amendment-7--diagnostic-wiring-and-proof-clarifications-2026-10-25) clarifies its unchanged escalation and proof boundaries. | -| 0033 | [Audit Durability Model](0033-audit-durability-model.md) | **Supersedes ADR-0016.** MUST-class audit written as durable intent inside the business transaction (fails closed); SHOULD/MAY-class stays best-effort; corrected partitioned `audit_log` primary key; `AuditConfig` cannot remove baseline MUST coverage. **Amendment 1 (2026-08-18):** a standalone MUST write failure changes the response only when the operation would otherwise have succeeded. **Amendment 2 (2026-09-07)** meets the code that shipped after it: intents are **plural**, one per audited resource, because one command already writes two; only the **owning** unit-of-work frame writes them and reports the commit boundary, so a nested `Send` cannot claim durability nothing committed; `outcome` closes at four values and the writer supplies `timestamp`, which is what keeps the deliberate duplicate-id pair legal under `(id, timestamp)`; both standalone writers announce **two** session variables, measured — an org-scoped `denied` row is refused without the second; a fourth write method serves `EnterPlatformAdminScope`; and a read-sensitive query **does** reach step 6, since Packet 6's `TransactionBehavior` has no request-kind gate. Decided by [ADR-0044](0044-audit-write-path.md). **Amendment 3 (2026-09-08)** gives the audit health check an owner and demand-gates the deployment-level stop-serving backstop to Phase 11 with a written trigger: stopping a process is the one operational act the next request cannot undo, and Phase 02a has neither a readiness surface nor an operator to answer the page it would raise. **Amendment 4 (2026-09-08):** a tenant override narrows and never elevates, a cancelled `COMMIT` is `Indeterminate`, and the override loader runs on a cache miss. **Amendment 5 (2026-09-11):** `EnterPlatformAdminScope` never reaches `WriteStandaloneAsync`, and a nested request's refusal outlives the commit it joined. **Amendment 6 (2026-09-11):** the audit health check answers only whether a MUST-class row can be written; a tenant-override read failure is its `Error` line alone. **Amendment 7 (2026-09-11):** a request refused at step 1 writes no audit row — validation runs before the audit step classifies anything — so the standalone path is reached by a short-circuit at step 4 or 5, the assertion recorder and the reconcile. [Amendment 8 (2026-10-12)](0033-audit-durability-model.md#amendment-8--common-audit-ownership-outside-mediatr-2026-10-12) clarifies common audit ownership outside MediatR under ADR-0057; durability and classification contracts survive. [Amendment 10 (2026-10-15)](0033-audit-durability-model.md#amendment-10--same-transaction-job-terminal-audit-2026-10-15) adds same-transaction job-terminal audit under ADR-0047. | +| 0033 | [Audit Durability Model](0033-audit-durability-model.md) | **Supersedes ADR-0016.** MUST-class audit written as durable intent inside the business transaction (fails closed); SHOULD/MAY-class stays best-effort; corrected partitioned `audit_log` primary key; `AuditConfig` cannot remove baseline MUST coverage. **Amendment 1 (2026-08-18):** a standalone MUST write failure changes the response only when the operation would otherwise have succeeded. **Amendment 2 (2026-09-07)** meets the code that shipped after it: intents are **plural**, one per audited resource, because one command already writes two; only the **owning** unit-of-work frame writes them and reports the commit boundary, so a nested `Send` cannot claim durability nothing committed; `outcome` closes at four values and the writer supplies `timestamp`, which is what keeps the deliberate duplicate-id pair legal under `(id, timestamp)`; both standalone writers announce **two** session variables, measured — an org-scoped `denied` row is refused without the second; a fourth write method serves `EnterPlatformAdminScope`; and a read-sensitive query **does** reach step 6, since Packet 6's `TransactionBehavior` has no request-kind gate. Decided by [ADR-0044](0044-audit-write-path.md). **Amendment 3 (2026-09-08)** gives the audit health check an owner and demand-gates the deployment-level stop-serving backstop to Phase 11 with a written trigger: stopping a process is the one operational act the next request cannot undo, and Phase 02a has neither a readiness surface nor an operator to answer the page it would raise. **Amendment 4 (2026-09-08):** a tenant override narrows and never elevates, a cancelled `COMMIT` is `Indeterminate`, and the override loader runs on a cache miss. **Amendment 5 (2026-09-11):** `EnterPlatformAdminScope` never reaches `WriteStandaloneAsync`, and a nested request's refusal outlives the commit it joined. **Amendment 6 (2026-09-11):** the audit health check answers only whether a MUST-class row can be written; a tenant-override read failure is its `Error` line alone. **Amendment 7 (2026-09-11):** a request refused at step 1 writes no audit row — validation runs before the audit step classifies anything — so the standalone path is reached by a short-circuit at step 4 or 5, the assertion recorder and the reconcile. [Amendment 8 (2026-10-12)](0033-audit-durability-model.md#amendment-8--common-audit-ownership-outside-mediatr-2026-10-12) clarifies common audit ownership outside MediatR under ADR-0057; durability and classification contracts survive. [Amendment 10 (2026-10-15)](0033-audit-durability-model.md#amendment-10--same-transaction-job-terminal-audit-2026-10-15) adds same-transaction job-terminal audit under ADR-0047. [Amendment 11: P03-1 identity authority](0033-audit-durability-model.md#amendment-11--prepared-global-identity-audit-ownership-2026-10-25). | | 0034 | [Hub Contract Surface Invariant](0034-hub-contract-surface-invariant.md) | Replaces "closed at four endpoints" with two enforceable invariants (Hub stores no tenant content; every crossing goes through a named adapter); enumerates the real endpoint set; TLS key material leaves the entitlement payload; host resolution never calls the Hub | | 0035 | [Demand-Gated Infrastructure](0035-demand-gated-infrastructure.md) | The one-way-door test; ports + default implementations ship now, vendor adapters ship on a named trigger in a named phase; uncontracted deployment modes may not decide technical choices | -| 0036 | [Trusted Inputs for Tenant and Organization Resolution](0036-tenant-resolution-trusted-inputs.md) | Resolution by **agreement, not priority** — every authoritative signal present is resolved independently and the request proceeds only on their intersection; no request header names a tenant or an organization, one header names a **host** over an authenticated hop and LearnStack still resolves it itself; `TenantContextOrigin` caps a host-only context to the `[PublicSurface]` read set; the platform-admin override leaves the resolution model. [Amendment 13](0036-tenant-resolution-trusted-inputs.md#2026-10-19--amendment-13-api-authentication-and-row-10-staging-correction) records ADR-0064's row-14 audit replacement, additive authentication attribution and row-10 staging errata. [Amendment 14](0036-tenant-resolution-trusted-inputs.md#2026-10-20--amendment-14-bounded-assertion-diagnostics) records ADR-0065's bounded assertion admission and metric-label replacement. | +| 0036 | [Trusted Inputs for Tenant and Organization Resolution](0036-tenant-resolution-trusted-inputs.md) | Resolution by **agreement, not priority** — every authoritative signal present is resolved independently and the request proceeds only on their intersection; no request header names a tenant or an organization, one header names a **host** over an authenticated hop and LearnStack still resolves it itself; `TenantContextOrigin` caps a host-only context to the `[PublicSurface]` read set; the platform-admin override leaves the resolution model. [Amendment 13](0036-tenant-resolution-trusted-inputs.md#2026-10-19--amendment-13-api-authentication-and-row-10-staging-correction) records ADR-0064's row-14 audit replacement, additive authentication attribution and row-10 staging errata. [Amendment 14](0036-tenant-resolution-trusted-inputs.md#2026-10-20--amendment-14-bounded-assertion-diagnostics) records ADR-0065's bounded assertion admission and metric-label replacement. [Amendment 15: P03-1 identity authority](0036-tenant-resolution-trusted-inputs.md#amendment-15--existing-binding-admission-before-tenant-resolution-2026-10-25). | | 0037 | [What an Idempotency Key Identifies, Owns, and Replays](0037-idempotency-key-contract.md) | A client-chosen key is a **nonce inside a tenant's key space**, not an identity: `(tenant, key)` addresses the record and a fingerprint over organization, principal, method, path, query and body decides whether replaying it answers the question asked; a fencing token owns the claim; capacity is **admission, not eviction**, so nothing unexpired is ever displaced; the guarantee is at-most-once while a claim is live and at-least-once across process death | | 0038 | [Cross-Cutting Port and Event Contracts](0038-cross-cutting-port-and-event-contracts.md) | **Supersedes ADR-0014.** Retains Dapr behind demand gates; fixes the event envelope, handler isolation, trace/audit scope and cache contracts. [Amendment 2 (2026-10-12)](0038-cross-cutting-port-and-event-contracts.md#amendment-2--additional-producer-payload-policy-2026-10-12) links ADR-0057's additional producer payload policy; original envelope, serializer and transport contracts survive. [Amendment 3](0038-cross-cutting-port-and-event-contracts.md#amendment-3--bounded-publish-outcome-supersession-by-adr-0046-2026-10-12) links ADR-0046's publish-outcome replacement. [Amendment 4](0038-cross-cutting-port-and-event-contracts.md#amendment-4--durable-acceptance-and-subscriber-delivery-implemented-2026-10-13) records P02b-3 durable acceptance and independent subscriber execution delivery. | | 0039 | [The Optimistic Concurrency Token](0039-optimistic-concurrency-token.md) | An explicit `row_version bigint` (CLR `long`), project-wide, incremented inside `AuditableEntity` by the single primitive `MarkUpdated` and `SoftDelete` both route through, and mapped with `HasDefaultValue(0L).IsConcurrencyToken().ValueGeneratedNever()` — exactly those three calls (Amendment 2): `ValueGeneratedOnAddOrUpdate()` / `IsRowVersion()` make EF omit the column from the `UPDATE` entirely (Amendment 1, measured), and `HasDefaultValue` alone leaves `ValueGenerated` at `OnAdd`, which the registered rule rejects; `xmin` is rejected because the token is client-visible through ETag / `If-Match` and a dump-restore or logical-replication cutover changes it — measured, unlike the widely-cited `VACUUM FREEZE` objection, which does not | -| 0040 | [The Ambient Unit of Work](0040-ambient-unit-of-work.md) | One `DbConnection` per scope, owned by `IUnitOfWork`; every module `DbContext`, `IAuditStore` and `IOutbox` enlists on it, because `SET LOCAL` is connection-local and a context on its own connection reads **zero rows** under the corrected RLS policy. Spans one aggregate's write plus audit plus outbox plus any reads — cross-aggregate writes stay forbidden, with the one enumerated exception [ADR-0042](0042-tenant-provisioning-cross-aggregate-transaction.md) carves for tenant provisioning (Amendment 4, 2026-08-30). Defines nesting, disposal, and the event-consumer entry point that never reaches MediatR. The closed set of `app.tenant_id` setters is seven by Amendment 3 (2026-08-30) and eight by **Amendment 7 (2026-09-11)**, which adds the tenant-flag projection loader `IFeatureFlags` fills on a cache miss. [Amendment 10 (2026-10-12)](0040-ambient-unit-of-work.md#amendment-10--bounded-produced-work-refusal-supersession-2026-10-12) discloses ADR-0057's bounded produced-work refusal supersession; [Amendment 11 (2026-10-12)](0040-ambient-unit-of-work.md#amendment-11--named-transaction-announcement-snapshot-reader-2026-10-12) separately adds the named read-only announcement snapshot seam. [Amendment 13](0040-ambient-unit-of-work.md#amendment-13--exact-authenticated-read-mode-scope-2026-10-19) discloses ADR-0064's exact AccountSite read-mode scope extension. | +| 0040 | [The Ambient Unit of Work](0040-ambient-unit-of-work.md) | One `DbConnection` per scope, owned by `IUnitOfWork`; every module `DbContext`, `IAuditStore` and `IOutbox` enlists on it, because `SET LOCAL` is connection-local and a context on its own connection reads **zero rows** under the corrected RLS policy. Spans one aggregate's write plus audit plus outbox plus any reads — cross-aggregate writes stay forbidden, with the one enumerated exception [ADR-0042](0042-tenant-provisioning-cross-aggregate-transaction.md) carves for tenant provisioning (Amendment 4, 2026-08-30). Defines nesting, disposal, and the event-consumer entry point that never reaches MediatR. The closed set of `app.tenant_id` setters is seven by Amendment 3 (2026-08-30) and eight by **Amendment 7 (2026-09-11)**, which adds the tenant-flag projection loader `IFeatureFlags` fills on a cache miss. [Amendment 10 (2026-10-12)](0040-ambient-unit-of-work.md#amendment-10--bounded-produced-work-refusal-supersession-2026-10-12) discloses ADR-0057's bounded produced-work refusal supersession; [Amendment 11 (2026-10-12)](0040-ambient-unit-of-work.md#amendment-11--named-transaction-announcement-snapshot-reader-2026-10-12) separately adds the named read-only announcement snapshot seam. [Amendment 13](0040-ambient-unit-of-work.md#amendment-13--exact-authenticated-read-mode-scope-2026-10-19) discloses ADR-0064's exact AccountSite read-mode scope extension. [Amendment 14: P03-1 identity authority](0040-ambient-unit-of-work.md#amendment-14--prepared-global-owners-and-candidate-reader-registration-2026-10-25). | | 0041 | [Correcting False Statements in Accepted ADRs](0041-correcting-false-statements-in-accepted-adrs.md) | Inline erratum beside the false text is the default; in-place replacement only where the text is a **canonical artifact for reuse** — a template others are told to copy, a DDL or command meant to be applied — never merely because something could be copied, and never because a non-ADR carrier holds the same token. Bounded to statements false **when they entered the record**, judged per statement: original body at the acceptance commit, amendment text at that amendment's date. A statement that has since gone stale is history, and gets an amendment or a superseding ADR. Every changed Accepted ADR carries its own dated Amendment | | 0042 | [Tenant Provisioning as a Bounded Cross-Aggregate Transaction](0042-tenant-provisioning-cross-aggregate-transaction.md) | A standing, **enumerated** exception to § Aggregate Ownership: tenant provisioning writes `Tenant` and its default `Organization` in one transaction, because `tenants.default_organization_id` carries an invariant an integration event cannot deliver — the substitute moves the second write to a later transaction and the window between them is exactly what the invariant forbids. Bounded by enumeration rather than by principle: two roots, one operation, a literal allow-list of one in the architecture test. Covers no child entity, no projection, and no cross-**module** write, which stays forbidden with no exception | | 0043 | [What LearnStack Does With a Tenant-Authored Payload](0043-customization-payload-validation.md) | JSON Schema draft 2020-12, evaluated by `JsonSchema.Net` **pinned at 8.0.5** (the last MIT-expression release) behind an `IJsonSchemaValidator` port. A tenant document passes **four ordered gates** — JSON, the LearnStack profile, the 2020-12 meta-schema, then the build — because the library's own defaults keep none of the rules the corpus states: its default dialect is not 2020-12, a tenant's `$schema` line overrides the pinned one, a tenant's `$id` becomes process-global state (first-writer-wins, a cross-tenant denial of service), and `true` / `false` / `{}` are all valid schemas that switch validation off. `pattern` is refused — the built `Regex` carries an infinite `MatchTimeout` and `maxLength` does not short-circuit it (measured, 30.2 s on one property). **No compiled-validator cache**: compiling is measured *cheaper* than evaluating (0.5× at the 100-property ceiling), so § 8.2's cache is deleted rather than re-keyed. Rule bodies are opaque `text` with a `dialect` discriminator naming the language of their `condition` expressions. Amendments 1–2 (2026-09-04/05) refuse **every** `$ref` cycle and bound the reference graph; Amendment 3 (2026-09-06) seals the port's exception surface and makes `ValidateInstance` enforce § 8.4's entry cap; **Amendment 4 (2026-09-07) refuses what the `jsonb` column refuses** — `U+0000`, an unpaired surrogate, a number outside `numeric`; **Amendment 5 (2026-10-02) adds ADR-0051’s optional ordered text-card profile** | -| 0044 | [The Audit Write Path](0044-audit-write-path.md) | **Amendments 1–5 (2026-09-08), 6–7 (2026-09-11).** The eleven questions ADR-0033 left open, decided before the first audit file: the reserved **non-nil** platform sentinel tenant id (the nil uuid is refused by three shipped guards that read all-zero as *no tenant*), and a `tenants` CHECK that keeps it unprovisionable; the row's `tenant_id` is the tenant the **transaction announced**, so a provisioning command audits under the tenant it creates and `make seed` still commits; **N intents per request**, one per audited resource, because two shipped commands already write two — and only the **owning** unit-of-work frame writes them or reports the commit boundary, which is what stops a nested `Send` from claiming durability nothing committed; `outcome` closes at four values (`indeterminate` included) and the writer always supplies `timestamp`, so ADR-0033's deliberate duplicate-id pair is legal under `(id, timestamp)` rather than a `23505`; the catalogue is **code** keyed by request type and the matrix is prose, with a test asserting they agree, and every request must be classified — there is no `RequestKind.Other`; the interceptor captures **every** tracked entity minus a named exclusion list, because the `AuditableEntity<>` predicate was blind to `platform_host_to_tenant`; `[PiiSensitive]` and an elision record that preserves the column's JSON type; `audit_log` is org-scoped, carries **no** FK to `tenants`, and both standalone writers announce **two** GUCs — measured: an org-scoped `denied` row is refused without the second. Amendment 1 makes `audit_config` tenant-**wide**; Amendment 2 corrects the redaction sentinel to the shipped constant and the reason `FORCE` needs a trigger (the policy binds the owner by tenant, not by immutability — measured); Amendment 3 gives the matrix↔catalogue join two directions with two domains, because 23 of 30 shipped matrix slugs have no request type and the rule as written was red on arrival, and moves the audit value types into `SharedKernel.Audit` to break the same project cycle `AuditEntryId` had; Amendment 4 makes `[PiiSensitive]` property-granular, `jsonb` included, ships `audit_config` unwritten and binds the matrix rule to modules with code; Amendment 5 guards the sentinel where it is announced and fills `entity_type` / `entity_id` from the declared aggregate; Amendment 6 — from an external review that reproduced four defects against real PostgreSQL — has a handler designate the subject when it writes two instances of its aggregate, carries the actor and correlation id on the intent, keeps each intent's own request's result, captures a contained entity with its aggregate, and instance-qualifies `changes` pointers; Amendment 7 corrects § 7's count of plain entities — seven today, five of them MUST — and names the Tenancy matrix alone as the one that singles out the host mapping. [Amendment 8 (2026-10-12)](0044-audit-write-path.md#amendment-8--common-audit-ownership-outside-mediatr-2026-10-12) clarifies common audit ownership outside MediatR under ADR-0057 without adding an audit writer. [Amendment 11 (2026-10-13)](0044-audit-write-path.md#amendment-11--shared-delivery-capture-exclusions-2026-10-13) accepts the inbox/delivery machinery capture exclusions under ADR-0046; P02b-3 implements them through the shared business owner. [Amendment 13 (2026-10-15)](0044-audit-write-path.md#amendment-13--job-terminal-sixth-write-and-capture-exclusions-2026-10-15) adds the job-terminal sixth write and exact job/control capture exclusions. | +| 0044 | [The Audit Write Path](0044-audit-write-path.md) | **Amendments 1–5 (2026-09-08), 6–7 (2026-09-11).** The eleven questions ADR-0033 left open, decided before the first audit file: the reserved **non-nil** platform sentinel tenant id (the nil uuid is refused by three shipped guards that read all-zero as *no tenant*), and a `tenants` CHECK that keeps it unprovisionable; the row's `tenant_id` is the tenant the **transaction announced**, so a provisioning command audits under the tenant it creates and `make seed` still commits; **N intents per request**, one per audited resource, because two shipped commands already write two — and only the **owning** unit-of-work frame writes them or reports the commit boundary, which is what stops a nested `Send` from claiming durability nothing committed; `outcome` closes at four values (`indeterminate` included) and the writer always supplies `timestamp`, so ADR-0033's deliberate duplicate-id pair is legal under `(id, timestamp)` rather than a `23505`; the catalogue is **code** keyed by request type and the matrix is prose, with a test asserting they agree, and every request must be classified — there is no `RequestKind.Other`; the interceptor captures **every** tracked entity minus a named exclusion list, because the `AuditableEntity<>` predicate was blind to `platform_host_to_tenant`; `[PiiSensitive]` and an elision record that preserves the column's JSON type; `audit_log` is org-scoped, carries **no** FK to `tenants`, and both standalone writers announce **two** GUCs — measured: an org-scoped `denied` row is refused without the second. Amendment 1 makes `audit_config` tenant-**wide**; Amendment 2 corrects the redaction sentinel to the shipped constant and the reason `FORCE` needs a trigger (the policy binds the owner by tenant, not by immutability — measured); Amendment 3 gives the matrix↔catalogue join two directions with two domains, because 23 of 30 shipped matrix slugs have no request type and the rule as written was red on arrival, and moves the audit value types into `SharedKernel.Audit` to break the same project cycle `AuditEntryId` had; Amendment 4 makes `[PiiSensitive]` property-granular, `jsonb` included, ships `audit_config` unwritten and binds the matrix rule to modules with code; Amendment 5 guards the sentinel where it is announced and fills `entity_type` / `entity_id` from the declared aggregate; Amendment 6 — from an external review that reproduced four defects against real PostgreSQL — has a handler designate the subject when it writes two instances of its aggregate, carries the actor and correlation id on the intent, keeps each intent's own request's result, captures a contained entity with its aggregate, and instance-qualifies `changes` pointers; Amendment 7 corrects § 7's count of plain entities — seven today, five of them MUST — and names the Tenancy matrix alone as the one that singles out the host mapping. [Amendment 8 (2026-10-12)](0044-audit-write-path.md#amendment-8--common-audit-ownership-outside-mediatr-2026-10-12) clarifies common audit ownership outside MediatR under ADR-0057 without adding an audit writer. [Amendment 11 (2026-10-13)](0044-audit-write-path.md#amendment-11--shared-delivery-capture-exclusions-2026-10-13) accepts the inbox/delivery machinery capture exclusions under ADR-0046; P02b-3 implements them through the shared business owner. [Amendment 13 (2026-10-15)](0044-audit-write-path.md#amendment-13--job-terminal-sixth-write-and-capture-exclusions-2026-10-15) adds the job-terminal sixth write and exact job/control capture exclusions. [Amendment 14: P03-1 identity authority](0044-audit-write-path.md#amendment-14--global-identity-attribution-and-central-write-seams-2026-10-25). | | 0045 | [The Entitlement and Feature-Flag Socket](0045-entitlement-and-feature-flag-socket.md) | **Amendment 1 (2026-09-08)** reads it against the Hub's merged code: the limit vocabulary is the Hub's, `expires_at`/`valid_until` are nullable, the generation guard admits the equal case, and `platform_killswitches` ships **unwritten** because `DenyAllPlatformAdminGate` makes a writer unreachable until Phase 03. **Amendment 2 (2026-09-11):** a registry's membership is the vocabulary the contract names — fourteen Hub features, nine `limits.*`, two tenant flags, three killswitches — and enforcement, not membership, waits for a consumer. **Amendment 3 (2026-09-11):** a key's fail-open/fail-closed class decides only when no projection exists; one past its grace window is read-only, as ADR-0021 decides. **Amendment 4 (2026-09-11):** of the projection's names, `PlanCode` differs from the wire (`tier`) and `ExpiresAt` from the column (`valid_until`) — § 1 had called both wire differences. Declares the port twenty documents name and none define. `IEntitlementProvider.GetAsync(TenantId)` + `RefreshAsync(projection)`, the projection carrying every field `entitlement-v1.schema.json` requires — **`compliance` and `generation` included**, both already `NOT NULL` columns — and the refresh **generation-guarded inside the write statement**, so a stale push cannot resurrect a revoked plan. `IFeatureFlags` is the only module-facing read and **composes over the provider** rather than querying `platform_entitlement_cache`, which is the only reading under which the Phase 02a criterion — swapping the provider changes the answer — can be true. Limits: **`-1` unlimited, `0` denied**, `long` not `long?`; the inverse reading would have made the degraded read-only mode grant unlimited. `NullEntitlementProvider` is registered in **every** deployment mode, per ADR-0035's default-implementation gate rather than ADR-0020's Development-only switch. Killswitches leave `tenant_feature_flags` for a platform-scoped `platform_killswitches`: a foreign key to `tenants` is a constraint no role or `BYPASSRLS` moves, so the sentinel could never have satisfied it. Push-primary, **not** push-only — ADR-0034's `license/verify` fallback stands; the no-Hub absolute belongs to host resolution | | 0046 | [Durable Event Delivery and Recovery](0046-durable-event-delivery-and-recovery.md) | Accepted 2026-10-12: fenced producer leases/retries, Pending readiness holds and atomic row-bound terminal audit; P02b-2 is complete and merged through PR #30; its [merge closeout](../roadmap/phase-02b-delivery-log.md#p02b-2-merge-and-closeout-2026-10-13) owns final verification. [Amendment 2](0046-durable-event-delivery-and-recovery.md#amendment-2--producer-enforcement-and-local-closeout-2026-10-12) records verified local closeout. [Amendment 1](0046-durable-event-delivery-and-recovery.md#amendment-1--producer-runtime-delivery-2026-10-12) records producer runtime delivery and its review evidence. [Amendment 3](0046-durable-event-delivery-and-recovery.md#amendment-3--consumer-runtime-and-enforcement-delivery-2026-10-13) records P02b-3 consumer runtime, both Active defaults and production enforcement; 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. Named bounded supersessions preserve earlier Accepted records. | | 0047 | [Transactional Background Job Runtime](0047-transactional-background-job-runtime.md) | Accepted 2026-10-15: H1 stock Hangfire opaque wakeups plus authoritative transactional job/attempt records, external stages, tenant capacity and trusted recurrence/fan-out; bounded supersessions and additive seams disclosed in prior records. [Amendment 1](0047-transactional-background-job-runtime.md#amendment-1--maintenance-replacement-and-additive-ownership-seams-2026-10-16) records ADR-0058's accepted maintenance configuration replacement and additive ownership seams. The [P02b-4 package](../roadmap/phase-02b-delivery-log.md#p02b-4-decision-package-2026-10-15) authorizes nine implementation steps on development; all nine steps and both reviews per step are complete and merged through PR #32 on 2026-10-19; the [merge closeout](../roadmap/phase-02b-delivery-log.md#p02b-4-merge-and-closeout-2026-10-19) records final-source qualification | @@ -106,14 +106,18 @@ records hosted qualification. Phase 11 owns production qualification. | 0061 | [Known External Job Failure Policy](0061-known-external-job-failure-policy.md) | Accepted 2026-10-17: one immutable three-state policy, Permanent only for Failed, deterministic retry/finalization/reason guards and actual-row-bound audit; [ADR-0047 Amendment 4](0047-transactional-background-job-runtime.md#amendment-4--known-completed-external-failure-policy-2026-10-17) discloses the bounded input replacement and additive contract. Step 7 implementation/reviews and Step 9 enforcement are complete and merged through PR #32; the [merge closeout](../roadmap/phase-02b-delivery-log.md#p02b-4-merge-and-closeout-2026-10-19) records final-source hosted qualification | | 0062 | [Native Crash Proof CI Provisioning](0062-native-crash-proof-ci-provisioning.md) | Accepted 2026-10-18: dedicated disposable native VM, verified fixed collector setup without restoration, complete complementary Docker execution and fail-closed existing required result; [ADR-0060 Amendment 1](0060-fatal-hangfire-startup-and-unsafe-unwind.md#amendment-1--native-ci-provisioning-boundary-2026-10-18) preserves earlier authority. Implementation/reviews and final-source hosted qualification are complete and merged through PR #32; the [merge closeout](../roadmap/phase-02b-delivery-log.md#p02b-4-merge-and-closeout-2026-10-19) records verified evidence and its availability limits | | 0063 | [Complete Bounded CI Test Shards](0063-complete-bounded-ci-test-shards.md) | Accepted 2026-10-18: bounded manual Architecture/ordinary counts, initial base + 6 + 12 + native, complete selector/case-ID aggregates, two-assignment qualification and confined non-Docker ownership; [ADR-0062 Amendment 1](0062-native-crash-proof-ci-provisioning.md#amendment-1--bounded-ci-shards-and-additive-non-docker-owner-2026-10-18) records replacement/additive seams. All three dependent steps/reviews and both full hosted assignments are complete and merged through PR #32; the [merge closeout](../roadmap/phase-02b-delivery-log.md#p02b-4-merge-and-closeout-2026-10-19) records exact source and actual bounded fit | -| 0064 | [Tenant API Authentication Boundary](0064-tenant-api-authentication-boundary.md) | Accepted 2026-10-19: strict tenant bearer profile, stable actor/subject quota, closed authenticated read and bounded membership-denial audit replacement; [five-step P02b-5 package](../roadmap/phase-02b-delivery-log.md#p02b-5-decision-package-2026-10-19) approved before implementation. Own dated disclosures in ADR-0036/0040/0052 preserve their Accepted bodies. All five implementation steps and both independent review rounds per step are locally complete; the [Step 5 closeout](../roadmap/phase-02b-delivery-log.md#p02b-5-step-5--local-implementation-and-review-closeout-2026-10-19) owns historical local/source evidence; the [2026-10-20 remediation](../roadmap/phase-02b-delivery-log.md#p02b-5-external-review-remediation-2026-10-20) owns subsequent corrections and PR #33 owns current-head CI. [Amendment 1](0064-tenant-api-authentication-boundary.md#amendment-1--bounded-assertion-diagnostics-2026-10-20) discloses ADR-0065's audit-admission replacement. [Amendment 2](0064-tenant-api-authentication-boundary.md#amendment-2--explicit-subject-registry-bound-and-attribution-2026-10-20) records ADR-0066 acceptance and corrects the old cap attribution. [Amendment 3](0064-tenant-api-authentication-boundary.md#amendment-3--read-mode-instrument-classification-2026-10-20) clarifies read-mode instrument classification. | -| 0065 | [Bounded Tenant Assertion Diagnostics](0065-bounded-tenant-assertion-diagnostics.md) | Accepted 2026-10-20: singleton host-tenant admission of 600 authenticated audit attempts per instance/minute, closed counters and one attributed warning per occurrence; explicitly accepts lost durable actor evidence and unbounded log volume. Ratifies process-wide native outbound metric projection and dependency-attribution cost. Implementation and local proofs are delivered; the [remediation record](../roadmap/phase-02b-delivery-log.md#p02b-5-external-review-remediation-2026-10-20) owns implementation and proof status. [Amendment 1](0065-bounded-tenant-assertion-diagnostics.md#amendment-1--exemplar-export-enforcement-2026-10-20) clarifies exemplar privacy enforcement and its actual export controls. [Amendment 2](0065-bounded-tenant-assertion-diagnostics.md#amendment-2--subject-registry-source-attribution-2026-10-20) corrects subject-registry attribution without changing audit allowance. [Amendment 3](0065-bounded-tenant-assertion-diagnostics.md#amendment-3--delivered-implementation-and-receipt-chronology-2026-10-20) clarifies delivered implementation chronology. | -| 0066 | [Bounded Tenant Subject Admission](0066-bounded-tenant-subject-admission.md) | Accepted 2026-10-20: explicit 4096 retained-subject process bound, one-disposal acquisition reclamation, sole joined cleanup owner and distinct quota/capacity/fault results and metrics. Sticky cleanup fault refuses new keys with 503; quota/capacity stay 429. ADR-0064/0065 each carry inline attribution errata and their own Amendment 2. [Amendment 1](0066-bounded-tenant-subject-admission.md#amendment-1--implementation-and-local-proof-ownership-2026-10-20) records implementation and actual proof owners; the [delivery record](../roadmap/phase-02b-delivery-log.md#adr-0066-acceptance-and-implementation-2026-10-20) owns status. [Amendment 2](0066-bounded-tenant-subject-admission.md#amendment-2--acceptance-time-proof-list-and-cleanup-evidence-2026-10-20) clarifies acceptance-time proof list and cleanup evidence. | +| 0064 | [Tenant API Authentication Boundary](0064-tenant-api-authentication-boundary.md) | Accepted 2026-10-19: strict tenant bearer profile, stable actor/subject quota, closed authenticated read and bounded membership-denial audit replacement; [five-step P02b-5 package](../roadmap/phase-02b-delivery-log.md#p02b-5-decision-package-2026-10-19) approved before implementation. Own dated disclosures in ADR-0036/0040/0052 preserve their Accepted bodies. All five implementation steps and both independent review rounds per step are locally complete; the [Step 5 closeout](../roadmap/phase-02b-delivery-log.md#p02b-5-step-5--local-implementation-and-review-closeout-2026-10-19) owns historical local/source evidence; the [2026-10-20 remediation](../roadmap/phase-02b-delivery-log.md#p02b-5-external-review-remediation-2026-10-20) owns subsequent corrections and PR #33 owns current-head CI. [Amendment 1](0064-tenant-api-authentication-boundary.md#amendment-1--bounded-assertion-diagnostics-2026-10-20) discloses ADR-0065's audit-admission replacement. [Amendment 2](0064-tenant-api-authentication-boundary.md#amendment-2--explicit-subject-registry-bound-and-attribution-2026-10-20) records ADR-0066 acceptance and corrects the old cap attribution. [Amendment 3](0064-tenant-api-authentication-boundary.md#amendment-3--read-mode-instrument-classification-2026-10-20) clarifies read-mode instrument classification. [Amendment 4: P03-1 identity authority](0064-tenant-api-authentication-boundary.md#amendment-4--verified-subjects-and-existing-application-bindings-2026-10-25). | +| 0065 | [Bounded Tenant Assertion Diagnostics](0065-bounded-tenant-assertion-diagnostics.md) | Accepted 2026-10-20: singleton host-tenant admission of 600 authenticated audit attempts per instance/minute, closed counters and one attributed warning per occurrence; explicitly accepts lost durable actor evidence and unbounded log volume. Ratifies process-wide native outbound metric projection and dependency-attribution cost. Implementation and local proofs are delivered; the [remediation record](../roadmap/phase-02b-delivery-log.md#p02b-5-external-review-remediation-2026-10-20) owns implementation and proof status. [Amendment 1](0065-bounded-tenant-assertion-diagnostics.md#amendment-1--exemplar-export-enforcement-2026-10-20) clarifies exemplar privacy enforcement and its actual export controls. [Amendment 2](0065-bounded-tenant-assertion-diagnostics.md#amendment-2--subject-registry-source-attribution-2026-10-20) corrects subject-registry attribution without changing audit allowance. [Amendment 3](0065-bounded-tenant-assertion-diagnostics.md#amendment-3--delivered-implementation-and-receipt-chronology-2026-10-20) clarifies delivered implementation chronology. [Amendment 4: P03-1 identity authority](0065-bounded-tenant-assertion-diagnostics.md#amendment-4--global-creation-remains-outside-mismatch-allowances-2026-10-25). | +| 0066 | [Bounded Tenant Subject Admission](0066-bounded-tenant-subject-admission.md) | Accepted 2026-10-20: explicit 4096 retained-subject process bound, one-disposal acquisition reclamation, sole joined cleanup owner and distinct quota/capacity/fault results and metrics. Sticky cleanup fault refuses new keys with 503; quota/capacity stay 429. ADR-0064/0065 each carry inline attribution errata and their own Amendment 2. [Amendment 1](0066-bounded-tenant-subject-admission.md#amendment-1--implementation-and-local-proof-ownership-2026-10-20) records implementation and actual proof owners; the [delivery record](../roadmap/phase-02b-delivery-log.md#adr-0066-acceptance-and-implementation-2026-10-20) owns status. [Amendment 2](0066-bounded-tenant-subject-admission.md#amendment-2--acceptance-time-proof-list-and-cleanup-evidence-2026-10-20) clarifies acceptance-time proof list and cleanup evidence. [Amendment 3: P03-1 identity authority](0066-bounded-tenant-subject-admission.md#amendment-3--verified-subject-input-before-application-binding-2026-10-25). | | 0067 | [Development Tenant Access-Token Issuance](0067-development-tenant-access-token-issuance.md) | Accepted 2026-10-21 after separate maintainer approval: dedicated authority for the already approved 900s development issuance choice, inherited ID-token expiration and bounded provider timestamp/session semantics. Security 11 owns the ongoing rule; API acceptance and BFF session policy remain separate. The [acceptance record](../roadmap/phase-02b-delivery-log.md#adr-0067-acceptance-and-carrier-reconciliation-2026-10-21) preserves original phase approval and source-bound proof/review status. | -| 0068 | [Development Warm-Realm Qualification](0068-development-warm-realm-qualification.md) | Accepted 2026-10-22 under conditional maintainer authority after verified review corrections: identity-independent prechecks, one bounded profile preparation and three qualified stock-console assignment detachments. Implementation and automatic-path qualification remain pending; the [acceptance record](../roadmap/phase-02b-delivery-log.md#adr-0068-acceptance-and-implementation-2026-10-22) owns the three-step plan and proof status. | +| 0068 | [Development Warm-Realm Qualification](0068-development-warm-realm-qualification.md) | Accepted 2026-10-22 under conditional maintainer authority after verified review corrections: identity-independent prechecks, one bounded profile preparation and three qualified stock-console assignment detachments. The [acceptance record](../roadmap/phase-02b-delivery-log.md#adr-0068-acceptance-and-implementation-2026-10-22) owns the three-step plan and proof status. | | 0069 | [Phase Documents and Delivery Logs](0069-phase-documents-and-delivery-logs.md) | Accepted 2026-10-22 after one review round: each phase keeps its plan in the phase document and its dated packet records in a sibling append-only delivery log whose Accepted decision packages stay normative; packet status lives once, in the phase document's bounded Status block; a whole-tree Markdown fragment audit and a roadmap structure guard enforce both, with Phase 02a, Phase 01 and ten Phase 02d entries declared as legacy shapes. | -| 0070 | [Owned Tenant BFF Sessions](0070-owned-tenant-bff-sessions.md) | Accepted 2026-10-23: openid-client, bounded native credential custody and host-only opaque cookies; qualified development provider events. Dated ADR-0035/0053/0054 disclosures preserve earlier bodies. The [acceptance record](../roadmap/phase-02b-delivery-log.md#p02b-7-acceptance-and-implementation-2026-10-23) owns authorized implementation and proof status. [Amendment 1](0070-owned-tenant-bff-sessions.md#amendment-1--delivered-proof-owners-and-read-failure-clarification-2026-10-24) names delivered proof owners and clarifies ordinary-read availability and source-IP limits. | -| 0071 | [Uncertain AccountSite Refusals](0071-uncertain-account-site-refusals.md) | Accepted 2026-10-24: explicit ordinary-read AccountSite status decision and ratification; ambiguous 401 retains local ownership without granting checked authority, while callback/post-refresh failures still refuse/revoke. [ADR-0070 Amendment 2](0070-owned-tenant-bff-sessions.md#amendment-2--explicit-accountsite-status-decision-2026-10-24) preserves its original history; the [acceptance record](../roadmap/phase-02b-delivery-log.md#adr-0071-acceptance-and-review-corrections-2026-10-24) owns the authorized correction plan and proof status. | +| 0070 | [Owned Tenant BFF Sessions](0070-owned-tenant-bff-sessions.md) | Accepted 2026-10-23: openid-client, bounded native credential custody and host-only opaque cookies; qualified development provider events. Dated ADR-0035/0053/0054 disclosures preserve earlier bodies. The [acceptance record](../roadmap/phase-02b-delivery-log.md#p02b-7-acceptance-and-implementation-2026-10-23) owns authorized implementation and proof status. [Amendment 1](0070-owned-tenant-bff-sessions.md#amendment-1--delivered-proof-owners-and-read-failure-clarification-2026-10-24) names delivered proof owners and clarifies ordinary-read availability and source-IP limits. [Amendment 4: P03-1 identity authority](0070-owned-tenant-bff-sessions.md#amendment-4--existing-session-identity-foundation-navigation-2026-10-25). | +| 0071 | [Uncertain AccountSite Refusals](0071-uncertain-account-site-refusals.md) | Accepted 2026-10-24: explicit ordinary-read AccountSite status decision and ratification; ambiguous 401 retains local ownership without granting checked authority, while callback/post-refresh failures still refuse/revoke. [ADR-0070 Amendment 2](0070-owned-tenant-bff-sessions.md#amendment-2--explicit-accountsite-status-decision-2026-10-24) preserves its original history; the [acceptance record](../roadmap/phase-02b-delivery-log.md#adr-0071-acceptance-and-review-corrections-2026-10-24) owns the authorized correction plan and proof status. [Amendment 2: P03-1 identity authority](0071-uncertain-account-site-refusals.md#amendment-2--binding-uncertainty-preserves-ordinary-read-refusals-2026-10-25). | +| 0072 | [Application-Owned Identity Bootstrap](0072-application-owned-identity-bootstrap.md) | Accepted jointly with ADR-0073 on 2026-10-25: stable authority/digest binding, prepared common global creation/audit and route-independent existing-binding admission. New-user HTTP/BFF activation remains P03-3; the [Phase 03 Status block](../roadmap/phase-03-identity-admin.md) owns implementation and qualification state. | +| 0073 | [Scoped Membership and Identity Data Foundation](0073-scoped-membership-and-identity-data-foundation.md) | Accepted jointly with ADR-0072 on 2026-10-25: contained Membership state, tenant-wide Role templates, finite manifests, fresh administration invariants and semantic PII census. No live authorization or production first-admin path is activated by acceptance. | +| 0074 | [Membership Admission Under Ordered Locks](0074-membership-admission-under-ordered-locks.md) | Accepted 2026-10-26: creation/reactivation and every assignment addition retain User-before-tenant fences; the real mutation trigger freshly verifies eligibility under the complete preheld plan. No reader, scope or grant is added; the [Phase 03 Status block](../roadmap/phase-03-identity-admin.md) owns current implementation and qualification state. | +| 0075 | [Ordinary CI Job Window](0075-ordinary-ci-job-window.md) | Accepted 2026-10-27: ordinary-only twenty-five-minute whole-job and expected-owner observation bounds, with own-record ADR-0062/0063 amendments. Other ceilings, counts, assignment, reserves and resource policy stay fixed; the [Phase 03 Status block](../roadmap/phase-03-identity-admin.md) owns implementation and fresh A/B qualification state. | ## Proposed ADRs diff --git a/docs/glossary.md b/docs/glossary.md index 1778dfb52..f06f08c22 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -23,13 +23,22 @@ This glossary defines LearnStack-specific terms. When a term is ambiguous across | Term | Definition | |------|------------| -| **User** | A person known to LearnStack at the global level. Identified by a stable user id. | -| **Membership** | The relationship between a user, a tenant, and (optionally) an organization. Triple-keyed `(user_id, tenant_id, organization_id)` per [ADR-0017](decisions/0017-tenant-organization-hierarchy.md). A user can have memberships in multiple tenants and multiple organizations within one tenant. | -| **Role** | A named bundle of permissions. Scope: `Platform` / `Tenant` / `Organization`. Examples: `tenant-admin`, `editor`, `instructor`, `learner`, `org-admin`. | +| **User** | A global application binding identified by the existing strongly typed `UserId`, separate from contextual Memberships. The permanent authority/subject-key mapping and lifecycle follow Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md). | +| **Identity authority** | Stable provider namespace identified by a UUID and anchored to one current exact issuer URI in a deployment-installed, application-read-only singleton. Issuer drift cannot replace it. Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md) assigns installation to P03-1 and controlled rebind to P03-9/G13. | +| **Identity subject binding** | Permanent mapping from stable identity authority and exact opaque subject, through the subject key, to one application actor. Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md) / [ADR-0073](decisions/0073-scoped-membership-and-identity-data-foundation.md) contract. | +| **Identity subject key** | Nonsecret SHA-256 equality and audit-linkage key derived from stable authority UUID and exact opaque subject under Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md). It remains personal data, including for low-entropy subjects vulnerable to guessing. The [Database standard](standards/05-database.md#proposed-p03-1-identity-storage-annex) owns canonical encoding; [Data Protection](architecture/23-data-protection.md#proposed-identity-foundation-and-classification-ownership) owns retention purpose. | +| **Global-self bootstrap** | Admitted creation of only the verified provider subject's application binding, with no tenant Membership or permission. Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md) supplies the common internal contract; P03-1 admits fixed seed adoption only. New-user HTTP/BFF activation requires its P03-3 contract; no such route is currently admitted. | +| **Bootstrap admission** | Eligibility of a verified provider subject to attempt binding creation under the independently admitted operation, authority, lifecycle and quota checks of Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md). It establishes no tenant Membership, invitation acceptance or ordinary BFF session. New-user HTTP/BFF activation remains P03-3. | +| **Closure tombstone** | Retained Closed binding preserving subject key and actor indefinitely to refuse recreation, with raw subject removed by separately authorized closure. It remains linkable personal data, not anonymisation or a reusable actor reservation. Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md) defines the foundation; [Data Protection](architecture/23-data-protection.md#erasure-authority-and-first-writer-prerequisites) assigns actual closure/retained-copy fulfillment to P03-10. | +| **Proposed identity target** | Audit attribution for the actor a creation attempt intended to establish, distinct from its authenticated actor. A failed or indeterminate attempt proves neither User commitment nor target authentication. Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md) contract. | +| **Membership** | Contextual relationship between a global User, tenant and optional organization. Accepted [ADR-0073](decisions/0073-scoped-membership-and-identity-data-foundation.md) defines a typed MembershipId and null-safe current uniqueness on `(tenant_id,user_id,organization_id)` for Active/Suspended rows; Revoked is terminal and rejoin creates a successor. | +| **MembershipProfile** | Tenant-owned, organization-scoped contained contextual profile of one Membership under Accepted [ADR-0073](decisions/0073-scoped-membership-and-identity-data-foundation.md). P03-1 supplies bounded contextual fields; P03-3 decides self/admin DTOs and P03-5 adds revision-aware custom values. No dynamic-value column or consent authority is implied by the foundation; consent follows [Data Protection](architecture/23-data-protection.md#consent-management). | +| **Role** | A named scoped capability bundle. Accepted [ADR-0073](decisions/0073-scoped-membership-and-identity-data-foundation.md) stores tenant-wide templates with Tenant or Organization capability; exact branch authority comes from the Membership assignment. Platform roles have no tenant template. Finite initial/adopted grants follow [Permissions](standards/19-permissions.md#proposed-identity-foundation-contract). | | **Permission** | A fine-grained capability `{module}.{resource}.{action}` with a scope (Platform / Tenant / Organization). Action set is closed: `read \| write \| delete \| admin`. | | **Invitation** | A pending offer for a user to accept a membership in a tenant + organization. | | **Development realm reconciliation** | P02b-6 tooling operation that converges the named tenant-realm configuration and demo identity attributes on a fresh or existing local Keycloak database. It preserves account identity and credentials, does not provision application memberships and is not the runtime `IIdentityProvider`. The [P02b-6 decision package](roadmap/phase-02b-delivery-log.md#p02b-6-decision-package-2026-10-20) owns its approved field/capability boundaries; the [Step 3 record](roadmap/phase-02b-delivery-log.md#p02b-6-step-3--shared-seeddemo-lifecycle-2026-10-21) records delivered entry-point convergence and the Step 4 record owns remaining qualification. | -| **Validated tenant identity** | P02b-5 request-local immutable projection of a successfully validated tenant access token: its issuer/subject, stable actor and optional scalar tenant/organization. Actor attribution is independent of tenant authority: a claimless actor can remain HostOnly and cannot enter protected reads. It proves neither live membership nor permission. Accepted [ADR-0064](decisions/0064-tenant-api-authentication-boundary.md) owns the contract; the P02b-5 delivery record owns implementation status. | +| **Verified provider subject** | Immutable `VerifiedProviderSubject` evidence produced by stock credential validation: exact issuer and opaque subject, with optional compatibility actor and tenant/organization claims. It grants no application actor, Membership or permission; ordinary admission independently resolves an existing binding before publishing a validated tenant identity. [Security Standards](standards/11-security.md#credential-quota-and-binding-order) owns the ordered handoff. | +| **Validated tenant identity** | Normalized request-local application identity after verified provider-subject admission and existing-binding resolution under Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md). Its actor is nonnullable; optional API wire `user_id` is evidence checked against the binding. It proves neither live Membership nor permission. Complete native sessions retain actor/tenant/AccountSite proof. | | **Claimless principal** | A validated tenant API identity without a tenant claim. It keeps the HostOnly public ceiling; it cannot acquire tenant authority merely through its actor UUID. See [ADR-0064](decisions/0064-tenant-api-authentication-boundary.md#access-token-profile). | | **BFF session owner** | Process-local credential and lifecycle authority in the native web process, separate from public request admission. Accepted [ADR-0070](decisions/0070-owned-tenant-bff-sessions.md) governs it; its opaque host-bound cookie proves no tenant membership or permission. | | **BFF session revision** | Logical server-side version published by one successful session refresh, independent of cookie delivery. See [ADR-0070](decisions/0070-owned-tenant-bff-sessions.md#effective-lifetime-activity-and-refresh); P02b-7 owns implementation. | @@ -145,8 +154,8 @@ This glossary defines LearnStack-specific terms. When a term is ambiguous across | **Tenant-owned, organization-scoped** | Adds a nullable `organization_id`, the `app.scope` read hatch, and two `AS RESTRICTIVE` write guards. | | **Parent organization mirror** | A child's organization scope matching its parent's exactly, including tenant-wide `NULL` scope. The factory derives it; the database's **parent-scope guard** independently checks it on INSERT and UPDATE. [Database Standards](standards/05-database.md#parent-organization-mirrors) owns the guard alongside the tenant-composite foreign key and organization immutability control. | | **Tenant-owned, self-keyed** | `tenants` itself. It has **no** `tenant_id` column — its `id` *is* the tenant id, so its policy keys on `id`. | -| **Platform-scoped table** | A table no tenant predicate can isolate — either because it is read *before* a tenant is known, or because its rows belong to no tenant at all. Two exist, and a third is a decision, not a convenience: `platform_host_to_tenant`, whose policies are qualified `TO learnstack_app` and admit the announced host while every write stays tenant-keyed; and `platform_killswitches`, which carries no tenant column and no foreign key — `learnstack_app` reads it `USING (true)`, because a switch every instance must honour cannot be hidden from the role that honours it, and every write is reserved to `learnstack_platform` through `EnterPlatformAdminScope(reason)` ([ADR-0045 § 5](decisions/0045-entitlement-and-feature-flag-socket.md)). | -| **Global table** | A table with no tenant dimension at all — a person, not a person-in-a-tenant. `users` is the case ([Phase 03](roadmap/phase-03-identity-admin.md)); tenancy arrives through the membership row beside it. `tenants` is **not** one: it is tenant-owned, self-keyed. | +| **Platform-scoped table** | A table no tenant predicate can isolate, because it is read before tenant resolution or its rows belong to no tenant. The shipped tables are `platform_host_to_tenant` and `platform_killswitches`; Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md) adds the deployment-installed `identity_authority` anchor. Exact role/command policies and grants live only in [Database Standards](standards/05-database.md#table-classes). A new table needs its own class decision. | +| **Global table** | A relation without tenant/organization columns whose rows represent global identity, rather than a person-in-a-tenant. Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md) assigns `users` to the global self-identity class with independent verified-subject EF filtering and FORCE RLS. No global-directory or platform bypass follows. `tenants` remains tenant-owned/self-keyed. | | **Tenant context** | The ambient resolved tenant and optional organization for a request, job or background task. Factory-preserved `HostScope` records the independent host ceiling under [ADR-0036 Amendment 8](decisions/0036-tenant-resolution-trusted-inputs.md#2026-10-03--amendment-8-public-host-provenance); P02d-4 Step 1 delivers this provenance and admission guard. | | **`HostScope`** | Immutable nullable host tenant/organization provenance constructed only by TenantContextFactory from the reconciled host signals, independently of claim-selected organization scope. Ambient, unresolved and claim-only contexts carry none. Accepted in [ADR-0036 Amendment 8](decisions/0036-tenant-resolution-trusted-inputs.md#2026-10-03--amendment-8-public-host-provenance) and [ADR-0052](decisions/0052-anonymous-public-read-boundary.md); delivered by P02d-4 Step 1. | | **Query filter** | EF Core global query filter that injects `WHERE tenant_id = @current_tenant_id` automatically. | @@ -260,16 +269,16 @@ These entries distinguish P02d-2 contracts from P02d-3 internal read contracts: | Term | Definition | |------|------------| -| **AuditEntry** | The append-only aggregate owned by `LearnStack.Modules.Audit`. Inherits `Entity`, **not** `AuditableEntity` — append-only by design (`AuditEntry_Inherits_Entity_Not_AuditableEntity`). Persisted to `audit_log`, whose primary key is the composite `(id, timestamp)` and whose `AuditEntryId` is minted **app-side** at pipeline step 3 — the one append-only table that is, because the `Indeterminate` pair has to carry a single identity across two connections ([ADR-0023 Amendment 9](decisions/0023-strongly-typed-id-source-generator.md)). `PostgresAuditStore` always supplies `timestamp` from `IClock` — the intent's `DeclaredAt` for the in-transaction row, a **fresh** reading for a standalone re-write — which is what keeps that pair legal under the composite key rather than a `23505`; `DEFAULT now()` stays only as a backstop. It carries `Outcome` — `success \| denied \| failed \| indeterminate`, a `text` column under a `CHECK`, superseding ADR-0016's `is_success boolean` — and `Reason`. Its `tenant_id` is the tenant the ambient transaction **announced**, never a request payload. `audit_log` is **tenant-owned, organization-scoped** and takes the canonical template from [Database Standards § Table classes](standards/05-database.md) unmodified, in a fourth migration chain owned by `AuditDbContext`; it carries **no** foreign key to `tenants`, because the sentinel has no `tenants` row and a record that cascades on tenant deletion is not an audit log. `audit_config` keeps its FK. See [ADR-0033](decisions/0033-audit-durability-model.md), [ADR-0044 §§ 2, 5, 9](decisions/0044-audit-write-path.md) and [31-audit-subsystem.md](architecture/31-audit-subsystem.md). | +| **AuditEntry** | The append-only aggregate owned by `LearnStack.Modules.Audit`. Inherits `Entity`, **not** `AuditableEntity` — append-only by design (`AuditEntry_Inherits_Entity_Not_AuditableEntity`). Persisted to `audit_log`, whose primary key is the composite `(id, timestamp)` and whose `AuditEntryId` is minted **app-side** at pipeline step 3 — the one append-only table that is, because the `Indeterminate` pair has to carry a single identity across two connections ([ADR-0023 Amendment 9](decisions/0023-strongly-typed-id-source-generator.md)). `PostgresAuditStore` always supplies `timestamp` from `IClock` — the intent's `DeclaredAt` for the in-transaction row, a **fresh** reading for a standalone re-write — which is what keeps that pair legal under the composite key rather than a `23505`; `DEFAULT now()` stays only as a backstop. It carries `Outcome` — `success \| denied \| failed \| indeterminate`, a `text` column under a `CHECK`, superseding ADR-0016's `is_success boolean` — and `Reason`. Ordinary rows carry the tenant the ambient transaction **announced**, never a request payload. Accepted ADR-0072 separately fixes sentinel attribution for typed global creation. `audit_log` is **tenant-owned, organization-scoped** and uses the ordinary tenant template plus Accepted ADR-0072's exact global-identity insertion/evidence departure from [Database Standards](standards/05-database.md#proposed-global-central-audit-branch), in the Audit migration chain; it carries **no** foreign key to `tenants`, because the sentinel has no `tenants` row and a record that cascades on tenant deletion is not an audit log. `audit_config` keeps its FK. See [ADR-0033](decisions/0033-audit-durability-model.md), [ADR-0044 §§ 2, 5, 9](decisions/0044-audit-write-path.md) and [31-audit-subsystem.md](architecture/31-audit-subsystem.md). | | **`OperationType` / `OperationClass` / `AuditClassification`** | Three enums, two of which are fields on `AuditEntry`. **`OperationType`** is what kind of operation produced the row: `create`, `update`, `delete`, `read-sensitive`, `security-event`, `platform-admin`, `action`. **`OperationClass { Must, Should, May }`** is the coverage tier the matrix and the catalogue **declare**, and the tier the row persists. **`AuditClassification { Off, May, Should, Must, Unclassified }`** is what `IAuditConfigService.ClassifyAsync` **returns**, after the tenant's `AuditConfig` override and the MUST floor: `Off` is how a request that writes no row is registered — the test-only request types among them — and `Unclassified` is the rejection behind `audit_unclassified_operation`. The two are not one enum with a spare member: `OperationClass` is a persisted column no row can legally hold an `Off` in. All three live in `LearnStack.SharedKernel.Audit` beside the ports that name them, never in the Audit module's `Domain`, which would make SharedKernel reference the module back. `OperationType` and `OperationClass`, with the default class for each type, are defined once in [Audit Coverage Standards § Operation Types](standards/18-audit-coverage.md); the audit catalogue supplies both alongside the operation slug. Per [ADR-0044 §§ 6, 11 and Amendment 3](decisions/0044-audit-write-path.md). | | **Audit Operation Key** | The catalogue key `(module, operation)`, where `operation` is the dotted slug `{module}.{resource}.{verb}` — `tenancy.tenant.create`, `customization.content_type.publish`. It borrows the **shape** of a *Permission Key* and shares its first two segments with the permission gating the same resource, but **not** its closed action set: an audit verb records what happened and comes from the module's own coverage matrix (`create`, `publish`, `revise`, `rename`, `soft_delete`, …), where a permission action bounds what a principal may do. There is no `RequestKind.Other` — every `IRequest>` reaching pipeline step 3 must be classified, an unregistered one is rejected with `audit_unclassified_operation` (500), and test-only request types register through the same builder in their fixture. Per [ADR-0044 § 6](decisions/0044-audit-write-path.md). | | **Audit Coverage Matrix** | The per-module table in `docs/modules//audit.md` mapping resources × operations to MUST / SHOULD / MAY / – classifications, with an `Operation` column carrying the dotted slug. Required for every module spec. It is the human-readable artifact; the **audit catalogue** — declared in code through `IAuditCatalogSource.Describe(IAuditCatalogBuilder)`, discovered from DI and keyed by request type — is the executable one. Neither is parsed from the other: `Every_TenantOwned_Command_HasAuditCoverage` (catalogue → matrix) and `Every_Matrix_Row_Whose_Command_Exists_Is_Registered` (matrix → catalogue) assert they agree, in **two directions with two domains**. *Catalogue → matrix is total* — every entry a module's source registers has a row in that module's matrix carrying the same slug, no exemption. *Matrix → catalogue binds only to slugs whose request type exists* — a row classified ahead of the command that will raise it carries **`(planned)`** in the `Operation` cell and is outside that direction, because classifying before the command ships is what the standard asks for. The marker is a claim the rule re-checks, not an escape: a `(planned)` row whose command **has** shipped fails. Operations that are not MediatR requests at all carry **`(off-path)`**, are outside the join in both directions, and register by slug rather than by type; the closed list of them is enumerated once, in the amendment that decides it. Per [ADR-0044 § 6 and Amendment 3](decisions/0044-audit-write-path.md). | | **AuditConfig** | The per-tenant override of the catalogue's coverage, held as a cached projection whose loader runs on a cache miss on its own short transaction — once per tenant and generation, never once per request. It **narrows and never elevates**: `is_enabled = false` silences a SHOULD or a MAY, `true` is the baseline, and neither touches a MUST. The classifier applies the override and then re-applies the catalogue's MUST floor. Elevation is refused rather than deferred: a lever that moved an operation onto the durable path would let a tenant admin provoke a `503` on operations the platform classified MAY ([ADR-0033 Amendment 4](decisions/0033-audit-durability-model.md)). A failure to **read** it does **not** reject the operation: classification falls back to the in-process catalogue, which carries the same MUST floor, so nothing proceeds unaudited and one cache outage does not deny every request platform-wide. The failure logs at `Error`; the audit health check does not move, because it answers only whether a MUST-class row can be written. Per [ADR-0033 and its Amendment 6](decisions/0033-audit-durability-model.md). | | **Audit Capture Pipeline** | `AuditChangeTrackerInterceptor` (EF) → `IAuditStateCapture` (before/after/`changes` JSON) → `AuditExecutionCoordinator` (MediatR adapter or direct owner) → `IAuditStore`. Modules never write `audit_log` directly. The interceptor captures **every** `ChangeTracker` entry in state `Added`, `Modified` or `Deleted`, minus the named machinery/audit exclusion list (including P3's shared inbox and delivery ledger), owned by Audit Coverage below. The earlier `AuditableEntity<>`-descendants predicate is withdrawn: it was blind to every plain class the modules ship, `PlatformHostMapping` and the other MUST-classified ones among them — [Audit Coverage § Required Behaviours](standards/18-audit-coverage.md#required-behaviours) lists them with their classes. It sees only what the `ChangeTracker` holds, so EF Core's set-based writes (`ExecuteUpdate`, `ExecuteDelete`, `ExecuteSql*`) would escape it and backend source uses none. It **captures only** — no row construction, no SQL — and reaches every module `DbContext` through `AddModuleDbContext`, which resolves `IEnumerable` from the provider, because DI registration alone does not attach it. An entity that is not an aggregate root and is reached through its root's navigation — a taxonomy's bands — is captured **inside its root's** diff rather than on its own, and in its root's snapshot only when the root was created in the same request and every member it was seen with is still tracked, the one case its membership is known to be complete; a filtered `Include` marks a partial collection loaded, so a loaded one is left out as unknown. `changes` serialises as a JSON **array** of `{ path, before, after }` with an instance-qualified pointer — `/{EntityType}/{EntityId}` and then an RFC 6901 pointer into that instance's snapshot — never ADR-0016's polymorphic object-or-array shape. Per [ADR-0044 § 7 and Amendment 6 §§ 4–5](decisions/0044-audit-write-path.md). | | **Elision Record** | What replaces a snapshot value too large to store: `{"_elided": true, "bytes": , "sha256": ""}` — never an empty object and never a silent truncation. Each of `before_state`, `after_state` and `changes` is capped at `JsonValue.MaxRowBytes` (256 KiB). The elision **preserves the column's JSON type**: `changes` is an array on both sides of the cap, so an elided `changes` is `[{"_elided": …}]`, while `before_state` and `after_state` take the object form — a reader must not have to branch on shape to know what it is reading. `audit_blob_id` is struck from the corpus: it exists in no DDL and names no blob store. Per [ADR-0044 § 8](decisions/0044-audit-write-path.md). | -| **Audit Intent** | One parked declaration that an audited `(resource, operation)` happened, minted with its `AuditEntryId` by `AuditExecutionCoordinator` (through step 3 for requests) and held in `IAuditStateCapture` as an **ordered list** — one intent per audited `(resource, operation)`, **not** one per request. `ProvisionTenantCommand` declares two, `tenancy.tenant.create` and `tenancy.organization.create`, which is why "exactly one intent per request" is retired. Only the **owning** unit-of-work frame (`IUnitOfWorkScope.IsOwner`) flushes the intents, signals `Committed` / `RolledBack` / `Indeterminate`, and it drains every intent in the scope rather than only its own; a joiner writes nothing and signals nothing. Only the outermost audit frame reconciles and calls `Clear()`; a nested frame that cleared would erase the outer execution's intents before commit. It also carries the `TenantId` and optional `OrganizationId` its row will be written under, resolved by `AuditExecutionCoordinator` before deferred work — through step 3 for requests, where ADR-0044 § 2's four cases are decidable, and the reason `PostgresAuditStore` composes a row from the intent rather than resolving a tenant itself. It carries the actor and the correlation id too, read at the same moment, so both writers write them. Every classified `AuditExecutionCoordinator` invocation opens an audit **frame**: an intent belongs to the frame that declared it, a captured change to the frame whose handler flushed it, and closing a frame records on its intents what that request returned — so a nested request refused under an outer one that commits keeps its refusal. Per [ADR-0044 §§ 2, 3, 4, Amendment 3 and Amendment 6 §§ 2–3](decisions/0044-audit-write-path.md) and [ADR-0033 Amendment 2](decisions/0033-audit-durability-model.md). | +| **Audit Intent** | One parked declaration that an audited `(resource, operation)` happened, minted with its `AuditEntryId` by `AuditExecutionCoordinator` (through step 3 for requests) and held in `IAuditStateCapture` as an **ordered list** — one intent per audited `(resource, operation)`, **not** one per request. `ProvisionTenantCommand` declares two, `tenancy.tenant.create` and `tenancy.organization.create`, which is why "exactly one intent per request" is retired. Only the **owning** unit-of-work frame (`IUnitOfWorkScope.IsOwner`) flushes the intents, signals `Committed` / `RolledBack` / `Indeterminate`, and it drains every intent in the scope rather than only its own; a joiner writes nothing and signals nothing. Only the outermost audit frame reconciles and calls `Clear()`; a nested frame that cleared would erase the outer execution's intents before commit. It also carries the `TenantId` and optional `OrganizationId` its row will be written under, resolved by `AuditExecutionCoordinator` before deferred work — through step 3 for requests, where ADR-0044 § 2's original tenant/platform cases are decidable, and the reason `PostgresAuditStore` composes a row from the intent rather than resolving a tenant itself. It carries the actor and the correlation id too, read at the same moment, so both writers write them. Every classified `AuditExecutionCoordinator` invocation opens an audit **frame**: an intent belongs to the frame that declared it, a captured change to the frame whose handler flushed it, and closing a frame records on its intents what that request returned — so a nested request refused under an outer one that commits keeps its refusal. Per [ADR-0044 §§ 2, 3, 4, Amendment 3 and Amendment 6 §§ 2–3](decisions/0044-audit-write-path.md) and [ADR-0033 Amendment 2](decisions/0033-audit-durability-model.md). | | **Audit Subject** | The one aggregate instance an audit row is about: its `entity_id`, `before_state` and `after_state`. The composer finds it among the captures of the intent's declared type; when a request writes **two** instances of that type — a publication retires the incumbent revision and activates the successor — the handler names it through `IAuditSubject.Designate(aggregate)`, and every other instance stays in `changes` under its own instance-qualified pointer. Undesignated, two instances are refused rather than guessed between. A designation binds only the current request's intents of that type. Per [ADR-0044 Amendment 6 § 1](decisions/0044-audit-write-path.md). | -| **Durable Audit Intent** | The MUST-class audit row, written by `IAuditStore.WritePendingAsync` on the **same transaction as the business write** — `AuditExecutionCoordinator` classifies and parks each intent (through step 3 for requests), and `TransactionExecutionCoordinator` writes them all, on the owning frame only, immediately before `COMMIT` — so each commits with that write or not at all, and so each executes while `app.tenant_id` is set and the Row Level Security `WITH CHECK` accepts it. "The same `SaveChanges`" was the earlier formulation and ADR-0033 withdraws it: the guarantee is the transaction, which needs no cross-`DbContext` machinery. If it cannot be written, the business operation **fails closed**. Enrichment, redaction, projection, and external fan-out happen after the commit, reading the durable row, and are best-effort. SHOULD/MAY-class audit is **not** a durable intent: it is written outside the transaction, and its accepted loss is written down rather than assumed. Per [ADR-0033](decisions/0033-audit-durability-model.md), which supersedes ADR-0016. | +| **Durable Audit Intent** | The MUST-class audit row, written by `IAuditStore.WritePendingAsync` on the **same transaction as the business write** — `AuditExecutionCoordinator` classifies and parks each intent (through step 3 for requests), and `TransactionExecutionCoordinator` writes them all, on the owning frame only, immediately before `COMMIT` — so each commits with that write or not at all, and so each ordinary tenant write executes under its announced scope. Accepted ADR-0072's typed global pending seam uses its separately enrolled identity scope, never a tenant sentinel announcement. "The same `SaveChanges`" was the earlier formulation and ADR-0033 withdraws it: the guarantee is the transaction, which needs no cross-`DbContext` machinery. If it cannot be written, the business operation **fails closed**. Enrichment, redaction, projection, and external fan-out happen after the commit, reading the durable row, and are best-effort. SHOULD/MAY-class audit is **not** a durable intent: it is written outside the transaction, and its accepted loss is written down rather than assumed. Per [ADR-0033](decisions/0033-audit-durability-model.md), which supersedes ADR-0016. | | **MUST-class audit** | The coverage tier whose admitted event's row is part of the operation's contract (the only bounded authenticated assertion admission exception is [ADR-0065](decisions/0065-bounded-tenant-assertion-diagnostics.md); tenant `AuditConfig` cannot weaken general mutation coverage), and whose two shapes fail differently. **In-transaction** — the durable intent above: a row that cannot be written leaves zero business rows and answers `503 audit_unavailable`. **Standalone** — written by `IAuditStore.WriteStandaloneAsync` on its own transaction, which announces **both** `app.tenant_id` and `app.organization_id` from the draft, since an org-scoped row written with the organization GUC unset fails `WITH CHECK`: its failure changes the response **only when the operation would otherwise have succeeded**. A standalone row recording an operation that is already being refused — a `denied` authorisation outcome, a rejected tenant assertion — keeps its own 403 / 404; the failure logs at `Critical`, increments the standalone-write-failure counter and marks the audit health check unhealthy. Per [ADR-0033 Amendments 1 and 2](decisions/0033-audit-durability-model.md) and [ADR-0044 §§ 9, 11](decisions/0044-audit-write-path.md). | | **Retention Class** | The retention floor for a category of audit entries (7y for security-event / platform-admin / financial; 2y for others). Enforced by a **daily** Hangfire purge job from [Phase 11](roadmap/phase-11-production-hardening.md). | @@ -278,7 +287,7 @@ These entries distinguish P02d-2 contracts from P02d-3 internal read contracts: | Term | Definition | |------|------------| | **Permission Key** | A dotted string `{module}.{resource}.{action}` with `action` drawn from the closed set `read \| write \| delete \| admin`. Domain terms (CEFR, English, yoga, …) are forbidden in keys. | -| **Permission Scope** | One of `platform` (Hub operators), `tenant` (within a tenant), or `organization` (within one organization). Registries are disjoint. | +| **Permission Scope** | One of Platform, Tenant or Organization. Definitions are identified by `(scope,key)` under Accepted [ADR-0073](decisions/0073-scoped-membership-and-identity-data-foundation.md); Tenant/Organization may register the same key as distinct capabilities. Platform definitions never enter tenant Roles. | | **Permission Matrix** | A per-module table mapping `Resource × Action` to ✓ / – plus default role grants. Required for every module spec. | ## Page Builder @@ -318,7 +327,7 @@ These entries distinguish P02d-2 contracts from P02d-3 internal read contracts: | **UI Catalogue** | App-owned platform messages under `frontend/apps/web/src/i18n/messages//.json`. Accepted [ADR-0027](decisions/0027-frontend-i18n.md) selects exact next-intl 4.14.9 and complete `en`/`tr` `public` catalogues, implemented by P02d-6 Step 1 with the server request runtime and catalogue controls. General UI identifiers are dotted feature keys, distinct from backend `lockey_*`. Whole-catalogue language fallback never changes admitted content locale; missing used keys in supported catalogues fail validation. The SDK contains no translations. | | **`None`** | The `readonly record struct` value used as `Result` when a command/query succeeds without returning data — replaces the `Result` with `IsSuccess = true` and `Value = null` shape Standards 09 § Forbidden bans. | | **`IClock` / `IRandom` / `IGuidFactory`** | The three deterministic-test abstractions in `LearnStack.SharedKernel`. Production code never reads `DateTime.UtcNow`, instantiates `System.Random`, or calls `Guid.NewGuid()` directly — those calls go through the abstractions so tests pin the values via `FixedClock` / `FixedRandom` / `FixedGuidFactory`. Per Standards 02 § Time. | -| **`UserId`** | The cross-cutting strongly-typed actor identifier in `LearnStack.SharedKernel.Identifiers` (Vogen `[ValueObject]`). Audit columns on `AuditableEntity` reference users by `UserId` so the "no raw `Guid` on the public surface" rule (Standards 02) holds even though the Identity module lands in [Phase 03](roadmap/phase-03-identity-admin.md). Identity consumes the same type when it ships. | +| **`UserId`** | The existing cross-cutting strongly typed actor identifier in `LearnStack.SharedKernel.Identifiers` (Vogen `[ValueObject]`), also used by global User under Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md). Audit columns retain typed actor references without a User FK; Membership's separately declared same-module User reference does not change that. | | **`Entity` / `AuditableEntity`** | The two aggregate bases in `LearnStack.SharedKernel.Domain`. `Entity` is the append-only / audit-row base — identity, in-process domain events, identity-based equality with **uninitialized-id + cross-runtime-type guards** so `HashSet`-backed collection navigations, `Distinct()` and `Contains` behave correctly before ids are minted. EF Core's change tracker is not among the reasons — it keys on the primary-key value and tracks by reference, never calling these members. `AuditableEntity` is the mutable base — adds `CreatedAt/By`, `UpdatedAt/By`, `DeletedAt/By`, `Version`, and the `IsDeleted` projection by implementing `ISoftDelete` + `IOptimisticConcurrency`. Three ordering guards, all throwing `InvalidOperationException`: `MarkCreated` refuses a second call, `SoftDelete` refuses a second delete (both because audit-trail integrity rules out silent overwrites), and `MarkUpdated` / `SoftDelete` refuse to run before `MarkCreated` — measured, without that last one an update left `CreatedAt` at the `0001-01-01` sentinel and a later `MarkCreated` produced a row whose `updated_at` preceded its `created_at`. `SoftDelete` also stamps `UpdatedAt` with the same instant so a job scanning `UpdatedAt` sees the delete; that is not a monotonicity promise, which nothing enforces — the caller's `IClock` is what supplies forward time. `AuditEntry` (audit subsystem) inherits `Entity` — never `AuditableEntity` — by architecture-test rule. | | **`IDomainEvent`** | The marker interface (`: MediatR.INotification`) every in-process domain event implements. Raised from aggregate methods; P02b-1 Step 3 collects successfully saved facts and dispatches them sequentially through MediatR during owner completion, before MUST audit and commit. The abstract `DomainEvent` base declares `EventId` and `OccurredAt` as `required init` so events are always stamped through `IGuidFactory` / `IClock` at the call site. Distinct from integration events, which cross module boundaries through the outbox + `IEventBus` (`InProcessEventBus` today; Dapr pub/sub after its trigger) per [ADR-0038](decisions/0038-cross-cutting-port-and-event-contracts.md). | | **`CursorPagination` / `Page` / `PageInfo`** | The cursor-first pagination triple in `LearnStack.SharedKernel.Pagination` matching Standards 04 § Pagination. `CursorPagination(Cursor, Limit)` is the request (default `Limit = 20`, max 100; ctor throws on `Limit <= 0` — kernel-level guard); `Page(Items, PageInfo)` is the response; `PageInfo(NextCursor, PreviousCursor, HasNext, HasPrevious)` carries the opaque cursors the client never parses. | @@ -409,9 +418,9 @@ and recurrence definitions remain empty. | **`IPartitionSerializer`** | Runs work sequentially within one partition key and concurrently across different ones in the current process. This invocation serialization establishes no durable publish-order guarantee; [ADR-0046](decisions/0046-durable-event-delivery-and-recovery.md#producer-dispatch-and-recovery) defines eligible-selection order and its limits. Queuing work for the key you are already inside is refused rather than deadlocked: the caller that does it is publishing from inside a handler, which [Standards 20](standards/20-infrastructure-stack.md) forbids. | | **`EventTenantContext`** | The `ITenantContext` a consumer runs under, rebuilt from the validated envelope by the delivery executor before business-handler construction or DI resolution. A consumer executes outside the request that produced the fact, so there is no ambient context to inherit. The effective principal is `UserId.SystemActor`; an envelope human remains available separately as `CausalActorUserId`. Restoring the tenant and optional organization is what makes query filters and RLS policies evaluate against the right scope. | | **`TenantId`** | The strongly-typed tenant identifier, in `LearnStack.SharedKernel.Identifiers` per [ADR-0023 Amendment 2](decisions/0023-strongly-typed-id-source-generator.md)'s cross-cutting placement rule — it rides on `ITenantContext`, on every `[TenantOwned]` entity, in cache keys, job payloads and event envelopes, so a Tenancy-owned type would make each of those a reference to that module. It has **no `New()`**: a tenant id is assigned by the registry that owns the `Tenant` aggregate, because a handler minting its own could not satisfy the self-keyed policy's `WITH CHECK` ([Database Standards § Table classes](standards/05-database.md)). | -| **`TenantId.PlatformSentinel`** | The reserved platform sentinel tenant id `00000000-0000-7000-8000-000000000002` — a UUIDv7-shaped constant on the precedent `UserId.SystemActor` sets, and **not** the nil UUID, which three shipped mechanisms read as *the absence of a tenant*. `tenants` carries a `CHECK` refusing it, so no tenant is ever provisioned under it and its rows are invisible to every tenant policy. Exactly one class of row carries it: a platform-scope operation with no resolvable tenant, written standalone — entry into `EnterPlatformAdminScope(reason)` and the operations inside it, of which `tenancy.killswitch.toggle` is the first — a row the Tenancy matrix carries as `(planned)`, because Packet 9 ships the killswitch table with no writer and [Phase 03](roadmap/phase-03-identity-admin.md) owns the toggle command. Never announced by `SetTenantContextAsync`, never written by a tenant request path, and never carrying a rejected tenant assertion — and that invariant has an **enforcer** rather than a hope: `SetProvisioningTenantContextAsync`, the one announcement path that takes a caller-supplied id, refuses the sentinel exactly as it already refuses `Guid.Empty`, and `Tenant.Create` refuses it in the factory. The `CHECK` is the **backstop, not the control** — a constraint on `tenants` cannot stop a GUC from being announced. Per [ADR-0044 § 1 and Amendment 3](decisions/0044-audit-write-path.md). | +| **`TenantId.PlatformSentinel`** | Reserved storage-attribution tenant id `00000000-0000-7000-8000-000000000002`, UUIDv7-shaped and distinct from the nil absence value. Exactly two named audit classes may carry it: platform-scope standalone operations and ADR-0072 global `identity.user.create` attempts. Neither class grants tenant authority or permits a tenant setter to announce it. `tenants` CHECK and existing factory/announcement guards remain; rejected tenant assertions never use it. Global operation/source/target/evidence rules live in [Database Standards](standards/05-database.md#proposed-global-central-audit-branch); the platform path stays separately confined. | | **`OrganizationId`** | The strongly-typed identifier for a sub-unit within a tenant ([ADR-0017](decisions/0017-tenant-organization-hierarchy.md)), cross-cutting for the same reason as [`TenantId`]. Nullable at almost every use site, and the null is a **scope** rather than "unknown": a tenant-owned row with no organization is tenant-wide, which is why the canonical policy reads `organization_id IS NULL OR organization_id = …`. Modules hold it by value and read organization data through an application contract; the `Organization` aggregate lives only in `LearnStack.Modules.Tenancy.Domain`. | -| **`UserId.SystemActor`** | The fixed, non-empty `UserId` (`00000000-0000-7000-8000-000000000001`) that integration-event consumers, background jobs and other non-request executions use as their effective audit principal — what [Audit Coverage](standards/18-audit-coverage.md) means by an actor of type `system`. It needs **no** `users` row: `created_by` and `actor_user_id` carry no referential constraint anywhere, and [31-audit-subsystem](architecture/31-audit-subsystem.md) depends on that absence so an erased actor leaves an orphan surrogate key rather than an unresolvable delete ([ADR-0038 Amendment 1](decisions/0038-cross-cutting-port-and-event-contracts.md)). The `users` table is owned by [Phase 03](roadmap/phase-03-identity-admin.md). | +| **`UserId.SystemActor`** | Fixed nonempty actor id `00000000-0000-7000-8000-000000000001` used by system executions and separately witnessed seed adoption. It needs no `users` row and cannot be an ordinary provider binding: audit `created_by` / `actor_user_id` columns retain no User FK. Accepted [ADR-0072](decisions/0072-application-owned-identity-bootstrap.md) preserves that boundary; SystemActor alone grants no seed, Platform or closure authority. | | **`AuditEntryId`** | The **fourth** cross-cutting identifier — the fourth id that lives in `LearnStack.SharedKernel` rather than in the module owning its aggregate, after `TenantId`, `OrganizationId` and `UserId` — even though `AuditEntry` is the Audit module's aggregate. Three SharedKernel types name it — `AuditIntent`, `IAuditStateCapture` and `AuditEntryDraft` — so a module-local id would require SharedKernel to reference the module back, which is a project cycle rather than a style preference; it lives in `LearnStack.SharedKernel.Audit` beside those ports. A UUIDv7-backed `[ValueObject]` on `LearnStackVogenDefaults.IdMask` with **no `New()`**: the call site is `AuditEntryId.From(guidFactory.NewUuidV7())`. Per [ADR-0023 Amendment 9](decisions/0023-strongly-typed-id-source-generator.md) and [ADR-0044 § 11](decisions/0044-audit-write-path.md). | | **`ICacheService`** | Interface for cache reads / writes. `InMemoryCacheService` today; a Valkey-backed implementation when more than one instance runs concurrently. Tenant keys are `{tenant_id}:{module}:{logical-name}`, or `{tenant_id}:{organization_id}:{module}:{logical-name}` for organization scope, composed by `CacheKey` and enforced by `CacheKey.EnsureValid`. `EnsureValid` admits exactly two platform-wide families, and admits them by enumeration rather than by opening the guard: the normalized host map `platform:hub:host-map:{normalized-host}`, composed by `CacheKey.ForHostMapping`, and the killswitch overlay `platform:tenancy:killswitch` ([ADR-0045 § 5](decisions/0045-entitlement-and-feature-flag-socket.md)). There is no generic platform factory, and a third family is a decision. `RemoveByPrefixAsync` is absent per [ADR-0038](decisions/0038-cross-cutting-port-and-event-contracts.md). Set invalidation uses a caller-owned durable generation key embedded in the key template. | | **`ISecretProvider`** | Interface for secret reads. `ConfigurationSecretProvider` today; the Vault-backed implementation when a production secret must rotate without a redeploy, or more than one operator needs access to production secrets ([ADR-0035](decisions/0035-demand-gated-infrastructure.md) — *not* when a non-development deployment merely exists, which SaaS satisfies on day one). Secret namespace `learnstack/{deployment}/{module}/{key}`. | diff --git a/docs/modules/audit/README.md b/docs/modules/audit/README.md index f58e116a6..c2603e51e 100644 --- a/docs/modules/audit/README.md +++ b/docs/modules/audit/README.md @@ -3,7 +3,7 @@ **Status:** Design stable, write path implemented. Shipped today: the two tables and their isolation, the three append-only layers, the SharedKernel ports and value types, `AuditDbContext`, and — in `LearnStack.Infrastructure.Audit` — `AuditStateCapture`, -`AuditChangeTrackerInterceptor`, `PostgresAuditStore` with all five write methods, the +`AuditChangeTrackerInterceptor`, `PostgresAuditStore` with eight write methods, the merged `AuditCatalog` and `AuditConfigService`, registered at both composition roots and attached to every module's `DbContext`. The pipeline is lit: `AuditLogBehavior` classifies and parks intents at step 3 and reconciles in its `finally`, @@ -14,6 +14,10 @@ fail-closed rule ships with it — the `audit` health check, the two counters, a `Critical` line ([ADR-0033 Amendment 3](../../decisions/0033-audit-durability-model.md)). `AuditingTenantAssertionRecorder` ships with them, so both `tenancy.tenant_assertion.*` slugs are written rather than declared. +Accepted [ADR-0072](../../decisions/0072-application-owned-identity-bootstrap.md) +adds two confined global-identity seams, implemented in P03-1 Step 3 with the +common prepared owner, exact evidence and real app-role/COMMIT fault controls. +No HTTP creation or global audit-read endpoint is activated. The entitlement socket of [ADR-0045](../../decisions/0045-entitlement-and-feature-flag-socket.md) shipped in the same packet. Rows marked @@ -99,8 +103,7 @@ know before touching it. and an audit row is not a log line: it is a record a regulator reads and a tenant admin can be shown. -**One property is worth stating before anything else.** `audit_log` is the only table -in the schema whose rows cannot be corrected. `learnstack_app` holds no `UPDATE` and no +**Audit rows cannot be corrected.** `learnstack_app` holds no `UPDATE` and no `DELETE`; `learnstack_platform`'s `UPDATE` names six columns and no more; and the table owner — which no grant bounds — is stopped by `audit_log_append_only_guard`. So a wrong `tenant_id`, a wrong `operation` or a wrong diff --git a/docs/modules/audit/audit.md b/docs/modules/audit/audit.md index 0b476b252..334fac033 100644 --- a/docs/modules/audit/audit.md +++ b/docs/modules/audit/audit.md @@ -108,3 +108,16 @@ class is defined here. The two `(off-path)` rows are the ones a retention policy never expire ahead of the rows they describe: a purge record that outlives nothing is a record of a deletion whose subject is gone, which is the only durable evidence that the deletion happened. + +## Mapped-property personal-data declarations + +P03-1 Step 2 explicitly declares the current append-only record and override +model's scalar paths in [the EF mappings](../../../backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure/Persistence/Configurations.cs). +Actor/email/IP fields are Identity; record/scope/resource/time, reason, client, +correlation and captured JSON/metadata use Audit purposes. Closed operation/ +outcome descriptors and override configuration are explicit nonpersonal metadata; +inherited override actor references/stamps follow the +[common declarations](../../architecture/23-data-protection.md#identity-foundation-and-classification-ownership). +Classification describes retained personal references; it does not claim they +are anonymous, redact SQL-written metadata or change the existing six-column +redaction authority. Snapshot capture and storage retention remain independent. diff --git a/docs/modules/audit/permissions.md b/docs/modules/audit/permissions.md index b142dd9d1..45b864572 100644 --- a/docs/modules/audit/permissions.md +++ b/docs/modules/audit/permissions.md @@ -5,11 +5,11 @@ Part of the [module spec](README.md). **No permission keys are enforced yet.** The matrix below is a forward declaration in the `{module}.{resource}.{action}` form with the closed action set of -[Permission Standards](../../standards/19-permissions.md). Registration runs through -`IModule.RegisterPermissions(IPermissionRegistry)`, and neither type exists in -`backend/src` yet; the registry lands with the Identity module in -[Phase 03](../../roadmap/phase-03-identity-admin.md), together with the query API these -keys gate. +[Permission Standards](../../standards/19-permissions.md). These Audit keys await +the separately admitted P03-2 registry/live-enforcement contract and the protected +query API in [Phase 03](../../roadmap/phase-03-identity-admin.md). The implemented +Identity foundation registry does not activate these forward declarations or +introduce an `IModule` interface. | Resource | read | write | delete | admin | Default role grants | |----------|:----:|:-----:|:------:|:-----:|---------------------| diff --git a/docs/modules/customization/README.md b/docs/modules/customization/README.md index e07685833..aa8568934 100644 --- a/docs/modules/customization/README.md +++ b/docs/modules/customization/README.md @@ -35,6 +35,14 @@ plan. cache key this module's reads compose. Not an aggregate ([ADR-0043 § 7](../../decisions/0043-customization-payload-validation.md)). +**Phase 03 addition, not yet implemented:** `TenantCustomFieldDef` belongs to +Customization; Identity owns the membership values and consumes the definition +contract. [G9](../../roadmap/phase-03-identity-admin.md#the-decision-register) +settles immutable revisions, value pins, classification history and schema +admission before that aggregate's first migration. Its permission/audit matrices +and module-spec diagrams extend with the implementation, not with a second +Identity-owned definition table. + **It does not own:** - **The content.** A `TenantContentType` says what an article looks like; the diff --git a/docs/modules/customization/audit.md b/docs/modules/customization/audit.md index e217b7657..ef874cf8b 100644 --- a/docs/modules/customization/audit.md +++ b/docs/modules/customization/audit.md @@ -160,3 +160,15 @@ remains classified. The transport skips construction for a durable inbox duplica so that duplicate adds no business audit. Completed Seeder acts skip the command before invocation. The [Step 5 record](../../roadmap/phase-02b-delivery-log.md#p02b-3-step-5--useful-defaults-and-semantic-seed-handoff-2026-10-13) owns validation and review status. + +## Mapped-property personal-data declarations + +P03-1 Step 2's [EF declarations](../../../backend/src/Modules/Customization/LearnStack.Modules.Customization.Infrastructure/Persistence/Configurations.cs) +classify scoped definition IDs, revision/status/renderer/schema and presentation +metadata as explicit None with purpose. These describe reusable definitions, +not stored person-specific field values. Inherited actor references and stamps +use the [common declarations](../../architecture/23-data-protection.md#identity-foundation-and-classification-ownership). +The complete final-model census includes taxonomy children and rejects omitted +properties. Future dynamic personal values require G9's revision-aware semantic +classification, consent and diagnostics; a definition's None category does not +classify values subsequently authored against it. diff --git a/docs/modules/education/audit.md b/docs/modules/education/audit.md index fa2874bd2..4c375e693 100644 --- a/docs/modules/education/audit.md +++ b/docs/modules/education/audit.md @@ -47,3 +47,16 @@ exposes eligible marketing metadata; lesson publication enables content only und the parent/access rules. Restriction does not lower the selected MUST classification. `GetCourseSeedStateQuery` and `GetLessonSeedStateQuery` are explicitly Off in `EducationAuditCatalogSource`; they declare no synthetic write operation. + +## Mapped-property personal-data declarations + +P03-1 Step 2 declares current curriculum IDs/scope, publication/access policy, +locales and authored content as explicit None with purpose in +[the EF mappings](../../../backend/src/Modules/Education/LearnStack.Modules.Education.Infrastructure/Persistence/Configurations.cs). +These models hold curriculum definitions, not an individual's attempts or +progress. Inherited author/change references and stamps follow the +[common declarations](../../architecture/23-data-protection.md#identity-foundation-and-classification-ownership). +The complete census covers both roots and translation children; a new personal +reference or learner-state model needs its own reviewed declaration. None is no +permission to log arbitrary authored text or substitute for later learner-data +classification and disclosure rules. diff --git a/docs/modules/identity/README.md b/docs/modules/identity/README.md new file mode 100644 index 000000000..d81385a55 --- /dev/null +++ b/docs/modules/identity/README.md @@ -0,0 +1,380 @@ +# Identity — Module Specification + +**Global/contextual storage, common audit, seed handoff and existing-binding API +admission are implemented.** Derived from +jointly Accepted [ADR-0072](../../decisions/0072-application-owned-identity-bootstrap.md) +and [ADR-0073](../../decisions/0073-scoped-membership-and-identity-data-foundation.md), +2026-10-25. The global User/authority model, internal binding/adoption consumers +and central creation owner exist. Contextual tables/commands/manifests below +are implemented; the [Phase 03 Status block](../../roadmap/phase-03-identity-admin.md) +owns current qualification and review state. New +HTTP/native-user activation remains P03-3. +The ordered admission timing/observation contract additionally derives from +[ADR-0074](../../decisions/0074-membership-admission-under-ordered-locks.md), +Accepted 2026-10-26. The phase Status block owns qualification and review state. + +## Overview + +Identity owns global application bindings, contextual Membership/Profile/ +assignments and tenant-wide Role templates. Keycloak owns credentials/provider +authentication; Tenancy owns Tenant/Organization lifecycle; Audit owns audit rows. +Cross-module facts use application contracts, without an Organization FK, +navigation or database join. Branch-specific Role configuration is not selected. + +### Global implementation and deployment + +P03-1 Step 3 implements one global User/authority model and migration chain, +the common prepared creation owner and eight central audit seams. API composition +denies seed adoption; the ordinary seed/demo handoff is implemented in Step 4. +Existing-binding API admission uses the same read-only contract. No creation +route is exposed here. + +Set both `Identity__AuthorityId` and `Authentication__Tenant__Issuer` in the +selected private deployment environment before `make migrate` installs/verifies +the authority. Supply the migration connection and complete pair together, either +as all three process variables or in the selected private environment file. +The migration owner refuses partial input and never combines the two sources; +a complete process selection takes precedence over file defaults. Schema-only +process input also refuses a file that supplies an authority pair. The ID is +deployment-pinned and never derived from an issuer URL. +The dedicated deployment child receives the migration credential only in its +environment; restore/build and API processes receive no migration credential. +An exact existing registration is a no-write verification. A conflicting pair +refuses without repair/rebind. With both keys absent, migrations create the +schema only; missing authority cannot admit a binding. A partially configured +pair refuses before migration writes. See [the environment example](../../../.env.example) +and the [canonical authority contract](../../standards/05-database.md#global-class-and-authority-anchor). + +Schema-only migration does not satisfy API startup. Every API host, including one +serving only anonymous reads, requires both runtime configuration keys and the +matching installed authority. Startup qualification rejects missing, unavailable +or mismatched registration before accepting HTTP requests. Direct `dotnet run` +reads process/.NET configuration, not the root `.env`. Restore the intended +configuration when it differs from the selected database; an issuer rebind remains +P03-9/G13 and is not an automatic repair. + +The internal binding service uses explicit startup qualification and fresh, +physically read-only existing-binding transactions; it never creates a missing +binding. Fixed seed adoption separately requires its confined admission port. +Real provider/app-role, schema/body/ACL/caller and physical outcome controls are +implemented. Closure, directory access, +production first-admin and issuer rebind remain their named later owners. + +### Aggregate and storage contract + +User's authority is [ADR-0072](../../decisions/0072-application-owned-identity-bootstrap.md); +the [canonical accepted database annex](../../standards/05-database.md#proposed-p03-1-identity-storage-annex) +owns its exact global SQL, grants and guards. + +| Table | Class / owner | Keys, scope and lifecycle | +|---|---|---| +| `memberships` | Tenant-owned, org-scoped; Membership root | UUIDv7 `MembershipId`; referenceable `(tenant_id,id)`; current unique `(tenant_id,user_id,organization_id) NULLS NOT DISTINCT WHERE deleted_at IS NULL` | +| `membership_profiles` | Tenant-owned, org-scoped; contained Membership child | PK `(tenant_id,membership_id)`; one profile created with Membership; exact parent organization mirror/lifecycle | +| `membership_role_assignments` | Tenant-owned, org-scoped; contained Membership child | PK `(tenant_id,membership_id,role_id)`; exact Membership organization mirror; Role capability compatibility guard | +| `roles` | Tenant-owned, tenant-wide; Role root | UUIDv7 `RoleId`; referenceable `(tenant_id,id)`; current unique `(tenant_id,permission_scope,built_in_key) WHERE deleted_at IS NULL`; no `organization_id` | +| `role_permission_grants` | Tenant-owned, tenant-wide; contained Role child | PK `(tenant_id,role_id,permission_scope,permission_key)`; exact Role capability-scope mirror; no `organization_id` | + +Use each [Standard 05 table class](../../standards/05-database.md#table-classes), +its EF filter and ENABLE/FORCE RLS. Org-scoped tables receive canonical +restrictive write guards and immutable organization triggers. Parent references +use `(tenant_id,parent_id)` with ON DELETE RESTRICT; index every FK. Independent +INSERT/UPDATE mirror triggers compare nullable organizations with +`IS DISTINCT FROM`. Never rely on a nullable organization column in a FK to +check tenant integrity under MATCH SIMPLE. + +Assignments reference Membership and Role through two tenant-composite FKs. +Membership's `user_id` references same-module `users.id` with ON DELETE RESTRICT +and its own supporting UserId index. The permanent User tombstone retains the +key; audit actor columns still have no User FK. The BEFORE admission guard maps +unknown and nonadmitting targets to the same refusal before FK diagnostics can +be exposed, and its fixed diagnostic translation discloses no constraint values. +Their trigger checks the exact Membership organization mirror, then requires +Tenant capability iff that organization is NULL and Organization capability iff +it is non-NULL. Role has no organization to match. Grant children reference Role +through its tenant-composite FK and mirror capability scope. Tenant, User/parent +references, Role built-in key and capability scope are immutable. +Role built-in/scope CHECKs admit only the finite manifest pairs; no free-form Role +key or Platform variant enters these tables. Soft-deleted Roles/Revoked or +Suspended Memberships do not contribute live grants. Tenant natural-key indexes +remain partial while referenceable primary-key-containing indexes remain full. + +`learnstack_app` receives SELECT/INSERT/UPDATE on Membership/Role/Profile and +SELECT/INSERT/DELETE on assignment/grant children, subject to all guards. Root +revocation is soft; no app root/Profile DELETE exists. Child changes go through +the owning root and tracked audit capture. No PUBLIC/Platform/dispatcher Identity +privileges or new login are introduced. Global grants/functions follow ADR-0072. +Each migration declares exact grants: a privilege never identifies a code path. + +Permission definitions remain compiled code, without a new global Permission +table. Persisted grants select `(scope,key)` from the registry; unknown/inactive +entries never authorize. [Standard 19's accepted foundation contract](../../standards/19-permissions.md#proposed-identity-foundation-contract) +owns the exact registry, version-1 grants and generated kernel artifact. + +### Lifecycle, profile and admission + +The database requires Active/Suspended Memberships to have NULL deletion fields +and Revoked to carry both deletion timestamp/actor. Its INSERT/UPDATE lifecycle +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. + +Profile carries optional contextual `DisplayName` (128 characters) and +`PreferredLocale` (35-character well-formed locale tag), both marked sensitive. +No unused contact field is collected. Missing values use explicit safe UI fallback, without copying +global fields on reads. NULL-org profiles contain no branch-private notes; +organization profiles are independent. Self/admin changes allow those fields +only, never canonical email/verification, global identity, Role bindings, +arbitrary settings or consent evidence. P03-3/G6 chooses exact DTOs; P03-5/G9 owns +dynamic fields/revisions. No dormant custom-fields column lands in the foundation. + +Creation, Suspended→Active and **all** assignment additions recheck the target +User fence, including additions of currently empty/inactive templates. +[Standard 05's accepted lock contract](../../standards/05-database.md#proposed-lock-snapshot-and-adoption-conditions) +alone owns the algorithm, ordering, fresh reads, deadlines and database guards. +Profile/nonadmin/organization mutations use its shared tenant invariant mode; +first-admin and tenant-admin eligibility/assignment/kernel transitions use its +exclusive mode. Actual affected rows bind the mode before acquisition; no +shared-to-exclusive upgrade or caller-declared nonadmin exemption is admitted. +Only the admission operations above automatically require the User fence; +profile-only changes and assignment removals retain their existing tenant-lock +requirements. Standard 05 also owns backend-heldness limits, fixed internal plan +fault versus target refusal, and the identical outward refusal. No algorithm or +new User reader is defined here. + +Every Membership mutation, in either lock mode, leaves an Active, globally +eligible, tenant-wide Tenant Admin with both kernel pairs. The first mutation +therefore establishes that administrator. Role roots may exist first; completed +foundation is actual eligible administration plus semantically valid required +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. + +P03-1 supplies the bounded Tenancy Application.Contracts port +`IIdentityScopeLifecycleReader.ReadAsync(TenantId, OrganizationId?, CancellationToken)`. +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. +Trial/Active admit ordinary work; Suspended retains an +admin without ordinary-work eligibility. Organization work requires Active and +nondeleted, not just belonging. Missing targets return closed false facts. + +The target must match an already trusted, announced owner scope. The Tenancy +implementation reads its own tables in one fresh READ COMMITTED statement on +that app-role transaction; no cached lifecycle result, additional setter, +cross-module SQL join or Organization FK is admitted. P03-1 Step 4 supplies the +port/implementation and seed controls; P03-2 executes it for live admission at +the declared per-act snapshot. P03-3 owns lifecycle-transition/last/default-org +concurrency before Tenancy endpoints. G3's foundation contract does not qualify +those later live checks or archive races. + +### First-admin and seed sequence + +P03-1 admits only the fixed development-seed capability. +`ISeedIdentityFoundationAdmission` is `DenyAllSeedIdentityFoundationAdmission` +in API composition. The external seed/demo owner supplies bounded canonical +manifest facts and actual provider-adoption witnesses to the confined Seeder +implementation. Email, a realm role or SystemActor alone supplies no admission. +There is no HTTP entry, operator population or general bootstrap bypass. + +Production first-admin/provisioning admission is **P03-9/G13**, before a +production provisioner uses it. Its authority/recovery cannot inherit the seed +capability. Tenancy's current ProvisionTenant remains the ADR-0042 Tenant/default +Organization pair; no cross-module transaction or further exception is admitted. + +1. The external seed owner completes Tenancy acts and ADR-0072 trusted binding + adoption, preserving all four actor/provider IDs, credentials and MFA. +2. `InitializeSeedRole` writes one Role and grants per transaction from version 1. + Eight templates per tenant include three Organization-capability variants; + there are no per-organization Role rows or organization-initialization step. +3. `CreateFirstSeedAdminMembership` atomically writes the declared admin, + contained Profile/Assignment and central MUST audit, referencing an existing + Tenant Admin template. Its complete root/child plan precedes mutation; + User/tenant/last-admin guards apply. +4. `CreateSeedMembership` writes each learner and contained state separately. + `SetSeedMembershipProfile` changes bounded fields through Membership. No + command writes another root merely because its transaction is available. +5. Each act uses a deterministic version-1 expected manifest fingerprint and + exact postcondition. Matching completed acts skip before dispatch. Interrupted + reruns verify committed acts and create only missing uncompleted declarations. + Revocation, suspension, ID conflict or edited grants refuse with a fixed + diagnostic, stop remaining acts and leave prior committed facts intact. + They never reset, repair or silently create successors. + +The expected fingerprint is not a new receipt table. Existing Role/Membership +facts establish completion; keep historical manifest versions to verify earlier +completed acts. Registry additions do not change adopted grants. P03-2 owns +separately admitted/audited grant adoption, including removal of the initial +profile grant outside the two-pair kernel. A legitimate later upgrade that no +longer matches this fixed v1 seed also makes that seed refuse; it never overwrites, +repairs or resets upgraded authority. Seed is not an upgrade reconciler. + +| Existing actor | Membership scope | Assignment | +|---|---|---| +| English admin (`a001` suffix) | English / NULL organization | Tenant Admin, Tenant capability | +| English learner (`a002`) | English / NULL organization | Learner, Tenant capability | +| Yoga admin (`b001`) | Yoga / NULL organization | Tenant Admin, Tenant capability | +| Yoga learner (`b002`) | Yoga / default studio | Learner, Organization capability | + +[SeedData](../../../backend/src/LearnStack.Tools.Seeder/SeedData.cs) owns the full +legacy actor/tenant/organization IDs. Exact assignment declarations extend that +manifest; suffixes above identify existing actors, not newly allocated IDs. +The four authentication personas remain fixed. Additional cross-tenant/two-branch +and same-tenant-second-person proof populations are fixture-local, outside +`IdentityUsers` and its exact four-user realm manifest. Email never merges them. + +Yoga admin `b001` keeps its existing provider claim for default studio `b1`. +Its seed Membership declaration independently selects NULL organization, and +the seed transaction derives NULL SQL organization scope from that trusted +target; the authentication manifest does not choose the Membership write scope. +After live authorization ships, a branch session may consume eligible Tenant +grants for branch operations only. Tenant-wide Membership/Profile/template +writes require an explicitly selected orgless context through P03-3's validated +reissue transition. Neither the existing branch claim nor `app.scope` promotes +writes; no extra branch-admin Membership or provider-claim rewrite is required. + +## Entity-relationship diagram + +```mermaid +erDiagram + User ||--o{ Membership : "stable identity reference" + Membership ||--|| MembershipProfile : contains + Membership ||--o{ MembershipRoleAssignment : contains + Role ||--o{ MembershipRoleAssignment : "tenant-composite reference" + Role ||--o{ RolePermissionGrant : contains + Membership { + uuid tenant_id + uuid organization_id "nullable; immutable" + uuid user_id + text status + } + Role { + uuid tenant_id + text permission_scope "capability; no organization column" + text built_in_key + } +``` + +Text fallback: User has contextual Memberships; each contains Profile and +assignments to tenant-wide Roles. Roles contain grants. OrganizationId is a +Membership value, without a cross-module FK/navigation. + +## State diagrams + +```mermaid +stateDiagram-v2 + [*] --> Active: admitted creation + Active --> Suspended + Suspended --> Active: User admission rechecked + Active --> Revoked: deletion markers + Suspended --> Revoked: deletion markers + Revoked --> [*] +``` + +Text fallback: Active and Suspended exchange; either revokes. Revoked is terminal, +with a distinct successor on rejoin. Global Active/Closing/Closed admission and +permanent binding follow ADR-0072, not a Membership state transition. + +## Sequence diagrams + +```mermaid +sequenceDiagram + participant Seed as External seed owner + participant Role as InitializeSeedRole + participant Member as CreateFirstSeedAdminMembership + participant DB as App-role PostgreSQL + participant Audit as Central audit path + Seed->>Role: Exact v1 template and closed seed witness + Role->>DB: One Role plus grants; commit + Seed->>Member: Declared admin and existing Role + Member->>DB: Standard 05 admission/invariant guards + Member->>DB: Membership, Profile and Assignment + Member->>Audit: MUST intent with captured children + Audit->>DB: Same-transaction audit + DB->>DB: Deferred invariant guards + DB-->>Seed: Commit and fresh semantic verification +``` + +Text fallback: Roles commit separately; first admin/children commit with audit. +Failure leaves no partial Membership; earlier Role acts are verified on resume. +There is no published primary integration-event flow in this foundation; see +the empty [catalogue](#integration-event-catalogue). + +## Component diagram + +```mermaid +flowchart LR + Seed[External seed/demo owner] --> Contracts[Identity Application.Contracts] + API[API: seed admission denied] --> Contracts + Contracts --> Application[Identity Application] + Application --> Domain[Identity Domain] + Application --> Tenancy[Tenancy lifecycle contract] + Application --> Shared[SharedKernel transaction/audit ports] + Infrastructure[Identity Infrastructure] --> Application + Infrastructure --> PostgreSQL[PostgreSQL: learnstack_app] + Shared --> Audit[Central Audit implementation] +``` + +Text fallback: Application uses domain, Tenancy application contracts and shared +ports. Infrastructure persists through the app role. API seed admission is denied; +global/provider adoption remains ADR-0072's confined owner. + +## Integration-event catalogue + +P03-1 publishes no Identity integration event and activates no provider ingress, +Invitation or closure consumer. P03-4/6/10 decide their first writers separately; +framework domain-event dispatch does not imply a published contract. + +## Permission matrix + +[Identity permissions](permissions.md) binds production seed commands to +the exact [accepted Standard 19 manifest](../../standards/19-permissions.md#proposed-identity-foundation-contract). +They are implemented in Step 4. Capability metadata activates +neither live permission behavior nor HTTP routes. + +## Audit coverage matrix + +[Identity audit](audit.md) declares implemented root/child classifications and +personal/reference paths. The central writer owns durability; Identity has no +audit table/direct audit SQL. Global mutation audit follows ADR-0072 alone. + +## Performance budget + +The canonical [initial performance budgets](../../standards/15-performance.md#initial-budgets) +apply: API p95 below 200 ms reads / 500 ms writes, excluding separately reported +provider calls. The [Step 4 record](../../roadmap/phase-03-delivery-log.md#p03-1-step-4--contextual-foundation-and-owned-seed-2026-10-26) +owns the small local command-path measurement and its limits; it establishes +no production capacity. The distinct +[Step 5 binding-load observation](../../roadmap/phase-03-delivery-log.md#p03-1-step-5--existing-binding-api-admission-2026-10-26) +retains its own control and scope. +Standard 05 owns bounded lock waits, +cancellation and metrics. Timeout yields a fixed retryable failure without +partial grants. P03-2 measures candidate-reader/authorization costs before +activation; a global permission cache/session grant cannot replace a fresh check. + +## Risks and open questions + +Branch-specific Role configuration reopens ADR-0073. P03-2 owns live delegation, +default deny/revocation and reader handoff; P03-3 scope transitions/DTOs; P03-4 +invitations; P03-5 dynamic values; P03-9 production first-admin/recovery; P03-10 +closure/locators. These are named later writers, not implicit foundation authority. + +| Subject/control | Current state | Owner / scope | +|---|---|---| +| Models, commands and registry | Global and contextual foundation implemented | P03-1 Steps 3/4; live authorization P03-2 | +| Canonical marker/filter/RLS/FK/unique/aggregate/audit controls | Identity extensions implemented with populated positive/dirty controls | P03-1 Step 4; [catalogue](../../standards/21-architecture-tests-catalogue.md#pending-identity-extensions-to-implemented-rules) owns the individual obligations | +| `Permission_Definitions_DeclareScope` | Implemented for the finite foundation | `IdentityFoundationConventionTests` and actual command metadata; broader enforcement P03-2 | +| `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`; combined final provider/browser qualification Step 6 | +| `Identity_Membership_Invariants_Use_Fresh_Ordered_Locks` | Implemented actual app-role races and closed helper/caller controls | `IdentityMembershipTests`, `IdentityMutationLockTests`, `IdentityFoundationConventionTests`; live transition/archive ownership remains P03-3/10 | +| 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 proofs; Step 3 completed both review rounds | `GlobalIdentitySchemaTests`, `IdentityAuditConventionTests` / `GlobalIdentityBootstrapTests`; P03-3 owns HTTP/new-user BFF activation | + +Registered means an actual catalogue entry exists. Until then a new control is +planned/unregistered; later Registered is not Implemented. No empty census, +skipped suite, type declaration or diagram supplies implementation evidence. diff --git a/docs/modules/identity/audit.md b/docs/modules/identity/audit.md new file mode 100644 index 000000000..3a313c987 --- /dev/null +++ b/docs/modules/identity/audit.md @@ -0,0 +1,76 @@ +# Identity — Audit Coverage Matrix + +**Status: Global and contextual seed writers implemented.** Current qualification +and review state lives in the [phase Status block](../../roadmap/phase-03-identity-admin.md). +The User off-path catalogue, contextual requests and persistence exist. +Derived from jointly Accepted [ADR-0072](../../decisions/0072-application-owned-identity-bootstrap.md), +[ADR-0073](../../decisions/0073-scoped-membership-and-identity-data-foundation.md) +and [Standard 18](../../standards/18-audit-coverage.md). Part of the [module spec](README.md). + +The baseline MUST floor applies. `IdentityAuditCatalogSource` declares +actual operations: catalogue-to-matrix coverage is total. Audit slugs are not +additional permission keys. + +| Resource | Operation | Class | Why | +|---|---|---|---| +| User/global immutable subject | `identity.user.create` `(off-path)` | **MUST** (`security-event`) | ADR-0072's confined creation/adoption owner and central non-success reconciliation; success shares the User transaction. Exact global witness, source and retention contract stays there. | +| Role including grants | `identity.role.initialize` | **MUST** (`security-event`) | `InitializeSeedRole`; one Role transaction, with contained grants. | +| Membership including Profile/Assignments | `identity.membership.create_first_seed_admin` | **MUST** (`security-event`) | `CreateFirstSeedAdminMembership`; one Membership transaction. | +| Membership including Profile/Assignments | `identity.membership.create_seed` | **MUST** (`security-event`) | `CreateSeedMembership`; one Membership transaction. | +| MembershipProfile, captured under Membership | `identity.membership_profile.set_seed_profile` | **MUST** (`update`) | `SetSeedMembershipProfile`; same Membership transaction. The slug matches the gated sub-resource while the row's subject remains its owning aggregate. | + +**Explicit Off reads.** Contextual seed verification request types are registered +Off before use; they inspect only the exact bounded declared seed facts, with no +directory/provider profile. Ordinary existing-binding lookups create no mutation +intent under ADR-0072. Off request registration is separate from MUST operation +rows; no Off value is presented as an `OperationClass` or a MUST audit slug. + +No seed command mutates a second root. Role grants travel in Role diffs; +assignments/Profile travel in Membership diffs. Instance-qualified paths +include `/Membership/{id}/Profile`, `/Membership/{id}/RoleAssignments/{roleId}` +and `/Role/{id}/Grants/{scope}:{key}`. Collection snapshots appear only when +actually complete; partial loads cannot claim a complete collection. Stable +resource/subject keys are references, not safe diagnostic labels. Global paths +and non-success reconciliation follow ADR-0072's canonical owner. + +## Personal-data declarations + +Step 2's actual mapped-property census declares a typed category or explicit +None/purpose for **every** mapped property, including inherited actor references +and owned children. This table assigns semantic review; it is not a completed +census or a reflection/name heuristic. + +| Subject | Personal/reference paths to classify | Snapshot/diagnostic rule | +|---|---|---| +| User | AuthorityId, raw `provider_subject`, subject key, actor and immutable audit linkage; no email/verification mirror | Raw subject explicitly `[PiiSensitive]`; keys/actor are classified retained linkage, not diagnostic labels; canonical grants/encoding in Standard 05 | +| Membership | `UserId`, lifecycle/audit actor references and person-to-tenant/org relationship | Explicit reference classifications; no diagnostic value capture | +| MembershipProfile | Display name and locale preference | Both personal scalars marked for snapshot redaction; fixed diagnostics | +| Assignment | Membership/person linkage and assignment history | Exact paths under Membership row; never log raw DTOs | +| Role/Grant | Built-in key, capability scope, scoped keys, tenant and inherited actor references | None only for reviewed nonpersonal metadata; actor/linkage paths stay classified | + +No credentials/token/browser binding, global active scope or dormant custom-field +blob belongs in these models. Publication does not make arbitrary tenant text +diagnostically safe. SQL-only/control/vendor inventory remains in canonical +[Data Protection](../../architecture/23-data-protection.md), not another durable-store list. + +Translate expected conflicts/upstream failures to fixed bounded descriptors +before L1/error-tracking sinks; retain no value-bearing original inner exception. +Unexpected paths retain a fixed operational signal. Snapshot markers, name-based +logging guards and LS0002 remain distinct; no global exception scrubbing is claimed. + +## Qualification and later owners + +P03-1 Steps 2/4 prove actual root/child capture, MUST rollback, inherited +references and sensitive/neutral-key nested canaries at each real sink: +validation/response, logs, local archive, Sentry envelope and audit snapshot. +Every sink receives a positive event. Preserve existing TenantSetting whole-value +redaction. Steps 3/4 also extend the existing audit-interface/matrix controls +for the central global seams, exact classifications and planted wrong-column, +missing-global-row and child-capture controls; canonical signatures/SQL stay in +[Standard 05](../../standards/05-database.md#proposed-global-central-audit-branch). +No runtime test is claimed here. + +P03-2 adds normal authorization/denied/read enrichment; P03-5 extends revision-aware +dynamic values; P03-10 delivers applicable user-reference locators and export/ +erasure/closure under separate authority. A stub or retained hash is not completion +or anonymisation. The module table records current versus planned proof status. diff --git a/docs/modules/identity/permissions.md b/docs/modules/identity/permissions.md new file mode 100644 index 000000000..2fdd4df56 --- /dev/null +++ b/docs/modules/identity/permissions.md @@ -0,0 +1,73 @@ +# Identity — Permission Matrix + +**Status: Finite foundation definitions and seed commands implemented; live enforcement remains P03-2.** Derived from jointly Accepted [ADR-0072](../../decisions/0072-application-owned-identity-bootstrap.md) +and [ADR-0073](../../decisions/0073-scoped-membership-and-identity-data-foundation.md). +No Identity HTTP route or live permission admission is implemented. The [module spec](README.md) +owns storage/lifecycle; [Standard 19's accepted foundation contract](../../standards/19-permissions.md#proposed-identity-foundation-contract) +owns the exact registry, grant manifests and kernel without a second copy here. + +## Foundation operation bindings + +These **production** commands compile in P03-1 Step 4 and are called +only through the closed seed composition, not test placeholder types. Permission +metadata supplies actual registry subjects. P03-1 separately checks finite seed +authority before dispatch; normal API composition denies it. P03-2 owns live +permission admission. An attribute, realm role or SystemActor value grants no route. + +| Command | Capability metadata | Independent P03-1 admission | +|---|---|---| +| `CreateFirstSeedAdminMembership` | Tenant `identity.membership.admin` | Exact declared admin, existing v1 Tenant Admin template, trusted adopted actor; User/tenant guards | +| `CreateSeedMembership` | Tenant or Organization `identity.membership.admin` | Exact declared learner tuple/target scope; no arbitrary actor/tenant/org/Role | +| `SetSeedMembershipProfile` | Tenant or Organization `identity.membership_profile.write` | Declared Membership and bounded contextual fields, through the Membership root | +| `InitializeSeedRole` | Tenant `identity.role.admin` | Exact tenant/template/v1 manifest, including Organization-capability templates; one Role root | + +Scope selection derives from immutable target Membership/validated declaration, +never a claimed scope string. Finite metadata alternatives count the exact five +scoped pairs, not merely three different strings. Canonical actor/provider +adoption supplies identity facts; it does not independently grant seed authority. + +## Resource matrix + +| Resource | read | write | delete | admin | Foundation defaults | +|---|:---:|:---:|:---:|:---:|---| +| `Membership` | – | – | – | Tenant + Organization | Exact Standard 19 v1 manifest; includes contained assignments | +| `Role` | – | – | – | Tenant | Tenant Admin alone; authoring stays tenant-wide | +| `MembershipProfile` | – | Tenant + Organization | – | – | Exact v1 manifest, bounded contextual fields | + +Empty cells mean no foundation key exists. Bootstrap/seed verification reads +do not invent directory/read keys; their exact owner/audit classification is +separate. P03-2/3 registers broader production operations before activation. + +## Delegation and scope boundary + +- Tenant-capability templates require NULL-org Membership. Organization-capability + templates require non-NULL-org Membership, which supplies the exact branch. +- Eligible Tenant grants compose with that organization's grants. Another branch + or a no-org Tenant check cannot consume an Organization grant. Tenant association + for discovery is not administrative authority. +- Branch-scoped sessions use eligible Tenant grants only for branch operations. + Tenant-wide writes require the explicit orgless reissue transition owned by + P03-3; `app.scope` widens reads only. The [seed handoff](README.md#first-admin-and-seed-sequence) + preserves Yoga admin's branch claim while using its declared NULL-org target. +- Org Admin cannot edit templates. Editing requires an eligible Tenant Admin + binding and Tenant `identity.role.admin`; that capability is reserved to Tenant + Admin and cannot be delegated to another built-in/Organization binding. +- Later live writes cannot delegate beyond current authority, cross scope, edit + self into higher authority or remove the immutable kernel. P03-2/G5 qualifies + these controls before a protected administration path activates. +- The two-pair admin kernel is deliberately smaller than the three-pair initial + Tenant Admin bundle. P03-2 owns explicit audited grant adoption/removal outside + that kernel. A later adopted manifest does not make the fixed v1 seed an + upgrade writer; a mismatch, including a legitimate upgrade, refuses unchanged. +- A per-act committed snapshot defines revocation: later admissions see the change; + already admitted work is not retroactively cancelled. JWT/session/UI caching + cannot establish that boundary. P03-3 owns UI freshness/target transitions. + +## Proof ownership + +P03-1 Step 4 proves actual command metadata, the nonempty five-pair registry, +finite grants, assignment guards, disabled new-key additions, fixed drift refusal +and complete no-write rerun. Missing production subjects fail rather than leaving +an empty population. Organization Learner has own-studio positive and other-studio +denied controls. Live permission/default-deny/delegation proof stays P03-2; +no live result is claimed here. diff --git a/docs/modules/tenancy/audit.md b/docs/modules/tenancy/audit.md index 32dae7b23..8dadef6b5 100644 --- a/docs/modules/tenancy/audit.md +++ b/docs/modules/tenancy/audit.md @@ -251,3 +251,18 @@ keeps the two existing operation slugs and extends their captured evidence: fields, never metric labels; no audit slug or row is added. - Existing anonymous burst limits and failure behavior remain: a failed audit preserves the refusal while the audit store reports Critical, failure count and unhealthy state. + +## Mapped-property personal-data declarations + +P03-1 Step 2 declares every current Tenancy scalar in its +[EF mappings](../../../backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure/Persistence/Configurations.cs). +Institution routing, entitlement and definition fields are explicit None with +purpose; inherited person references and stamps use the +[common declaration contract](../../architecture/23-data-protection.md#identity-foundation-and-classification-ownership). +Setting JSON, free-text verification errors/operator explanations and actor +references are classified Identity. This conservative declaration reads no row +values and grants no public projection, log exposure or new retention policy. +TenantSetting.Value retains its independent whole-value snapshot redaction. +The model finalizer and complete census reject undeclared/new neutral fields; +provider/domain-verification and privileged toggle writers retain their named +phase authority and fixed-diagnostic requirements before activation. diff --git a/docs/roadmap/README.md b/docs/roadmap/README.md index 0b9d4caed..cef001115 100644 --- a/docs/roadmap/README.md +++ b/docs/roadmap/README.md @@ -49,9 +49,11 @@ not deferred to the showcase phase. packet's merge closeout; the [individual exit evidence](phase-02d-exit-evidence.md) maps each exit criterion to its proof. - [Phase 02b: Events, Background Jobs, Identity, and Session](phase-02b-events-auth.md) - — **in progress**. Its Status block owns packet state and links current - decisions, delivery evidence and the remaining exit work. + — **complete and merged — 2026-10-25**. Its Status block owns packet state and + links the merge closeout and individual exit evidence. - [Phase 03: Identity Domain, Authorization, and Admin Foundation](phase-03-identity-admin.md) + — its Status block owns current packet state; its packet plan and decision + register define dependencies and first-writer boundaries. - [Phase 04: Headless CMS, Page Builder, and Media Library](phase-04-cms-media-pages.md) - [Phase 05: Education Catalog and Learning Content](phase-05-education-learning-content.md) - [Phase 06: Public Site Renderer and Admin Studio](phase-06-renderer-admin-studio.md) diff --git a/docs/roadmap/phase-02b-delivery-log.md b/docs/roadmap/phase-02b-delivery-log.md index 25abf4d43..5dd930d13 100644 --- a/docs/roadmap/phase-02b-delivery-log.md +++ b/docs/roadmap/phase-02b-delivery-log.md @@ -266,7 +266,7 @@ each packet decided and delivered, as - [P02b-7 observer correction review round 2 and source freeze (2026-10-24)](#p02b-7-observer-correction-review-round-2-and-source-freeze-2026-10-24) — 26 lines - [P02b-7 review correction qualification (2026-10-24)](#p02b-7-review-correction-qualification-2026-10-24) — 83 lines - [P02b-7 merge and closeout (2026-10-25)](#p02b-7-merge-and-closeout-2026-10-25) — 46 lines -- [P02b-8 — Exit enforcement](#p02b-8--exit-enforcement) — 1,288 lines +- [P02b-8 — Exit enforcement](#p02b-8--exit-enforcement) — 1,352 lines - [P02b-8 decision package (2026-10-25)](#p02b-8-decision-package-2026-10-25) — 246 lines - [P02b-8 proposal review round 1 (2026-10-25)](#p02b-8-proposal-review-round-1-2026-10-25) — 24 lines - [P02b-8 proposal review round 2 (2026-10-25)](#p02b-8-proposal-review-round-2-2026-10-25) — 32 lines @@ -296,6 +296,7 @@ each packet decided and delivered, as - [P02b-8 browser artifact ownership correction, review round 1 (2026-10-25)](#p02b-8-browser-artifact-ownership-correction-review-round-1-2026-10-25) — 44 lines - [P02b-8 browser ownership correction, review round 2 and freeze (2026-10-25)](#p02b-8-browser-ownership-correction-review-round-2-and-freeze-2026-10-25) — 19 lines - [P02b-8 PR correction qualification and closeout (2026-10-25)](#p02b-8-pr-correction-qualification-and-closeout-2026-10-25) — 105 lines + - [P02b-8 merge and phase closeout (2026-10-25)](#p02b-8-merge-and-phase-closeout-2026-10-25) — 64 lines - [Status archive](#status-archive) — 112 lines @@ -22265,6 +22266,70 @@ assignment, including PR-only meta gates. The PR's live checks own that result; this frozen A/B receipt does not imply it. Maintainer review and merge remain separate release gates, and Phase 02b remains in progress until merge closeout. +### P02b-8 merge and phase closeout (2026-10-25) + +Read-only GitHub verification confirms +[PR #37](https://github.com/HodeTech/LearnStack/pull/37) merged at +`2026-10-25T11:17:05Z` (14:17:05 in Europe/Istanbul), squash commit +`7cad8402a8490cc4914c270cab18118d57a70a97`. Its final source is +`b1f19f5b32fd9cb11fc8abc427817dbe72878068`. Fetching the merge confirms both +have tree `9eb11ced9d70f66dc84ad629f409801f1aeebbcf`; their file contents are +identical. The actual squash commit is distinct from CI's tested merge commit. + +The [preceding qualification](#p02b-8-pr-correction-qualification-and-closeout-2026-10-25) +owns the corrected implementation source's complete A/1 and B/2 evidence at +`7a2ef1d364a55b7438d17e44a02a5309d433d24d` in +[run 40182091476](https://github.com/HodeTech/LearnStack/actions/runs/40182091476). +The documentation-only final PR head additionally passes one complete +current-head assignment in +[run 40185549406](https://github.com/HodeTech/LearnStack/actions/runs/40185549406), +attempt 1/C. It tests merge `457de7ee3d0957127dfedc50a6b807e74b1c2de2` against +main `0dfade02a08fce6bd937fe0554f94f47c571ca8e`, with the same tree as the +final head and actual squash merge. + +Final-head retained-evidence verification confirms 27 successful jobs and all +seven required contexts; the same manifest, plan, toolchain and 6,122 unique +.NET assembly/case IDs as A/B; 2,376 frontend passes; zero skips/todos; all 20 +natural producer completions and cleanups; 25 authenticated archive digests and +957 extracted member files; nine public pages and 27 Lighthouse JSON/HTML pairs. +The maximum producer whole-job wall is 915 seconds. The final independent +readiness audit finds no pending technical gate within that scope. This closeout +rechecks successful run metadata, the seven exact required-check results and +merge-tree equality; it does not rerun application tests or claim new post-merge +execution. Earlier failures, source attribution and artifact-retention limits +remain in their original records. + +The dated live protection readback still requires all seven exact contexts in +[Contributing](../../.github/CONTRIBUTING.md#branch-protection-settings-on-main) +from GitHub Actions app `15368`, strict up-to-date checks and conversation +resolution. The final readiness readback confirms all three review threads +resolved. The maintainer's merge completes the remaining review/release gate; +no protection setting is changed. + +All four P02b-8 implementation steps, their two independent review rounds and +subsequent verified correction bundles are closed. The approved G16 `LS0002` +Warning contract, G18 asynchronous-copy inventory, reconciled carriers and +individual exit evidence are delivered. The +[exit index](phase-02b-exit-evidence.md) maps all 26 Deliverables, 60 Completion +Criteria and 11 Phase Exit Decision obligations to their owners and proofs. +P02b-0 through P02b-8 and the Phase 02b exit are complete; the phase document's +Status block owns that state. + +[Phase 03](phase-03-identity-admin.md) is next on the critical path. Its first +work is document review and the identity/membership and authorization decision +pass before first writers. Its existing scope retains real membership and +permissions, deny-by-default dispatch, identity-event ingress, privileged +recovery/dashboard admission, DSAR authority and `LS0001`/`LS0002` Error promotion +at its exit. This closeout accepts no Phase 03 package and starts no runtime work. + +[Phase 06](phase-06-renderer-admin-studio.md) retains the full browser-driven +OIDC and Studio/Portal journeys; [Phase 11](phase-11-production-hardening.md) +retains production/distributed sessions, operational adapters, readiness and +retention/purge qualification. [Phase 02c](phase-02c-hub-foundation.md) stays +parallel and starts on its existing billing/plan-gating trigger. The inventory +is not an erasure mechanism, and phase completion makes no production-readiness +or legal-compliance claim. + ## Status archive The Status block the phase document carried until 2026-10-22, kept verbatim. Its diff --git a/docs/roadmap/phase-02b-events-auth.md b/docs/roadmap/phase-02b-events-auth.md index ac5c19690..b9e13775a 100644 --- a/docs/roadmap/phase-02b-events-auth.md +++ b/docs/roadmap/phase-02b-events-auth.md @@ -1,22 +1,21 @@ # Phase 02b: Events, Background Jobs, Identity, and Session -> **Status (2026-10-25).** Phase 02b is **in progress**. P02b-0 through P02b-7 are -> complete. P02b-1–5 are merged through PRs #29–#33; P02b-6 through PR #34 and +> **Status (2026-10-25).** Phase 02b is **complete and merged**. P02b-0 through +> P02b-8 are complete. P02b-1–5 are merged through PRs #29–#33; P02b-6 through PR #34 and > correction PR #35; P02b-7 through > [PR #36](https://github.com/HodeTech/LearnStack/pull/36). > [ADR-0070](../decisions/0070-owned-tenant-bff-sessions.md) and > [ADR-0071](../decisions/0071-uncertain-account-site-refusals.md) are Accepted and -> implemented. The P02b-7 merge closeout below links the source-bound A/B and -> final PR-head qualification. P02b-8's G16/G18 decisions are Accepted; all four -> implementation steps and both review rounds per step are complete. Its -> [correction qualification closeout](phase-02b-delivery-log.md#p02b-8-pr-correction-qualification-and-closeout-2026-10-25) -> records complete A/B proof on the corrected source. -> [PR #37](https://github.com/HodeTech/LearnStack/pull/37) has completed both -> correction review rounds; earlier qualification stays bound to its own source. -> Current-head checks, conversation resolution, maintainer review and merge -> remain release gates; this phase is not yet marked merged. +> implemented. P02b-8's G16/G18 decisions are Accepted; all four implementation +> steps, both review rounds per step and subsequent corrections are complete. +> [PR #37](https://github.com/HodeTech/LearnStack/pull/37) merged on 2026-10-25. +> Its [merge and phase closeout](phase-02b-delivery-log.md#p02b-8-merge-and-phase-closeout-2026-10-25) +> links corrected-source A/B and final PR-head qualification, verifies identical +> merged contents, and closes the review and merge gates. Earlier evidence stays +> bound to its recorded source. > The [individual exit index](phase-02b-exit-evidence.md) names each criterion's -> owner. +> owner. The [Phase 03 Status block](phase-03-identity-admin.md) owns current +> identity, membership and authorization packet state. > > This document is the plan. Every dated decision package, step record, review > round, correction and merge closeout lives in the [delivery log](phase-02b-delivery-log.md), split out @@ -35,7 +34,7 @@ > | P02b-5 | API authentication | ✅ complete and merged — PR #33, 2026-10-20; [merge closeout](phase-02b-delivery-log.md#p02b-5-merge-and-closeout-2026-10-20) | > | P02b-6 | Realm and seed | ✅ complete and merged — PR #34 and correction PR #35, 2026-10-23; [correction closeout](phase-02b-delivery-log.md#p02b-6-correction-merge-and-closeout-2026-10-23) | > | P02b-7 | BFF session | ✅ complete and merged — PR #36, 2026-10-25; [merge closeout](phase-02b-delivery-log.md#p02b-7-merge-and-closeout-2026-10-25) | -> | P02b-8 | Exit enforcement | Implemented, reviewed and source-qualified — [acceptance](phase-02b-delivery-log.md#p02b-8-acceptance-2026-10-25); [Step 1](phase-02b-delivery-log.md#p02b-8-step-1-review-round-2-and-closeout-2026-10-25), [Step 2](phase-02b-delivery-log.md#p02b-8-step-2-closeout-2026-10-25), [Step 3](phase-02b-delivery-log.md#p02b-8-step-3-review-round-2-and-closeout-2026-10-25), [Step 4](phase-02b-delivery-log.md#p02b-8-step-4--completed-source-qualification-and-review-closeout-2026-10-25) and [corrected-source A/B](phase-02b-delivery-log.md#p02b-8-pr-correction-qualification-and-closeout-2026-10-25) complete with both review rounds; current-head checks, maintainer review and merge govern release | +> | P02b-8 | Exit enforcement | ✅ complete and merged — PR #37, 2026-10-25; [merge and phase closeout](phase-02b-delivery-log.md#p02b-8-merge-and-phase-closeout-2026-10-25) | ## Goal @@ -141,7 +140,10 @@ Each item below is named somewhere as adjacent to this phase's work. Each has an `platform-admin` role check owes; [Phase 11](phase-11-production-hardening.md#security) carries the APISIX half. - **Job definitions.** This phase ships the runner, its tenant contract and its enqueue - guard, and registers no job of its own. The first tenant-scoped jobs arrive in + guard, and registers no job of its own. + [Phase 03 G8/G16](phase-03-identity-admin.md#the-decision-register) must define any + earlier invitation/DSAR jobs and their exact execution profiles before their + first writers; later consumers remain [Phase 04](phase-04-cms-media-pages.md) and [Phase 08a](phase-08a-assessment-notifications.md). The first **tenantless** ones are [ADR-0028](../decisions/0028-audit-log-partition-management.md)'s two audit jobs, diff --git a/docs/roadmap/phase-02b-exit-evidence.md b/docs/roadmap/phase-02b-exit-evidence.md index 6e7ed535a..77fc8a363 100644 --- a/docs/roadmap/phase-02b-exit-evidence.md +++ b/docs/roadmap/phase-02b-exit-evidence.md @@ -6,12 +6,13 @@ The abbreviated locators below do not replace, weaken or omit the canonical bull subordinate conditions. Each row refers to its entire canonical bullet. This is an ownership index. The -[P02b-8 correction closeout](phase-02b-delivery-log.md#p02b-8-pr-correction-qualification-and-closeout-2026-10-25) -records completed exact-source A/B, artifact/skip/cleanup evidence and the dated -live required-check read-back. The review PR's live checks own qualification of -its actual current head. The frozen-source receipt does not imply a passing -result for a later documentation-only commit; maintainer review and merge remain -separate gates. +[P02b-8 merge and phase closeout](phase-02b-delivery-log.md#p02b-8-merge-and-phase-closeout-2026-10-25) +links completed exact-source A/B and final PR-head artifact/skip/cleanup evidence, +the dated required-check read-back and the actual merge. The merge and qualified +final head have identical file contents. Each receipt remains bound to its source; +neither the frozen A/B receipt nor the final-head receipt qualifies this later +documentation-only closeout as a new test execution. Phase state lives in +[Phase 02b's Status block](phase-02b-events-auth.md). Evidence lanes: **B** = backend base/unit/architecture and non-Docker HTTP tests; **I** = real Docker/PostgreSQL/Keycloak/native-HTTPS integration; **F** = frontend diff --git a/docs/roadmap/phase-03-delivery-log.md b/docs/roadmap/phase-03-delivery-log.md new file mode 100644 index 000000000..bcff3f154 --- /dev/null +++ b/docs/roadmap/phase-03-delivery-log.md @@ -0,0 +1,2876 @@ +# Phase 03 — delivery log + +The dated record of +[Phase 03: Identity Domain, Authorization, and Admin Foundation](phase-03-identity-admin.md). +The phase document holds the plan and Status; this log holds dated records under +[ADR-0069](../decisions/0069-phase-documents-and-delivery-logs.md). + +Entries are append-only after their packet ships. An explicitly Accepted decision +package is normative and its gate links the exact answer. Preparation records are +not acceptance of implementation choices. Navigate by the generated index below. + + + +**Index** + +- [P03-0 — Entry preparation](#p03-0--entry-preparation) — 83 lines + - [Entry preparation (2026-10-25)](#entry-preparation-2026-10-25) — 81 lines +- [P03-1 — Identity authority and membership foundation](#p03-1--identity-authority-and-membership-foundation) — 2,709 lines + - [P03-1 proposed decision package (2026-10-25)](#p03-1-proposed-decision-package-2026-10-25) — 130 lines + - [P03-1 proposal review round 1 (2026-10-25)](#p03-1-proposal-review-round-1-2026-10-25) — 35 lines + - [P03-1 proposal review round 2 (2026-10-25)](#p03-1-proposal-review-round-2-2026-10-25) — 36 lines + - [P03-1 proposal readiness (2026-10-25)](#p03-1-proposal-readiness-2026-10-25) — 35 lines + - [P03-1 maintainer review disposition (2026-10-25)](#p03-1-maintainer-review-disposition-2026-10-25) — 34 lines + - [P03-1 revised decision package (2026-10-25)](#p03-1-revised-decision-package-2026-10-25) — 114 lines + - [P03-1 revised proposal review round 1 (2026-10-25)](#p03-1-revised-proposal-review-round-1-2026-10-25) — 16 lines + - [P03-1 revised proposal review round 2 and readiness (2026-10-25)](#p03-1-revised-proposal-review-round-2-and-readiness-2026-10-25) — 30 lines + - [P03-1 second maintainer review and revised package (2026-10-25)](#p03-1-second-maintainer-review-and-revised-package-2026-10-25) — 99 lines + - [P03-1 second revision review round 1 (2026-10-25)](#p03-1-second-revision-review-round-1-2026-10-25) — 23 lines + - [P03-1 second revision review round 2 and approval readiness (2026-10-25)](#p03-1-second-revision-review-round-2-and-approval-readiness-2026-10-25) — 28 lines + - [P03-1 joint acceptance and Step 1 (2026-10-25)](#p03-1-joint-acceptance-and-step-1-2026-10-25) — 41 lines + - [P03-1 Step 1 review round 1 (2026-10-25)](#p03-1-step-1-review-round-1-2026-10-25) — 21 lines + - [P03-1 Step 1 review round 2 and closeout (2026-10-25)](#p03-1-step-1-review-round-2-and-closeout-2026-10-25) — 16 lines + - [P03-1 Step 2 implementation and local qualification (2026-10-25)](#p03-1-step-2-implementation-and-local-qualification-2026-10-25) — 36 lines + - [P03-1 Step 2 review round 1 (2026-10-25)](#p03-1-step-2-review-round-1-2026-10-25) — 20 lines + - [P03-1 Step 2 review round 2 and closeout (2026-10-25)](#p03-1-step-2-review-round-2-and-closeout-2026-10-25) — 18 lines + - [P03-1 Step 3 global storage and common audit implementation (2026-10-26)](#p03-1-step-3-global-storage-and-common-audit-implementation-2026-10-26) — 66 lines + - [P03-1 Step 3 final local pre-review controls (2026-10-26)](#p03-1-step-3-final-local-pre-review-controls-2026-10-26) — 25 lines + - [P03-1 Step 3 retained-subject pre-commit correction (2026-10-26)](#p03-1-step-3-retained-subject-pre-commit-correction-2026-10-26) — 12 lines + - [P03-1 Step 3 existing-adoption scope correction (2026-10-26)](#p03-1-step-3-existing-adoption-scope-correction-2026-10-26) — 24 lines + - [P03-1 Step 3 review round 1 and corrections (2026-10-26)](#p03-1-step-3-review-round-1-and-corrections-2026-10-26) — 46 lines + - [P03-1 Step 4 ordered-lock timing proposal (2026-10-26)](#p03-1-step-4-ordered-lock-timing-proposal-2026-10-26) — 39 lines + - [ADR-0074 proposal review round 1 (2026-10-26)](#adr-0074-proposal-review-round-1-2026-10-26) — 12 lines + - [P03-1 Step 3 review round 2 and local closeout (2026-10-26)](#p03-1-step-3-review-round-2-and-local-closeout-2026-10-26) — 40 lines + - [ADR-0074 proposal review round 2 and readiness (2026-10-26)](#adr-0074-proposal-review-round-2-and-readiness-2026-10-26) — 16 lines + - [ADR-0074 maintainer review correction and acceptance (2026-10-26)](#adr-0074-maintainer-review-correction-and-acceptance-2026-10-26) — 52 lines + - [P03-1 Step 4 — Contextual foundation and owned seed (2026-10-26)](#p03-1-step-4--contextual-foundation-and-owned-seed-2026-10-26) — 90 lines + - [P03-1 Step 4 review round 1 (2026-10-26)](#p03-1-step-4-review-round-1-2026-10-26) — 25 lines + - [P03-1 Step 4 review round 2 and diagnostic correction (2026-10-26)](#p03-1-step-4-review-round-2-and-diagnostic-correction-2026-10-26) — 47 lines + - [P03-1 Step 4 exported trace correction (2026-10-26)](#p03-1-step-4-exported-trace-correction-2026-10-26) — 37 lines + - [P03-1 Step 4 local closeout (2026-10-26)](#p03-1-step-4-local-closeout-2026-10-26) — 22 lines + - [P03-1 Step 5 — Existing-binding API admission (2026-10-26)](#p03-1-step-5--existing-binding-api-admission-2026-10-26) — 85 lines + - [P03-1 Step 5 review round 1 and read-diagnostic correction (2026-10-26)](#p03-1-step-5-review-round-1-and-read-diagnostic-correction-2026-10-26) — 43 lines + - [P03-1 Step 5 review round 2 and local closeout (2026-10-26)](#p03-1-step-5-review-round-2-and-local-closeout-2026-10-26) — 30 lines + - [P03-1 Step 6 — Complete qualification inventories (2026-10-26)](#p03-1-step-6--complete-qualification-inventories-2026-10-26) — 46 lines + - [P03-1 Step 6 review round 1 and carrier correction (2026-10-26)](#p03-1-step-6-review-round-1-and-carrier-correction-2026-10-26) — 36 lines + - [P03-1 Step 6 full ordinary failures and bounded corrections (2026-10-26)](#p03-1-step-6-full-ordinary-failures-and-bounded-corrections-2026-10-26) — 78 lines + - [P03-1 Step 6 review round 2 and complete parent-stack correction (2026-10-26)](#p03-1-step-6-review-round-2-and-complete-parent-stack-correction-2026-10-26) — 41 lines + - [P03-1 Step 6 correction approvals and first hosted assignment (2026-10-26)](#p03-1-step-6-correction-approvals-and-first-hosted-assignment-2026-10-26) — 48 lines + - [P03-1 Step 6 measured timing revision (2026-10-26)](#p03-1-step-6-measured-timing-revision-2026-10-26) — 39 lines + - [P03-1 Step 6 qualification closeout and PR handoff (2026-10-26)](#p03-1-step-6-qualification-closeout-and-pr-handoff-2026-10-26) — 73 lines + - [P03-1 PR 38 review corrections (2026-10-26)](#p03-1-pr-38-review-corrections-2026-10-26) — 98 lines + - [P03-1 PR 38 correction review round 1 (2026-10-26)](#p03-1-pr-38-correction-review-round-1-2026-10-26) — 55 lines + - [P03-1 PR 38 correction review round 2 (2026-10-26)](#p03-1-pr-38-correction-review-round-2-2026-10-26) — 31 lines + - [P03-1 PR 38 correction fixture census (2026-10-26)](#p03-1-pr-38-correction-fixture-census-2026-10-26) — 15 lines + - [P03-1 PR 38 measured timing correction (2026-10-26)](#p03-1-pr-38-measured-timing-correction-2026-10-26) — 42 lines + - [P03-1 PR 38 independent mutation collections (2026-10-26)](#p03-1-pr-38-independent-mutation-collections-2026-10-26) — 77 lines + - [P03-1 PR #38 current-source A/B and ordinary window proposal (2026-10-26)](#p03-1-pr-38-current-source-ab-and-ordinary-window-proposal-2026-10-26) — 98 lines + - [ADR-0075 proposal review round 1 (2026-10-26)](#adr-0075-proposal-review-round-1-2026-10-26) — 29 lines + - [ADR-0075 proposal review round 2 (2026-10-26)](#adr-0075-proposal-review-round-2-2026-10-26) — 27 lines + - [ADR-0075 maintainer review and revised package (2026-10-27)](#adr-0075-maintainer-review-and-revised-package-2026-10-27) — 103 lines + - [ADR-0075 revised proposal review round 1 (2026-10-27)](#adr-0075-revised-proposal-review-round-1-2026-10-27) — 20 lines + - [ADR-0075 revised proposal review round 2 (2026-10-27)](#adr-0075-revised-proposal-review-round-2-2026-10-27) — 25 lines + - [ADR-0075 acceptance and Step 1 (2026-10-27)](#adr-0075-acceptance-and-step-1-2026-10-27) — 28 lines + - [ADR-0075 Step 1 review round 1 (2026-10-27)](#adr-0075-step-1-review-round-1-2026-10-27) — 14 lines + - [ADR-0075 Step 1 review round 2 and closeout (2026-10-27)](#adr-0075-step-1-review-round-2-and-closeout-2026-10-27) — 13 lines + - [ADR-0075 Step 2 closed budget implementation (2026-10-27)](#adr-0075-step-2-closed-budget-implementation-2026-10-27) — 44 lines + - [ADR-0075 Step 2 review round 1 (2026-10-27)](#adr-0075-step-2-review-round-1-2026-10-27) — 16 lines + - [ADR-0075 Step 2 review round 2 and qualification handoff (2026-10-27)](#adr-0075-step-2-review-round-2-and-qualification-handoff-2026-10-27) — 24 lines + - [ADR-0075 Step 3 fresh hosted A/B evidence (2026-10-27)](#adr-0075-step-3-fresh-hosted-ab-evidence-2026-10-27) — 54 lines + - [ADR-0075 Step 3 review round 1 (2026-10-27)](#adr-0075-step-3-review-round-1-2026-10-27) — 30 lines + - [ADR-0075 Step 3 review round 2 correction (2026-10-27)](#adr-0075-step-3-review-round-2-correction-2026-10-27) — 28 lines + - [ADR-0075 three-step closeout (2026-10-27)](#adr-0075-three-step-closeout-2026-10-27) — 32 lines + + + +## P03-0 — Entry preparation + +### Entry preparation (2026-10-25) + +**Scope.** Reconcile the phase plan and its connected contracts before the first +identity, membership or authorization writer. No runtime, schema, provider realm, +Hub crossing or deployment activation is changed. No Phase 03 implementation +decision package is Accepted in this entry. + +**Verified baseline.** Preparation starts from development at +`819ef226053f06ffcf787ceaceefa09781240f32`, after completed Phase 02b. Relevant +production seams were rechecked against that source: + +- `TenantTokenProfile` requires stable UUID actor claims; the native provider + requires actor and tenant before callback publication. Development reconciliation + only installs declared seed identity attributes, not arbitrary runtime accounts. +- `TenantResolverMiddleware` asks membership before installing tenant context. + `AuthorizationBehavior` still passes through before the ordinary transaction. + Membership and Platform admission defaults deny everyone. +- The authenticated native caller admits only AccountSite. Existing provider user + attributes emit active scope; ordinary BFF refresh preserves the original scope. +- The shared JSON Schema profile requires nonempty root properties. Current + Customization definitions are versioned; no custom-field aggregate is delivered. +- Platform scope has a separate bypass connection and no admitted actor consumer; + ordinary event/job execution supplies no privileged redaction authority. +- The committed gateway scaffold has priorities and no Hub-secret reference, but + retains version wildcard paths. Architecture 30 already documents their remedy. + +**Reconciliation.** Each first-writer question now has a packet, vehicle and +observable proof in the phase's decision/delivery/criterion tables. Detailed +answers remain with their last responsible consumer under +[Decision Timing](README.md#decision-timing). + +| Concern | Canonical disposition | +|---|---| +| Actor bootstrap before accepted login | G1 / P03-1; real nonseed and concurrent mapping proof in C01 | +| Pre-context membership/permission access | G2 / P03-1 contract and P03-2 execution; exact grants/setters and C05 | +| Platform population, surface and actor chain | G13 / first privileged consumer; preserve ADR-0036 and demand-gated Hub boundary | +| Per-session scope switching | G4 implications before shared schema, transition in P03-3; independent real refresh proof | +| Grant ceilings, seed defaults and revocation | G5 / foundation and authorization; Standard 19 identifies unresolved target choices | +| Membership/profile/lifecycle/global disclosure | G3 before migration; conceptual ER no longer implies a single role or cross-module Organization FK | +| Protected native/API operations | G6 / policy then transport; exact SDK/CSRF/ETag/replay/cache boundary in C06 | +| Invitation identity, races, atomicity and delivery | G8 before its first affected schema/writer; usable bounded handoff owned here, full engine remains Phase 08a | +| Subject/org/recipient DSAR authority | G15; RLS remains tenant/org isolation and never substitutes for subject predicates | +| Custom-field revision/classification and schema profile | G9; Customization owns definitions; unsafe global User helper and unversioned illustrative DDL removed | +| Provider-event topology and attribution | G10; authenticated durable intake, stable dedup and outbox-backed facts, no direct business publication | +| Tenant federation and account linking | G12; broker/email alone grants no membership, with scoped provider ownership/recovery proof | +| DSAR artifact/workflow/global closure | G16; private artifact and job prerequisites, retained authority, closure fence and privileged reconciliation | +| Denied/sensitive-read audit and enrichment | G7; actual HTTP/application evidence ownership, trusted request port and locators | +| Packet/register/exit completeness | Twelve packets, nineteen gates, D01–D16 and C01–C21 with inherited catalogue obligations | +| Gateway correction boundary | G18; explicit version paths and inactive scaffold correction here, reviewed public allowlist/lint/activation Phase 11 | +| Stale ownership/PII/target descriptions | Phase and Customization architecture reflect the delivered marker and Membership target; G19 owns first-PII census | +| HMAC threat statement | Gateway architecture distinguishes forged body signatures from independent JWT/mTLS admission | + +**Validation.** Documentation-only checks pass on the reconciled sources: + +- `make lint-docs`: 2,399 relative fragment links resolve, ADR-0069 plan/log/status + structure conforms and three generated delivery-log indexes are current. +- Existing guard controls: 9 fragment, 12 roadmap-structure, 9 delivery-index and + 5 workflow-link tests pass, 35 in total. +- The changed-document file-target sweep resolves 1,014 relative links across + 17 Markdown files. Gate/deliverable/criterion identities are complete and unique; + all nineteen implementation gates remain Open. +- `git diff --check` and the added-prose wrap check pass. No runtime/configuration + file or Accepted ADR is edited; all changed-document references resolve to + canonical repository sources. + +The semantic self-review checks realm/actor boundaries, earliest schema/adapter +consumers, scope/filter/write-guard separation, aggregate/module ownership, audit +and privacy evidence, external-effect recovery and complete phase-exit coverage. +No backend/frontend/provider/browser suite is rerun: this record qualifies the +document preparation, not the undelivered runtime behavior in the criteria. + +**Next boundary.** P03-1 begins with explicit acceptance of G1/G2/G3/G19 and the +schema-affecting G4/G5 parts. It includes G8/G16 only where their answers affect +the first identity tables. No later feature table or dormant writer may preempt +its own gate. Selecting a provider/platform mechanism that changes an Accepted +decision needs its correct disclosure or successor before implementation. + +**Preparation versus delivery.** The document plan is ready for that decision +pass. Nonseed bootstrap, live authorization, operator admission and DSAR runtime +proof remain required implementation work; this entry claims none of them passed. + +## P03-1 — Identity authority and membership foundation + +### P03-1 proposed decision package (2026-10-25) + +**Status: Proposed.** The maintainer requested P03-1 on `development`, with a +complete prior-document review, upfront decisions, approval before a new ADR is +implemented, and two fresh independent review rounds after each committed step. +No gate is Accepted here. No runtime, realm, schema, permission or grant changes. + +**Source.** Review starts at `46da68132987759b7ca6a19230b525b5485c7441`, the +existing Phase 03 entry-preparation commit. Its predecessor closes merged Phase +02b. Preserve both commits and the unrelated untracked worktree directory. + +**Problem and scope.** Establish durable application identity and contextual +membership/role foundations before live authorization. Existing strict bearer +validation and native BFF custody are inputs, not bootstrap or grant mechanisms. +P03-1 supplies D01/D08 and the foundation portions of C01/C02/C03/C10. P03-2 owns +live resolver/permission execution; P03-3 owns administration and usable scope +discovery/switching. This package does not accept their still-open policies. + +#### Documentation and source review + +Read the working agreement and `implement-task`/`start-task`, product vision, +MVP/roadmap/principles/glossary, current phase/entry record, identity and module +boundaries, database/tenant/permission/audit/privacy authorities and related +Accepted decisions. Trace current API/BFF/seed, transaction/filter/RLS, audit +capture/error sinks and architecture-test seams. Three independent read-only +audits separately cover G1/G2, schema/lifecycle/delegation and G19/privacy. +These are static design reviews, not provider/database/runtime qualifications. + +| Verified fact | First-writer consequence | +|---|---| +| Identity's four packages contain assembly markers only | No existing identity schema/grant behavior decides the model | +| API and BFF require an actor claim; only four development personas receive one | A nonseed actor needs an explicit bootstrap contract before accepted login | +| Membership is asked before tenant context; permission behavior precedes transaction | No ordinary repository, hidden setter or Platform bypass can fill this gap | +| Four login roles and eight logical tenant setters are closed | New subject owners/candidate reader need explicit authority and census | +| Global User has no tenant; current global audit rejects this write shape | Decide global self RLS and same-transaction central audit, not a fake tenant | +| Tenant filters do not exclude deleted rows or carry app.scope; org validation checks belonging | Lifecycle predicates and eligibility cannot be inferred from those mechanisms | +| SeedData preserves four actor identities; it declares no application memberships | Adopt actual provider bindings explicitly, then create only declared grants | +| Snapshot PII markers/name redaction/LS0002 have bounded distinct scopes | Add a semantic mapped-property census and fixed writer diagnostics | +| Existing audit/event references survive six-column redaction | Decide anti-recreation/fence now; do not claim completed anonymisation | + +Four current non-ADR carrier ambiguities are corrected in this preparation: +Module Boundaries now distinguishes native BFF custody from Identity and central +mutation audit from provider mirroring; Data Protection places tenant restriction +in membership context, never User; Audit architecture/catalogue distinguish +P03-1's User prerequisite from P03-10's locator/privileged erasure delivery. +Accepted ADR bodies and all historical delivery entries remain untouched. + +#### Proposed answers and exact split gates + +| Gate/part | Proposed answer / vehicle | Remaining named obligation | +|---|---|---| +| G1 | ADR-0072: application allocates one permanent actor from verified issuer/opaque sub; explicit bootstrap; trusted seed adoption | P03-4 completes real invitation enrollment; no email merge/provider Admin write | +| G2 storage/reader contract | ADR-0072 global self owner; ADR-0073 app-role candidate read owner, new enumerated setter and step-5/6 handoff | P03-2 execution, live rows 7/10/14 and protected 6/9; claim-only mismatch evidence before activation | +| G3 | ADR-0073: Membership contains one contextual profile and multiple assignments; null-safe natural key, lifecycle/successor and finite role scopes, including the explicit Organization Learner variant | P03-3 field/HTTP/admin/organization operations; P03-5 dynamic fields | +| G4 shared implications | No global active-scope column; actor-only bootstrap does not publish a tenant BFF session | P03-3 usable discovery, per-session issuance, switch/refresh/logout races and real A/B proof | +| G5 schema/bootstrap | Scoped permission identity; code definitions, finite initial grants, disabled later additions, last-admin serialization | P03-2 permission enforcement/delegation/denial and revocation execution; P03-3 UI | +| G7 only new global mutation | ADR-0072: first User and central MUST row share one app-role transaction; confined same-subject failed/indeterminate reconciliation preserves ADR-0033 | P03-2 normal HTTP/application denial/enrichment; no general standalone budget | +| G8 shared shape | No Invitation table/implicit multi-root exception; Membership natural key supports later reconciliation | P03-4 acceptance/delivery/aggregate atomicity decision before writer | +| G16 shared invariants | Permanent binding/tombstone, global admission lock, no implicit global closure on tenant erasure | P03-10 authority, holds, participants, transformations, artifacts, provider finalization and completion | +| G19 | ADR-0073: explicit mapped-property classification, fixed diagnostics and sink/capture canaries | P03-5 revision-aware dynamic values; P03-10 locator/erasure fulfillment | + +The new global mutation slice replaces an audit restriction through its named +ADR. It adds no operator population, Platform permission, Hub crossing or provider +ingress; G10/G13 need not move into bootstrap under this selected design. If +implementation discovers such a dependency, its affected gate closes before code. + +#### Maintainer decisions requested together + +1. Adopt ADR-0072, knowingly replacing the required provider `user_id` with an + application-owned binding and an optional consistency claim. Keep all other + strict token checks; ordinary reads never create Users. This changes the API/ + BFF contract and introduces authenticated binding-store availability cost. +2. Admit the exact global-self POST, transactional global User/audit class and + confined non-success reconciliation, subject RLS and owner-read closure guard. + Linkable audit subject keys survive under security retention even without a + User. No fifth login/bypass, operator grant, public directory or tenant + authority is implied. +3. Adopt ADR-0073's contained membership/profile/grant model, null-safe lifecycle, + scoped finite permission manifests and concurrent last-admin invariant. +4. Approve permanent anti-recreation binding retention as a first-schema choice. + It retains linkable identifiers; P03-10 still owes the separate privacy/ + transformation decision. Approve no automatic new-permission grants on rerun. +5. Adopt the complete classification/diagnostic boundary and six implementation + steps below. The two ADRs and this package are the approval surface; no + separate runtime policy is hidden in a review receipt. + +#### Six implementation steps + +| Step | Concrete result | Main surfaces | Required validation before closure | +|---|---|---|---| +| 1 | Accept decisions, append exact dated disclosures, register obligations and reconcile canonical authorities | ADR-0003/0017/0033/0036/0040/0044/0064/0070; Standards 05/11/18/19/21; Identity spec and applicable architecture/glossary | Parser/status, exact clauses/carrier audit, whole-tree docs lint, no Accepted-body rewrite | +| 2 | Complete typed property classification census and safe diagnostic boundary before identity PII writes | SharedKernel metadata; production EF models; module PII/audit specs; observability/error tests | Nonempty model census; planted omission; real sink/capture positive and canary controls; existing redaction remains | +| 3 | Global User/binding storage, confined self owner, atomic central audit/non-success reconciliation and closure guard | Identity Domain/Infrastructure; common transaction/audit contracts; migration chain and fixtures | Real app-role RLS and uniqueness races; missing/mismatched success audit, rollback/loser/unknown-COMMIT/standalone failure, fresh post-lock/incompatible-isolation and owner/pooled/cancellation controls | +| 4 | Membership/Profile/Role foundation and semantic identity/member seed adoption | Identity packages/contracts; Tenancy lifecycle contract; Seeder/shared seed-demo handoff; role/PII matrices | Null-key/scope/child/audit/lifecycle and last-admin races; real warm provider seed readback, preserved credentials and no-write rerun | +| 5 | Explicit bootstrap HTTP, binding-based ordinary identity and coordinated native BFF/SDK activation | API authentication/global-self surface; generated SDK; native provider/session response owners; OpenAPI | Real actorless Keycloak tokens/native HTTPS; binding matrix; unknown-host/quota/body/protocol/late-publication controls; unchanged anonymous flow | +| 6 | Complete integrated qualification, corpus/CI assignment and source-bound closeout | Actual test owners; bounded shard plan if discovery changes; phase Status/log; reviewable PR description | Relevant complete backend/frontend suites, real provider/browser slice, full complementary A/B CI under existing ceilings/names, no skips/empty proof | + +Each step is committed on `development`, receives two independent fresh review +rounds, and commits fixes only for verified findings. New reviewers inspect the +fixed source; receipts name commits, scope, commands/results and limitations. +Continue automatically between accepted steps. A new architectural decision or +verified blocker is surfaced before its dependent work. No historical review +claim is silently rewritten and no passing suite substitutes for the other round. + +Implementation dispatches `add-tenant-owned-entity` only for contextual tables, +`add-ef-migration`, `add-mediatr-handler`, `add-audit-coverage`, `add-permission`, +`add-architecture-test`, `add-integration-test`, `seed-tenant` and the relevant +native/SDK workflow. Global User follows its accepted class, not a tenant template. +`run-tests-locally`, `standards-check` and `commit-and-pr` supply verification and +commit gates. No runtime provider SDK is needed by the selected binding strategy; +its conditional backfill is not claimed complete. + +#### Proof boundaries and carry-forward + +Foundation proof must use real PostgreSQL with `learnstack_app` for ordinary +isolation, pinned Keycloak for actual actorless/seed issuance and native HTTPS +for BFF publication. Structural checks have planted dirty/clean controls; +behavioral failures must identify the mechanism they exercise. Register actual +production model/route/adoption subjects, not test-only placeholders. + +No generic protected route is admitted while AuthorizationBehavior remains a +shell. No invite, federation, operator, DSAR, global-profile editor, full Studio, +dynamic-field schema or distributed session store is delivered by this package. +Their first-writer contracts remain assigned in the phase register; no required +P03-1 prerequisite is relabeled as a later production-hardening task. + +**Validation boundary.** The review and readiness entries below own completed +mechanical/static results. There is no backend/frontend/provider execution or +implementation qualification in this documentation-only decision pass. + +### P03-1 proposal review round 1 (2026-10-25) + +**Reviewed source:** `8cf352f40e57766206ea81ec2a1dd803242cbf46`. Two fresh, +independent reviewers use GPT-6 Astra / xhigh for authority/global SQL/audit and +GPT-6.1 Sol / xhigh for the membership/privacy/step model. Both run read-only +reviews, inspect current source and Accepted authorities, and execute no runtime +tests or provider writes. This records their actual scope, not implementation +qualification or maintainer acceptance. + +Two Major proposal gaps are verified and corrected before the next round: + +- The BFF currently rejects missing tenant before bootstrap. ADR-0072 now + explicitly admits a strict pre-session provider-subject projection with actor + and tenant optional. It requires the ordinary positive AccountSite scope + witness before session publication and a real actorless/tenantless control. +- The declared Yoga learner has organization scope, but the role proposal had + no explicit Organization Learner shape. ADR-0073 now selects that finite + scope variant, exact assignment compatibility and other-branch denial, without + silently making the learner a tenant-wide member. + +Two design ambiguities are also resolved, without claiming observed runtime +defects: creation-audit reciprocity is an insertion-time deferred witness, not a +perpetual cross-module FK blocking retention purge; the User fence uses a named +transaction advisory lock and exact owner-policy read, not an unspecified row +lock requiring a second policy. A separate state-only Boolean read supports +last-admin eligibility; later closure joins the same tenant invariant locks. +The canonical new proof names and planned owners are now explicit. + +Mechanical checks on the initial proposal pass: `make lint-docs` resolves 2,408 +fragment links, roadmap structure and three generated indexes; the changed-doc +file sweep resolves 1,013 relative targets; both ADRs parse Proposed. Existing +ADR/parser/fragment/roadmap/index controls pass 37 tests in total. No application +suite is rerun for this documentation-only review. Corrected-source checks and +a second independent round remain required before requesting approval. + +### P03-1 proposal review round 2 (2026-10-25) + +**Reviewed source:** `c9a969f6`. Two different fresh reviewers use GPT-6.1 Sol / +xhigh for authority/SQL and GPT-6 Astra / xhigh for model/privacy/audit. Both +independently verify the first round's tenantless pre-session, scoped Learner, +insertion-only witness and advisory-lock corrections. Both remain read-only; +neither runs application/provider/database tests or changes source. + +Two additional Major contract gaps are verified and corrected: + +- Lock ownership alone does not supply a fresh snapshot. User/tenant invariant + writers and database guards now require READ COMMITTED, refuse incompatible + isolation and read again after the awaited lock in a fresh VOLATILE query. + Held-lock competing-commit and stale-snapshot controls are mandatory. +- ADR-0033 requires failed/indeterminate MUST reconciliation, while the initial + global proposal admitted only a transactional success row. ADR-0072 now names + the central global non-success seam, same verified subject, exact duplicate + witness, loser/rollback/unknown-COMMIT/failure disposition, cleanup ownership + and ADR-0033 disclosure. Its immutable subject-key attribution is explicitly + linkable PII under the existing security-audit retention; no new budget waives + those rows. Normal known-binding reads stage no mutation/audit intent. + +Final source reconciliation preserves ADR-0044 § 5's fresh standalone timestamp +and possible indeterminate pair, instead of introducing an unnecessary global +key/timestamp exception. User's success reference remains insertion-only; a +duplicate must match the exact operation/target/subject/outcome, and a durable +failed row is never evidence that User creation committed. + +The subject EF filter and direct baseline catalogue ownership are also explicit; +no tenant override lookup or new context bypass is inferred for global rows. +The existing native API response budget remains ten seconds; cancellation ends +waiting/publication, not proof that centrally owned audit cleanup completed. +The corrected proposal is rechecked against source and the PostgreSQL 18 +isolation/volatility/policy contracts. A targeted correction verification and +final mechanical checks follow before maintainer approval is requested. + +### P03-1 proposal readiness (2026-10-25) + +**Source reviewed:** `037fd56f`, after first draft `8cf352f4`, round-one fixes +`c9a969f6` and round-two fixes `d0fd67de`. Three initial read-only audits establish +the prior-document/source gaps. Two fresh reviewers per full round examine the +proposal; the second-round reviewers then independently verify the targeted +corrections at the final source. That verification is not a third full round. +Their reviewed scopes report no remaining concrete actionable finding. Neither +static review nor these documentation checks supplies runtime qualification. + +The new authorities remain Proposed: + +- [ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md): application- + owned binding, exact global-self operation, atomic global audit and confined + failed/indeterminate reconciliation, seed preservation and closure fence. +- [ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md): + contained contextual membership state, finite scoped grants/Organization + Learner, last-admin/read-committed invariants and complete PII/diagnostic census. +- The [six-step package](#p03-1-proposed-decision-package-2026-10-25) identifies + the user decisions, exact gate parts, proof owners and later packet boundaries. + +The final audit preserves P03-0 history byte-for-byte outside the generated index, +changes no Accepted ADR/runtime/configuration file, leaves all nineteen gates +Open and stays on `development`. No foreign process/worktree or provider state +is changed. Commits are local; no PR or push is performed by this preparation. +The user's explicit approval-before-new-ADR requirement is the remaining gate; +acceptance/disclosures and all dependent implementation await that answer. + +Final document validation is recorded on this proposal source before commit: +2,413 whole-tree fragment links, roadmap structure and three current indexes; +1,258 changed-document relative targets with none missing; both ADRs parse +Proposed; added ADR prose, whitespace and private-path residual checks pass. +Existing parser/fragment/structure/index guard controls pass 37 tests. No +application test is presented as run or passing in this proposal preparation. + +### P03-1 maintainer review disposition (2026-10-25) + +**Reviewed source:** `9211789342fd15c0a9a1cafaeb80ea7b7ca345d8`. The maintainer +returned review findings rather than approval. Both ADRs remain Proposed; all +nineteen gates remain Open. Earlier source-bound reviewer conclusions remain +historical. This follow-up reopens their readiness conclusion; it does not claim +the earlier reviewers verified findings they did not report. + +Three read-only source verifications cover global SQL/auth/instruments, +membership/bootstrap/manifests, and privacy/retention/operational carriers. +They inspect current code and authorities, not instructions in review data. +No provider/database/application tests or state changes occur in that audit. + +| Review items | Verified disposition / revision | +|---|---| +| F1/K1, Y4 | Valid incomplete global write/read contract and contradictory unmodified-policy wording. Proposed Standard 05 now declares seventh class, exact audit policy arms, owner evidence functions, grants and central seams. PlatformSentinel's second population is explicit, not operator authority. | +| F2 | Host-lookup definer rejection is real but host-specific, not a universal impossibility. Explicitly choose limited migration-owner execution with owner SELECT policies; compare projection/fifth-role alternatives. Migration credentials stay outside runtime. | +| K2/O7 | Key already uses issuer/sub, but its typed consumer requires actor. New provider projection/feature/quota handoff before binding is explicit; API/BFF sub limit is 255. This is a proposed replacement, not a claim current code supports it. | +| K3/Y3/F10 | New ADRs already supply a superseding instrument, but affected clauses/Amendments were underspecified. Append-ready drafts below name each bounded change, separate navigation and keep old bodies/metadata intact. No Amendment number is reserved. | +| F3/Y5 | Replace independently configured per-org Roles with tenant-wide capability templates; organization lives on Membership assignments. Exact contextual schema/FKs/guards are in the Proposed Identity spec. No per-org Role initialization writer is needed. | +| Y1/Y2/O8 | Define staged seed Role roots then first-admin Membership, no cross-module transaction. First/final-admin predicate covers Trial/Active/Suspended and every Membership mutation. Production first-admin belongs P03-9/G13; Tenancy archive race remains P03-3 before its writer. No writable bootstrap flag/table is invented. | +| Y7 | Include reactivation and authority-increasing assignment changes in User-before-tenant admission fencing; DB lifecycle prevents resurrection. Current global eligibility already denies closed accounts, so this was not demonstrated shipped access bypass. | +| F4 | Introduce stable authority registration, config-drift refusal and named P03-9 rebind owner before rename; no silent new identity domain or email-based continuity. | +| F5/O1/O2 | Choose permanent digest/actor tombstone now, with raw subject nullable and removed at Closed. No per-User raw issuer or unused email. Digest remains access-controlled, potentially guessable PII; metadata remains immutable under security retention. P03-10 locates failed attempts even without User. | +| F6 | Serialize subject before allocation/intent; benign waiters return the winner without failed mutation audit. Genuine failures/unknown COMMIT keep MUST reconciliation. Membershipless identity is allowed without verified email; provider registration cardinality cost is explicit. | +| F7 | 401 on ordinary binding outage preserves Accepted 0064/0071; mandatory 503/witness is not a bug fix. Compare and decline that separate policy change. Add closed diagnostic reasons and typed bootstrap 503 translation instead. | +| F8/O4/O5 | Proposed Standard 19 enumerates five production-command permission pairs, eight templates/seven role keys and exact two-pair kernel; one versioned compiled source generates verified guard artifacts. Registry scope identity and Organization Learner are explicit; later routes remain closed. | +| F9/O9 | Remove unused email/verification columns and parsing from P03-1. First proven mirror consumer, currently P03-6/G10, owns their later schema/freshness. | +| O3 | Seed already refused unauthorized repair by decision. Pin existing manifests/fingerprints; registry additions do not change v1 completion. Conflict stops later seed acts, leaving earlier commits. A destructive reset is not introduced. | +| O6/census ownership | Prior draft already named Step 2 and DataProtectionConventionTests; timeline was not TBD. Strengthen per-module declaration/coordinator ownership and automatic complete-model diff. Distinguish planned/unregistered, Registered, Awaiting backfill and actual Implemented states. | +| Missing contention detail | Specify bounded transaction lock waits and identity-free closed telemetry; Phase 11 owns field thresholds/load qualification. | +| Global-table glossary allegation | Not reproduced: the current term does not impose bypass-only access. Preserve it; fix actual AuditEntry/sentinel/class/method claims on acceptance. | +| Stale generated index | Reproduced at 92117893. Final readiness prose changed its line count without regeneration; the earlier lint claim did not qualify that final commit. Regenerate after the last edit and validate the committed index. | + +### P03-1 revised decision package (2026-10-25) + +**Status: Proposed; no maintainer acceptance.** This package replaces the earlier +draft as the current approval surface, not its historical review entries. +Joint [ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md) and +[ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md), +their clearly Proposed canonical annexes/specs and these Amendment drafts are +reviewed together. Existing Adopted standards and Accepted ADR text stay active +until explicit approval. No runtime/configuration/schema file changes here. + +#### Approval surface and owners + +| Contract | Canonical proposed owner / decision | +|---|---| +| Global class, anchor, key, grants, RLS/evidence reads, lock limits | [Standard 05](../standards/05-database.md#proposed-p03-1-identity-storage-annex): one authority anchor, digest/actor tombstone, no raw subject at Closed; enumerated owner privilege and two global audit seams | +| Provider-subject credential/quota and exact route | [Standard 11](../standards/11-security.md#proposed-p03-1-identity-admission-annex): no bearer → 404, invalid present → 401; quota before binding; ordinary outage uniform 401, exact bootstrap storage 503 | +| Contextual tables/first-admin/lifecycle | [Identity spec](../modules/identity/README.md): one Membership root and tenant-wide Role templates, guarded seed-only commands, no new ADR-0042 exception or bootstrap flag | +| Exact roles/permissions/kernel/upgrades | [Standard 19](../standards/19-permissions.md#proposed-identity-foundation-contract): five scoped pairs, finite v1 manifests, no new-key automatic grants; generated SQL/compiled-source equality | +| PII and retained-copy purpose | [Data Protection](../architecture/23-data-protection.md#proposed-identity-foundation-and-classification-ownership): per-module declarations, complete automated model diff in Step 2, explicit snapshot/diagnostic boundaries, Identity closure/Audit participants in P03-10 | +| Module matrices | [Permissions](../modules/identity/permissions.md), [audit](../modules/identity/audit.md): compiled internal seed commands are production subjects, not proof of live endpoint enforcement | + +G1/G3/G19 and schema parts of G2/G4/G5/G16 close only on joint acceptance. +G7 closes only the explicit global mutation/reconciliation slice; G2 candidate +reader execution stays P03-2. G8 needs no Invitation table/exception here. +Production onboarding, live permissions, scope transition, provider mirroring, +operator recovery and closure remain with their named packets; none is an +unclaimed P03-1 dependency. No provider ingress or new Platform population is +required by the selected bootstrap mechanism. + +#### Append-ready Amendment drafts + +These are proposed texts for existing ADRs, not amendments already applied. +At acceptance, use the actual date/next available heading in each target, link +the newly Accepted vehicles, and preserve every original heading/body/metadata. +Append each under that ADR's Amendments; a table entry or the word disclosure +alone does not amend the old authority. No future number is reserved here. + +**ADR-0036 — bounded global-self admission and candidate-reader contract.** + +> ADR-0072/0073 bound this ADR's ordinary HTTP resolution rule for the exact +> POST /api/v1/account/bootstrap. Known-host credential verification and +> provider-subject quota precede it; missing bearer remains masked 404, invalid +> present bearer 401. Valid subject enters the new global-self owner without +> installing ITenantContext or choosing a tenant. Ordinary reconciliation and +> its rows remain route-independent. The exact GlobalSelfIdentity descriptor is +> separate from AllowsUnresolvedTenantContext; its provisioning allowlist and +> four TenantContext writers do not grow. PreContextIdentityAuthorizationReader +> confirms an already verified actor's candidate tenant/org in a short app-role +> READ ONLY owner; it installs no context. Its execution and real rows 7/10/14, +> protected 6/9 and claim-only mismatch evidence remain P03-2 prerequisites. + +**ADR-0040 — global owners, nesting and the ninth logical tenant setter.** + +> ADR-0072 adds exact global self-read/bootstrap/seed-adoption/reconcile owners +> with verified identity announcements specified in Standard 05. They connect +> as learnstack_app and never announce PlatformSentinel as tenant. Common frame +> generation, capture and cleanup govern them; tenant/global modes cannot join +> or retarget one another. ADR-0073 accepts the separately named future ninth +> tenant setter PreContextIdentityAuthorizationReader, using learnstack_app +> with exact candidate app.tenant_id/app.organization_id in its own physically +> READ ONLY transaction, closed before the ordinary request owner. The existing +> eight logical paths remain the current implemented set until P03-2 delivers +> and qualifies this adapter. Identity-only announcements are a separate census, +> not hidden tenant setters. No other setter/context writer is admitted. + +**Other required dated Amendment bodies:** + +| Target | Proposed appended text / instrument | +|---|---| +| ADR-0003 | ADR-0072 admits global self-identity as a seventh class, the identity_authority platform anchor, exact role-qualified global audit/owner-policy arms and named definer functions. Standard 05 is the sole SQL authority; existing tenant/org template and four login credentials remain. This names new owner execution power without runtime owner credentials. | +| ADR-0017 | ADR-0073 clarifies Membership's contained profile/assignments and tenant-wide Role templates: template capability scope is not storage/authoring scope. Organization authority derives only from exact Membership binding; tenant grants plus matching-org grants remain. Organization aggregate/CRUD stays Tenancy-owned. | +| ADR-0033 | ADR-0072 extends central decide/write/reconcile to global identity creation under the named app-role owners, including failed/indeterminate attempts. Success shares the User transaction; fresh standalone timestamps/indeterminate pairs and required failure signals remain. Amendment 5's old platform-only routing does not authorize or substitute for these new global seams. | +| ADR-0044 | ADR-0072 narrowly supersedes the sole sentinel population/writer and unresolved-no-row rules for identity.user.create MUST/SecurityEvent. Exact new app INSERT, owner evidence reads, central pending/reconcile seams and insertion-time witnesses are required. Tenant setters/ordinary writers still reject sentinel; platform entry remains its separate standalone owner. No metadata UPDATE or broad sentinel capability is granted. | +| ADR-0053 | ADR-0072 extends Amendment 11's confined authenticated BFF seam with exact pre-session POST /api/v1/account/bootstrap using the independently verified provider grant and host/visitor hop. The result establishes only matching actor association; AccountSite still witnesses ordinary session scope. No browser credential forwarding, general proxy or change to anonymous public wrappers follows. | +| ADR-0064 | ADR-0072 narrowly replaces required wire actor with verified provider-subject plus existing-binding normalization, and extends GET/HEAD-only surface with exact global-self POST. Quota source moves before binding; actor optionality is no anonymous fallback. Absent-bearer 404 and other strict validation remain. No ordinary permission route or scope authority follows. | +| ADR-0070 | ADR-0072 adds pre-session provider projection with 255-character subject and optional actor/tenant, followed by explicit bootstrap association. Only matching AccountSite publishes ordinary scope. Refresh resolves existing identity without allocation and preserves original claim presence/values and session fences. Actor-only entry publishes no tenant session. | +| ADR-0071 | Navigation only: ADR-0072 preserves the ordinary-read table and uniform 401 despite the additional binding-store uncertainty source. Bootstrap has separate initial storage failures; no new refusal witness, retry or refresh policy is inferred. | + +Before dependent code, reconcile Standard 05's six-class, global-index exceptions, +closed GUC-name list, unmodified-audit and migration-never-runtime-execution +statements; Standard 11's owner/census; Standard 19's scoped identity/manifests; +CLAUDE/glossary sentinel +population and IAuditStore XML/method counts. Preserve source-bound current +history; do not edit Accepted bodies as though these decisions were factual +corrections. All new catalogue obligations are planned until actual registration. + +#### Revised implementation steps and falsifiable proof + +The original six-step dependency order is retained, with the following explicit +corrections; every committed step still receives two fresh independent reviews. + +| Step | Required scope / evidence | +|---|---| +| 1 — Acceptance | Joint approval, actual dated Amendments above, promote only approved annexes, authority headers and planned catalogue rows. No dependent code precedes the acceptance commit. | +| 2 — Classification | Each mapped module owns complete declarations; Infrastructure Data Protection coordinator compares real EF properties automatically, including inherited IDs, raw subject and stable linkage. DataProtectionConventionTests and planted neutral-name omission are implemented here before Step 3. Existing snapshots/log/local/Sentry positive-plus-canary controls remain distinct. | +| 3 — Global storage/audit | Sixth Identity migration chain, deploy-only authority installer, subject-key serialization before intent, exact RLS/evidence functions, reciprocal success/failed/unknown-COMMIT/duplicate/standalone-failure controls, READ COMMITTED/fresh post-wait and incompatible-isolation controls. No operator credential in runtime. | +| 4 — Contextual foundation | Five contextual tables, tenant templates/five-pair registry, kernel artifact equivalence, null/scope/FK/lifecycle and reactivation/admin guards. Separate Role-root commits then first-admin Membership; fixed seed admission denied in API, real provider adoption, v1 interrupted/no-write/conflict reruns and preserved actors/credentials. | +| 5 — API/BFF activation | New provider-subject feature/quota handoff before SQL, exact global descriptor and HTTP matrix, 255 sub bound, SDK/native bootstrap, actorless/tenantless real provider and wrong-subject/capacity/cancellation/late-result controls. Anonymous public behavior and ordinary 401/ADR-0071 stay. | +| 6 — Integrated qualification | Complete relevant suites and source-bound shard/discovery accounting, actual PostgreSQL/Keycloak/native/browser slice, required A/B CI without skips or relaxed names/ceilings, updated corpus and reviewable PR. No first-admin production/onboarding, full authorization or closure claim from seed proof. | + +`User_Aggregate_Has_No_TenantScoped_Columns` is currently Registered; +`Permission_Definitions_DeclareScope` awaits real backfill. The new classification +and global-isolation controls are planned, not yet registered/implemented. Step 1 +registers named owners; Steps 2/3/4/5 supply actual subjects and positive/dirty +controls. Existing Implemented rules retain status with explicit pending +extensions; this proposal does not alter catalogue counts or claim coverage. + +The final semantic review must independently assess SQL owner privileges, +authority installation/drift, digest/raw closure contract, input/feature/quota +handoff, generated manifest/kernel equality, staged seed recovery, derived first- +admin predicate and exact predecessor Amendments. Run fragment/file/status/ +structure/index/whitespace/private-reference checks after the **last** edit. +Static checks qualify only the proposal; no runtime proof is claimed here. + +### P03-1 revised proposal review round 1 (2026-10-25) + +**Reviewed source:** `6bff3fe0`. Two fresh read-only reviewers independently +inspect the revised package and current source: global SQL/authentication and +authority instruments (GPT-6 Astra, xhigh), and model/permissions/lifecycle/ +privacy (GPT-6.1 Sol, xhigh). Both approve within their stated scopes; neither +claims runtime proof or maintainer approval. + +The SQL review identifies two acceptance-carrier omissions. The current closed +GUC list must explicitly adopt the two identity announcements, and ADR-0053 +Amendment 11's authenticated AccountSite seam needs an Amendment for the exact +bootstrap caller. The revision above adds both obligations and the proposed +ADR-0053 text; Accepted predecessor text remains untouched. No other actionable +proposal contradiction is reproduced. Database/provider/application tests are +not run or inferred from this documentation review. + +### P03-1 revised proposal review round 2 and readiness (2026-10-25) + +**Reviewed source:** `26237b823a0bf72a1986dfffc849c6a28dd67355`. Two new +read-only reviewers inspect the complete revised approval surface independently: +authentication/global SQL/audit and source handoffs (GPT-6 Astra, xhigh), and +model/manifests/lifecycle/privacy and adoption carriers (GPT-6.1 Sol, xhigh). +Both approve within the Proposed documentation scope, with no actionable finding. +No reviewer edits files or claims implemented enforcement or maintainer consent. + +The authentication review also checks a possible attribution ambiguity against +ADR-0044 Amendment 6: aggregate `created_by = SystemActor` when no actor exists +does not substitute SystemActor for the NULL authenticated audit principal. +That concern is not a finding and does not change the selected contract. + +Parent validation at the reviewed source passes all 37 existing Python guard +controls and all five Release `CorpusConsistencyTests` cases, with zero skips. +The changed-document sweep resolves 884 relative file targets; both ADR statuses +parse as Proposed, and no temporary review report is referenced. ADR prose checks +exclude the documented table/link exceptions. Whole-tree fragment, roadmap +structure, regenerated-index and whitespace checks qualify the final record +after its last edit. These are documentation/corpus checks, not Identity SQL, +Keycloak, API, browser, concurrency or privacy-fulfillment qualification. + +The revised package is ready for **joint maintainer review**, not Accepted. +Both ADRs and all nineteen gates remain Proposed/Open as applicable. No runtime, +schema or provider configuration changes accompany this preparation. Acceptance +and the six implementation steps wait for the explicit approval requested before +new ADR implementation; after approval, Step 1 applies the actual dated +Amendments and authority reconciliation before dependent code. + +### P03-1 second maintainer review and revised package (2026-10-25) + +**Status: Proposed; joint ADR acceptance is still pending.** The maintainer +returns a second set of review findings rather than approving ADR-0072/0073. +The prior readiness entries describe their reviewed sources; their conclusions +do not qualify the integration gaps verified below. This entry replaces the +previous package as the current approval surface, without rewriting its history. + +**Accepted staging decision.** After the source-bound consumer analysis, the +maintainer explicitly selects P03-3 for new-user HTTP bootstrap and native BFF +entry. P03-1 retains global storage/common creation authority, central audit, +fixed seed adoption and route-independent existing-binding API admission. No +new POST, SDK operation or native no-session completion is activated here. +P03-3/G1/G6 must decide provider signup and durable creation budgets before +opening that surface; current rate-limit partitions do not bound durable rows. +This staging approval does not accept either ADR or authorize dependent code. + +#### Verified finding dispositions + +Three read-only source audits cover common persistence/audit, API/native seams, +and membership/seed contracts at `acd20764`. They inspect actual code and current +authorities. No provider/database state is changed and no runtime proof is claimed. + +| Review item | Disposition / concrete correction | +|---|---| +| Prepared owner, intent order and creation key | Valid. Ordinary audit declares before transaction and unresolved paths declare nothing. Standard 05 now names prepared global ownership, serialized recheck, typed central intent/reference handoff and the original owner's completion, following the existing prepared delivery precedent. No Identity-private audit writer. | +| Deferred guard failure at COMMIT | Valid current classification gap. Force pending constraints IMMEDIATE after final SQL, before commit admission; failure uses known precommit rollback. Do not add a broad SQLSTATE shortcut or reinterpret a lost physical COMMIT acknowledgement. Real guard-refusal/unknown-COMMIT controls remain Step 3 requirements. | +| Owner-read policy and permanent bindings | Valid wording/protection gap. Single policy role-qualified USING arms are not SELECT-only policies. Add explicit User DELETE/TRUNCATE refusal including owner execution; disclose the DDL trust limit. Audit already has its own mutation/TRUNCATE guards. | +| Ordinary pending sentinel refusal | Valid. Shipped WritePendingAsync lacks the direct guard claimed by the draft. Before admitting global RLS, add hard ordinary audit/transaction/EF mode refusals and a global-discriminator refusal in platform entry. Typed global intent/composer metadata is central, not handler supplied. | +| Route-dependent bootstrap, missing token and wrong method | Valid proposed integration gaps, now outside P03-1 activation. Existing public anonymity, AccountSite absent404/valid405, route-invariant resolution and endpoint/SDK union remain. P03-3 must explicitly supersede route invariance if its selected bootstrap design needs it. | +| Duplicate evidence and cross-module SQL carriers | Partly already explicit, but carrier incomplete. New global duplicate evidence must match exact subject/key/target/source/outcome; non-success durability never proves User absence or success. Name the bounded central witness-installer exception in ADR-0010/0044 and structural controls. Do not generalize the ordinary 23505 shortcut. | +| Audit matrix and profile slug | Valid. Use Resource/Operation/Class/Why so the existing parser reads the class; add literal identity.user.create MUST/security-event. Profile operation uses identity.membership_profile.set_seed_profile, matching the permission resource. | +| Phase custom-field permission | Valid remaining phase spelling. Align the future profile-value writer to identity.membership_profile.write; G9 still owns dynamic-value semantics. Other foundation declarations were already consistent. | +| Tenantless/native outcome and bootstrap status table | Valid missing transport contract; belongs to the newly selected P03-3 activation gate. Current complete ProviderIdentity/LoginCompletion and positive AccountSite publication remain. A committed identity without session needs a typed, truthful outcome before activation. | +| Yoga admin scope | Valid handoff omission, not a reason to change its provider claim. Preserve b001's org claim and NULL-org Tenant Admin Membership; seed SQL uses explicit declared target scope. Tenant-wide writes later require explicit orgless session reissue. The read hatch never widens writes. | +| Assignment addition wording | Valid drift. All additions recheck User admission, including an initially empty template; do not substitute a heuristic for current authority increase. | +| Tenant lock granularity / final-admin predicate | Valid serialization cost. Use shared tenant locking for profile/nonadmin/org mutations and exclusive for first-admin/admin eligibility/assignment/kernel changes, with actual-transition classification and no upgrade. Preserve the total eligible-admin invariant; future closure cannot silently strand it. | +| Production first-admin owner | Partially documented before; missing in phase result/proof. P03-9/G13 now explicitly owns admitted first-admin/provisioning, partial-setup recovery and controlled issuer rebind. Production onboarding waits for that owner; seed-backed UI can be qualified earlier. | +| Tenant-owned to global User reference | Existing same-module FK is not forbidden by the tenant-to-tenant composite rule. Add the third named canonical shape and tests; do not weaken ordinary composite references or add User FKs to audit actors. | +| Kernel two versus initial admin three | Intentional, not a contradiction. The two-pair kernel preserves administration; profile-write is an explicitly removable initial grant outside that minimum. Clarify this distinction in Standard 19 and seed upgrade behavior. | +| Standards precedence and adoption text | Valid adoption incompleteness. Standards 05/19 now provide precise replacement text while their active prefixes stay unchanged before approval. Distinguish stored templates from enabled assignments, scoped pair identities, initial v1 grants and later audited adoption. | +| G3 lifecycle and seed accounting | Valid missing delivery detail. Name the bounded Tenancy lifecycle contract in Step 4 and its live P03-2 consumer. Extend actual seed audit accounting; keep the four authentication personas, with extra proof subjects fixture-local. | +| Durable cardinality / lookup cost | Risks already disclosed, not new demonstrated exploits. HTTP staging removes immediate open allocation. Step 5 additionally qualifies uncached lookup latency, pool pressure, cancellation and uniform401 under store failure; no measured p95 or production capacity guarantee is claimed. | + +#### Current approval surface and predecessor Amendments + +Joint [ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md) and +[ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md) +remain Proposed. Their canonical contracts are the Proposed annexes in Standards +05/11/19, the Identity specification/matrices and Data Protection's classification +section. Standard 05 now owns the prepared-owner, audit/evidence, lock and exact +adoption text; other documents link rather than repeat that algorithm. + +The following complete Amendment drafts replace the prior package's drafts. +On actual joint acceptance, append each at its target's next available heading +and actual date. Do not reserve numbers, rewrite earlier bodies/metadata or +apply these to Accepted authorities before approval. + +| Target | Append-ready text / bounded instrument | +|---|---| +| ADR-0003 | ADR-0072 adds global self-identity as a seventh table class and its platform-scoped authority anchor. Standard 05 owns the exact FORCE-RLS policy arms, immutable binding guards, same-module tenant-to-global User reference and five confined owner functions. The ordinary tenant/org template and four login roles remain. | +| ADR-0010 | ADR-0072 admits the enumerated central IdentityCreationWitnessInstaller persistence contract: reciprocal User/central-audit creation guards and exact evidence reads over declared key/discriminator fields. Central infrastructure contains that fixed SQL without module entity/assembly imports. Identity migration invokes it without copied audit SQL. This is the only new structural SQL exception; business cross-module joins and a fifth application communication mechanism remain forbidden. | +| ADR-0017 | ADR-0073 defines Membership as one profile/assignment root and Role as a tenant-wide capability template. Organization grants apply only through an exact Organization Membership; template storage does not confer cross-branch authority or authoring. Tenant grants plus matching-org grants remain. Tenancy owns Organization lifecycle. | +| ADR-0033 | ADR-0072 extends central MUST creation and reconciliation to exact prepared global identity owners without resolved tenant context. Serialized lookup precedes intent; only absence opens the common audit frame and creation-reference handoff. Success shares User COMMIT. Known precommit refusal and unknown COMMIT remain distinct; non-success preserves captured attribution and fresh standalone timestamp. No Identity-owned audit writer or provider transaction is added. | +| ADR-0036 | ADR-0072 inserts quota-before-binding, route-independent existing-binding normalization before ordinary tenant reconciliation. No new HTTP endpoint, context writer or unresolved marker is admitted. ADR-0073's separately named PreContextIdentityAuthorizationReader is a short READ ONLY app-role candidate read, with no ITenantContext; its live rows/HostScope/claim-only evidence remain P03-2 proof. | +| ADR-0040 | ADR-0072 adds common global read/prepared-creation/seed/reconciliation owners with exact identity announcements, connection/generation capture and one-shot prepared completion. Tenant/global modes cannot join or retarget. ADR-0073 registers the planned ninth tenant setter PreContextIdentityAuthorizationReader, executed only in P03-2 with exact candidate tenant/org and physical READ ONLY. Identity GUCs are a separate census, never sentinel tenant announcements. | +| ADR-0044 | ADR-0072 narrowly extends §§1/2/3/5/9/10 with a second sentinel population, identity.user.create MUST/SecurityEvent, typed global attribution and two central writer seams. Ordinary pending/standalone/best-effort/tenant entry refuses it; platform entry rejects this identity discriminator. Global success requires reciprocal User/audit evidence and precommit constraint validation. For this population, 23505 alone proves no outcome: exact-key/source/subject/target/outcome evidence is required, and a fresh non-success row proves only its own durability. Fixed central witness SQL receives only the enumerated structural exception. Existing append-only/redaction/retention authority is unchanged. | +| ADR-0064 | ADR-0072 replaces required API wire user_id with verified-subject admission followed by existing-binding normalization. Credential enforcement recognizes the verified stage; the unchanged issuer/sub quota precedes binding SQL. Unknown/conflicting/Closed/unavailable bindings uniformly refuse401 without allocation. Route invariance, the closed GET/HEAD surface, public anonymity and AccountSite404/405 remain. P03-3 needs separate acceptance before new-user HTTP activation. | +| ADR-0065 | Navigation only: ADR-0072's global MUST identity creation receives no host-tenant mismatch allowance or suppression. The independently defended-host admission key and budget remain unchanged. | +| ADR-0066 | ADR-0072's input stage admits verified provider subjects before application binding. The broader population retains issuer/sub keys, numeric bounds, once-per-request debit, cleanup/fault ownership and non-reset behavior; the registry bounds neither permanent Users nor audit rows. | +| ADR-0070 | Navigation only: P03-1 preserves complete native identity, ID-token/AccountSite association and publication/refresh fences. Align opaque subject validation to the API's 255-character contract. New optional pre-session identity, bootstrap association and no-session completion remain unaccepted P03-3 changes. | +| ADR-0071 | Navigation only: ADR-0072 preserves the ordinary-read refusal table despite the additional binding-store uncertainty source. No automatic retry, refresh or identity-refusal witness follows. | + +ADR-0053's AccountSite seam receives no P03-1 extension; its future pre-session +caller waits for P03-3 acceptance together with ADR-0064/0070. Adopt Standard +05's exact replacement clauses and Standard 19's scope/default/manifest text, +reconcile Standards 01/04/07/10/11/18/21, architecture/CLAUDE/glossary/XML claims +and actual schema/method/guard censuses before their dependent code. Preserve +historical packet method counts. Existing Implemented tests retain status with +pending extensions; new controls are Registered only when actually catalogued. + +#### Revised six steps and required proofs + +| Step | Required closure evidence | +|---|---| +| 1 — Authority acceptance | Joint approval and the actual dated Amendments above; promote approved annexes, authority headers, exact adoption prose and named catalogue controls before code. G1 closes storage/common creation, G3 its foundation contract; transport/live/archive gates remain Open. | +| 2 — Classification | Complete real EF-property declarations and automatic per-module/coordinator model diff, inherited references and neutral-name missing controls. Fixed diagnostics plus positive/canary sink proof precede Identity writers. | +| 3 — Global persistence/audit | Sixth chain/authority installer; common prepared global owner/reference/intent lifecycle, ordinary seam refusals, single-policy arms and permanent-binding DELETE/TRUNCATE guards. Real app-role/owner-body/privilege/caller controls; benign race has one intent, precommit refusal differs from lost COMMIT, mismatched/foreign duplicate evidence fails. No mocked census can close this step. | +| 4 — Contextual foundation/seed | Five contextual tables, exact finite registry/kernel artifact, reference/lifecycle/scope guards and shared/exclusive fresh-lock proof with real held-lock competing commits. Deliver the bounded Tenancy lifecycle contract. Preserve all four authentication personas and target-derived Yoga seed scope; extra subjects stay fixture-local. Staged Role/first-admin/learner acts, actual extended audit accounting, interrupted/no-write/conflict/upgrade reruns and seed denial in API. | +| 5 — Existing-session admission | Stock verified-subject feature, credential gate, unchanged subject quota then global READ ONLY existing binding before route-independent resolver. Native complete-identity/AccountSite flow and current operation census remain; align sub255. Qualify actual provider/app-role lookup, plan/latency/pool/cancellation/store-fault paths. No new-user POST/BFF caller. | +| 6 — Complete qualification | Relevant full suites, corpus and source-bound shard/discovery accounting; real PostgreSQL/Keycloak/native existing-session slice and complementary A/B CI with zero skips and unchanged required names/ceilings. Update docs and prepare the reviewable PR without claiming later HTTP/onboarding/closure delivery. | + +P03-2 owns live candidate reads, permission enforcement and explicit later grant +adoption. P03-3 owns new-user transport, registration/capacity decisions and +session/no-session continuation. P03-9 owns production first-admin, issuer rebind +and exceptional recovery; P03-10 owns closure/retained-copy fulfillment. Neither +schema nor seed evidence closes those later flows. Each implementation step still +receives a commit and two new independent review rounds with verified fixes. + +### P03-1 second revision review round 1 (2026-10-25) + +**Reviewed source:** `c63ca622`. Two fresh read-only reviewers independently +trace the revised proposal against current source: execution/audit/API contracts +(GPT-6 Astra, xhigh) and membership/manifests/seed/lifecycle contracts +(GPT-6.1 Sol, xhigh). No runtime proof is claimed. + +The execution slice approves with a minor internal-result wording correction: +HTTP401 belongs only to the ordinary API column; the internal creation owner +returns typed refusal and P03-3 owns its HTTP mapping. The model slice requests +changes for one Major contradiction: the unqualified shared/exclusive admin +assertion also forbids initial Role roots before the first Membership. + +Standard 05 now gives finite first Role creation its explicit shared-lock +exception, requiring exact admitted initial manifest/source and no historical +Membership. Existing Role edits, upgrades and repairs cannot take that path; +first-admin creation takes exclusive mode and every Membership/child mutation +retains the total invariant. ADR-0072's internal result wording is corrected. +No other actionable finding is reported within the reviewers' assigned slices. +Parent validation at the reviewed source passes 37 Python documentation controls +and 20 compiled CorpusConsistencyTests/AuditCoverageTests cases, zero skipped. +These checks do not qualify the proposed Identity runtime or database guards. + +### P03-1 second revision review round 2 and approval readiness (2026-10-25) + +**Reviewed source:** `cd8150c9`. Two new read-only reviewers independently +inspect execution/audit/API boundaries (GPT-6 Astra, xhigh) and model/lifecycle/ +seed contracts (GPT-6.1 Sol, xhigh). Both approve within their assigned Proposed +design/source-review scopes, with no actionable findings. The model reviewer +explicitly falsifies the first Role-before-admin path and direct-write/lock +contracts; the execution reviewer traces current coordinators, Npgsql outcome, +store, credential and native handoffs. These verdicts do not establish runtime +confinement or accept either ADR. + +The earlier round's Role-initialization contradiction and internal-result +wording are resolved at the reviewed source. Parent controls pass 37 existing +Python documentation cases and 20 compiled CorpusConsistencyTests/ +AuditCoverageTests cases, with zero skips. Local file/fragment, inactive-annex, +ADR-status, whitespace and private-review-reference checks are separate mechanical +evidence, not proof of future Identity execution. Final text reflow/status and +this append-only receipt require regenerated indexes and whole-tree lint after +the last edit. + +The current second-maintainer package is ready for joint review of ADR-0072/0073. +Only HTTP/new-user BFF staging to P03-3 is already approved. Both ADRs remain +Proposed, their acceptance-dependent gates remain Open, and no schema/runtime/ +provider change has occurred. Steps 3/4 still require real owner-function/body/ +privilege/caller and held-lock competing-commit proofs; metadata scans cannot +close them. No new approval is inferred from a review verdict or the staging +answer. Acceptance must be the first implementation step before dependent code. + +### P03-1 joint acceptance and Step 1 (2026-10-25) + +The maintainer explicitly approves revised ADR-0072, ADR-0073 and the complete +six-step second-maintainer package after `06b36199`. This is joint acceptance, +not an inference from the earlier review verdicts or HTTP-staging answer. +The approved P03-3 HTTP/new-user BFF boundary remains: P03-1 adds no new route. + +Step 1 adopts the named authority before dependent code. Both ADR statuses +become Accepted; the decision index moves their rows to Active. Actual dated +Amendments append to ADR-0003/0010/0017/0033/0036/0040/0044/0064/0065/0066/0070/ +0071, without changing predecessor bodies or metadata. Standards adopt their +exact canonical replacements and register proof owners; architecture, glossary +and module contracts distinguish approved obligations from runtime capability. +No runtime grant, Identity table, provider mutation or live authorization is +claimed by this acceptance commit. + +G1/G3/G19 and foundation portions of G2/G4/G5/G7/G16 are decided to the scope +named in the register. Invitation acceptance remains G8/Open; this foundation +adds no Invitation table or ADR-0042 exception. Candidate-reader execution, +new-user HTTP/native transport, production first-admin, controlled issuer rebind +and closure remain their named later gates. Current deny-all live membership, +complete native identity and AccountSite operation union persist until their +respective qualified implementation steps. + +The six approved steps retain the reviewed order and two new independent review +rounds per committed step. Step 1's authority diff receives both rounds before +Step 2 adds classification code. Steps 3/4 cannot close on schema metadata alone: +actual function/body/owner/privilege/caller controls, real held-lock competing +commits, exact duplicate/outcome evidence and first/final-admin behavior remain +mandatory. Lookup latency/pool/cancellation qualification belongs to Step 5; +full source-bound qualification and the reviewable PR belong to Step 6. + +Step 1 parent validation passes all 37 existing Python documentation controls and +20 compiled corpus/audit-matrix controls, with zero skips. Both new ADRs parse +Accepted. A byte-prefix comparison proves all twelve predecessor bodies and +metadata are unchanged; only the new dated entries append. The changed-file +sweep resolves 2,705 relative file targets and contains Markdown only. Whole-tree +fragment/roadmap/index and whitespace checks run after the last edit. Registered +Identity obligations are not reported as implemented by those checks. The +acceptance commit is followed by two fresh independent Step 1 review rounds. + +### P03-1 Step 1 review round 1 (2026-10-25) + +**Reviewed source:** `e6272082`. Two fresh read-only reviewers inspect authority +adoption (GPT-6 Astra, xhigh) and corpus/model carriers (GPT-6.1 Sol, xhigh). +Both request documentation corrections; neither claims runtime qualification. + +Both verify Architecture 31 incorrectly infers User absence from a non-success +row. The authority reviewer also verifies stale unmodified-audit-policy and sole +sentinel-population claims, plus Audit module status counting five rather than +six existing methods. These mutable carriers now distinguish current schema, +the accepted pending global extension and exact non-success evidence. A parent +sibling sweep also corrects Domain Model's provider-sub-as-actor, global-profile/ +custom-field and audit-policy shorthand to the accepted canonical contracts. +No Accepted ADR body changes in this correction. + +The corpus reviewer considers the ADR-0073 G8 shorthand and reproduces no separate +finding: its later invitation paragraph and the authoritative register expressly +leave G8 Open. Do not rewrite the now-Accepted body merely to restyle that +boundary. Both reviewers confirm predecessor-byte preservation, legitimate joint +approval, planned control statuses and the unchanged P03-3 transport boundary. + +### P03-1 Step 1 review round 2 and closeout (2026-10-25) + +**Reviewed source:** `7ded2585`. Two new read-only reviewers independently assess +authority/canonical execution contracts (GPT-6 Astra, xhigh) and corpus/model/ +proof-state carriers (GPT-6.1 Sol, xhigh). Both approve within Step 1's scope, +with no actionable findings. They verify the earlier non-success/sentinel/policy/ +method-count corrections, Domain Model alignment, predecessor-byte preservation, +registered proof owners, finite manifests and P03-3 transport staging. + +Step 1 is complete. Acceptance/canonical adoption precedes all dependent code; +no runtime or schema qualification is inferred. Parent fragment, roadmap/index +and whitespace checks pass; current compiled corpus/audit-matrix controls pass +20 cases with zero skips. Step 2 proceeds automatically under the accepted plan: +explicit mapped-property declarations, common classification validation and a +neutral-name missing-declaration control before Identity writers. + +### P03-1 Step 2 implementation and local qualification (2026-10-25) + +Step 2 adds explicit personal-data category/purpose declarations and a shared EF +model-finalizing validator. The actual production census covers five contexts +(including the deliberately empty Platform context), 19 mapped entities and 201 +scalar properties: Tenancy 83, Customization 39, Audit 34 and Education 45. +Inherited actor/audit fields and shadow properties participate. Each module owns +its semantic declarations; no field-name heuristic supplies a default category. +Classification does not itself authorize disclosure, redact snapshots, establish +consent or change retention. SQL-only stores retain their separate inventory. + +The canonical mapped-property control is now Implemented in +`DataProtectionConventionTests`. Its eight methods produce eleven cases, +including a neutral shadow property added after normal production customization: +missing classification prevents model use, and the same property with an explicit +declaration succeeds. Invalid categories, blank/excessive purposes, conflicting +declarations and misspelled unmapped names refuse without values in diagnostics. +A relational comparison with all four existing migration snapshots is empty; this +step adds no schema, migration, Identity writer or authentication change. + +Release build passes with zero warnings/errors. Local qualification passes 2,692 +Unit cases, five Contract cases and 153 relevant real-PostgreSQL integration +cases, all with zero skips. The complete Architecture run executes 551 cases: +545 pass and six fail in existing corpus/inventory/module-matrix accounting. +The corrections preserve exact census checks: include the accepted Identity +module specification, name the implemented test owner in the catalogue's parsed +Status, and place pending global audit linkage under the existing audit custody +boundary rather than inventing another physical store. Rebuilt focused +Architecture qualification passes all 104 affected and classification cases, +with zero skips. The first complete run remains recorded as failed; its six +failures are not described as a green complete rerun. + +Changed C# formatting verification passes. Documentation, generated-index and +whitespace checks run after this entry. The implementation commit precedes two +fresh independent review rounds; Step 2 is not closed by these local results. + +### P03-1 Step 2 review round 1 (2026-10-25) + +**Reviewed source:** `3261114c`. Two fresh read-only reviewers independently +inspect the common validator/model boundary (GPT-6 Astra, xhigh) and module +semantics/corpus (GPT-6.1 Sol, xhigh). The first approves without actionable +findings and independently passes all eleven classification cases with zero +skips. The second verifies one Minor documentation drift: the Identity spec +and G19 status still describe the current classification control as pending. +Those mutable statuses now distinguish the implemented current-model census +from pending Identity mappings and writer diagnostic proofs. No Accepted ADR +body changes. + +Both verify explicit None purposes against actual institution/configuration/ +curriculum semantics, conservative personal/reference declarations, value-free +diagnostics and actual snapshot/model relational comparison. Complex-leaf +recursion is structurally reviewed, not claimed as a separate production complex +property proof: no current production complex mapping exists. No verified runtime +finding remains within these review scopes. A second fresh review round follows +the correction commit. + +### P03-1 Step 2 review round 2 and closeout (2026-10-25) + +**Reviewed source:** `eccf2dff`. Two new read-only reviewers independently review +the model/finalization boundary (GPT-6 Astra, xhigh) and semantic declarations/ +corpus (GPT-6.1 Sol, xhigh). Both approve within Step 2's scope, without actionable +findings. Each independently passes the eleven focused Release classification +cases with zero skips; the census and all four relational comparisons agree. +They verify the earlier mutable-status correction and leave Accepted bodies +unchanged. Their focused proof does not claim a new full-suite/provider run. + +Step 2 is complete after both fresh review rounds. Explicit classification and +the missing-declaration counterexample precede the first Identity model/writer. +Steps 3/4 must add their actual properties to this complete census and retain +separate snapshot/diagnostic controls. Step 3 now proceeds automatically: global +User/authority persistence, the prepared common owner and central creation/ +reconciliation seams, with real app-role/function/outcome proofs before closeout. +No new HTTP or native new-user flow is activated. + +### P03-1 Step 3 global storage and common audit implementation (2026-10-26) + +Step 3 implements the internal global foundation under ADR-0072/0073. One new +Identity migration chain creates User and the deployment authority singleton; +the applied population is 44 data tables plus six history tables, seven table +classes and three Identity SECURITY DEFINER functions. Five contextual tables +and two Membership owner functions remain Step 4. The 17 global mapped scalars +join the complete classification census: six contexts, 21 entities, 218 scalars. +No unused email mirror or global profile/custom-field storage is added. + +The admitted internal source qualifies the fixed authority/issuer pair, opens a +fresh global app-role transaction, announces only its immutable subject scope, +locks/rechecks and returns an existing binding without mutation intent. Only +serialized absence enters the common typed audit frame. The centrally minted +creation reference binds target, original audit key, actual connection, +transaction and generation; handler construction remains deferred. The existing +common completion path writes the User and MUST audit together, validates all +deferred constraints before commit admission and retains known rollback versus +physical COMMIT uncertainty. Global and ordinary owners cannot join or retarget. +Exact context/connection/transaction capture admission precedes snapshot reads. +A non-allocating scoped enrollment reader preserves the lazy application-source +boundary for ordinary/platform audit entry. + +PostgresAuditStore remains the sole audit INSERT owner, with eight closed seams. +The central migration installer owns the reciprocal/evidence SQL; Identity copies +no audit SQL. Actual applied body/signature/return/owner/ACL/caller inspection +compares the compiled migration contract, including three global definers and +their exact trigger callers. Committed disposable faults independently widen +RLS/function results, grant PUBLIC execution, remove callers/immutability or +introduce an unrelated definer; clean twins establish the effective boundaries. +Ordinary writers refuse global enrollment even before an intent exists. + +A dedicated deployment child installs or verifies the configured authority on +the migration connection; it never repairs/rebinds. Make's explicit order applies +Audit before Identity, passes the credential only to no-build deployment children +and rejects partial authority configuration before migration writes. Runtime +qualification is read-only and installation is not registered in API DI. API +composition denies seed adoption; the ordinary seed/demo handoff remains Step 4, +existing-binding HTTP activation Step 5 and new-user HTTP/native entry P03-3. + +Local Release qualification passes 2,727 Unit cases with zero skips. The affected +Architecture run passes 228 cases; after canonical status/model-name reconciliation, +114 focused corpus/model/owner cases also pass. The first affected run's five +failures identify assertion-overload, nested/generic IL-inspection and mutable +catalogue/matrix bookkeeping; exact controls are corrected without weakening +closed sets. The asynchronous inventory now consumes every mapped module's +compiled migration chain, explicitly classifying global synchronous stores. + +The first global integration run has 30 passes and 16 failures before business +execution: the test provider omits the real cache needed by AuditConfigService. +The corrected fixture registers production InMemoryCacheService and propagates +early race-participant failures instead of hiding them behind a timeout. Rebuilt +qualification passes all 49 cases with zero skips: 23 schema/control cases, +16 production-service/provider/evidence cases, eight global unit-of-work cases, +one actual deployment-child case and the complete WITH CHECK proof census. The +other 303 requested schema/audit/rollback regressions pass; their earlier sole +census failure passes in that rebuilt global run. Thus all 352 distinct requested +integration cases pass. Owned real Keycloak/HTTPS evidence establishes signed +seed subject/actor and authenticated readback; no actorless/new-user transport is +claimed. Original failed TRX receipts remain separate from successful retries. + +Final exact-evidence read-only hardening, full-solution/Contract/format/document +checks and the complete Architecture run are recorded with their actual results +below. No hosted source-bound qualification or step closeout is inferred here. +The implementation commit precedes both fresh independent review rounds. + +### P03-1 Step 3 final local pre-review controls (2026-10-26) + +The clean exact-evidence transaction now establishes physical READ ONLY before +announcing the captured subject. The existing native duplicate case instruments +its owned evidence function: production reconciliation sees read-only mode, a +direct writable control refuses with SQLSTATE 25006, and exact read-only plus +fresh-creation controls remain successful. All four evidence cases pass again, +zero skipped; no production function/policy or test-count change follows. + +The complete Release solution builds with zero warnings/errors. The final Unit +run passes all 2,727 cases, zero skips, including sixteen issuer-registration +cases aligned with the existing API address grammar. Contract qualification +passes five cases, zero skips. Post-promotion corpus/model/owner qualification +passes 114 Architecture cases; the earlier broader affected set passes 228. +The implemented catalogue population is 241 rules (137 in Architecture), with +297 Architecture method declarations. User's global-only canonical rule now has +its actual model owner; contextual controls remain Registered. These counts do +not substitute for the complete Architecture run, which follows the commit. + +The scoped formatter, document/index and whitespace checks run after the final +edit. The default-deny seed capability, two-global-table/three-definer staged +population and P03-3 HTTP boundary remain explicit. No Accepted ADR body changes, +new erasure authority, migration credential in runtime, or hosted/PR qualification +is claimed. Both fresh independent review rounds remain required before Step 4. + +### P03-1 Step 3 retained-subject pre-commit correction (2026-10-26) + +The unshipped initial Identity migration and its model/snapshot now match the +Accepted retained-subject lifecycle: Closing permits a NULL subject; a retained +subject remains bounded and nonempty. Active requires a subject and Closed +requires NULL. The applied PostgreSQL CHECK is evaluated over all fifteen +status/NULL/length controls, without introducing a lifecycle writer or widening +UPDATE grants. All 24 schema/control cases pass with zero skips; the three +global model/snapshot controls also pass. The distinct requested integration +population is now 353 successful cases, including this additional CHECK proof. +The prior failed runs and earlier 352-case successful population remain history. + +### P03-1 Step 3 existing-adoption scope correction (2026-10-26) + +Pre-commit inspection finds that a no-write seed adoption of an existing binding +disposes an unresolved prepared frame, poisoning its otherwise successful scope. +The owner now completes that no-intent transaction after constraint validation. +The new real app-role control also exposes a second-generation context enrollment +refusal; the confined binding lookup explicitly enrolls its scoped context in +the current owner before reading. It never repairs a detached mutation context: +the existing pre-snapshot detached-context refusal remains effective. + +Rebuilt production-consumer qualification passes all seventeen cases with zero +skips, including two repeated existing adoptions and a subsequent tenant frame +in the same scope. User and success-audit counts remain one each, and repeat +adoptions declare no intent. The first control run (sixteen passes, one failure) +is retained separately. This adds one distinct integration proof, bringing the +requested successful population to 354. Formatting, final build and affected +owner/model controls run again before the implementation commit. + +Final scoped formatting passes. The complete Release solution builds with zero +warnings/errors; all 2,727 Unit cases and seven focused owner/model Architecture +cases pass again, zero skipped. The complete Architecture run and both fresh +review rounds follow the implementation commit; neither is claimed complete by +these focused results. + +### P03-1 Step 3 review round 1 and corrections (2026-10-26) + +**Reviewed source:** `e3f56cb2`. Three fresh read-only reviewers independently +inspect the common owner/audit boundary (GPT-6 Astra, xhigh), global schema and +owner-function privileges (GPT-6.1 Sol, xhigh), and scoped consumers/deployment/ +corpus (GPT-6.1 Sol, xhigh). The schema reviewer approves its assigned scope. +The other reviewers identify three verified runtime issues and one mutable +documentation gap; no runtime test is attributed to their initial static review. + +The binding reader no longer eagerly constructs creation-only scoped +coordinators before tenant resolution. Common scoped factories defer them until +admitted creation, and the binding service checks the live context accessor. +Owner cleanup is awaited without replacing a primary failure or cancellation; +cleanup failure on a normal return becomes a bounded storage refusal and emits +a fixed diagnostic without exception payload. The pending global audit command +explicitly uses the ten-second command limit; independent reconciliation keeps +its separate budget. Mutable Standard 05/issuer-environment descriptions now +match the implemented owners, installer and ordinary writer refusals. + +The complete Architecture baseline is interrupted after four verified closed- +census failures; it is not a complete or passing run. Exact tests now include +the extracted private transaction opener, the two guarded global coordinator +entries and the named physical completion/failure owners. Extra-call/delegate +and removed-guard controls remain, including removed-commit controls for all four +new physical commit owners. No job/delivery bypass or broad class exemption is +introduced. The failed/interrupted log remains separate from requalification. + +The corrected Release solution builds with zero warnings/errors. All 25 native +global-consumer cases pass, zero skips: they include actual pre-context lookup +followed by resolved-context MediatR business/MUST audit, joined cleanup failures +with primary exception/cancellation preservation and value-free diagnostics, +and an observed sleeping audit INSERT under both deadline and caller cancellation. +Each stalled-write refusal has a successful clean twin and independent failed +reconciliation. The eight additional cases bring the distinct requested native +population to 362; this is not a complete integration-suite claim. + +Formatting, Unit and focused corpus/owner checks run before the correction +commit. The complete Architecture rerun and a second fresh independent review +round follow that commit. Step 3 remains open until those controls close. + +Final R1 pre-commit controls pass: scoped formatting, the complete Release build +with zero warnings/errors, 2,727 Unit cases and 147 focused Architecture cases, +all with zero skips. Documentation/index checks and whitespace checks also pass. +The focused set does not claim the interrupted closed-census controls passed; +their corrected execution remains part of the complete rerun below. + +### P03-1 Step 4 ordered-lock timing proposal (2026-10-26) + +[ADR-0074](../decisions/0074-membership-admission-under-ordered-locks.md) proposes +a bounded read-timing replacement before contextual writers. Step 4 feasibility +inspection exposes a literal conflict between the trigger-only User reader and +the complete pre-mutation lock plan for a parent with future administrator +assignments. A separate read-only analysis confirms the conflict and +the continuous-User-fence safety argument. This is design analysis, not runtime +qualification; no contextual table/function/writer is implemented. + +The proposed delta retains User-before-tenant lock order, strongest complete +plans, fresh trigger admission, five definers and the existing grant boundary. +Only the requirement that the eligibility read itself precedes tenant acquisition +changes. A closed target can occupy a tenant fence until its check refuses. +Dependent code waits for the maintainer's explicit approval; Step 3 is unaffected. + +On approval, append these dated Amendments at the next available heading and +actual acceptance date, preserving Accepted bodies/status/dates: + +| Carrier | Append-ready bounded text | +|---|---| +| ADR-0072 | ADR-0074 narrowly replaces the delegated Membership eligibility-read timing: an admitted complete plan acquires the actual target's exclusive User fence before tenant fences and retains it through mutation/completion; the actual admission trigger may freshly verify eligibility after those fences are preheld. No missing User key is first acquired beneath tenant authority. The global subject owner, five-function confinement and absence of a generic User reader remain. | +| ADR-0073 | ADR-0074 separates fence acquisition from eligibility-read timing for complete Membership/child plans. User-before-tenant order, actual-row classification, strongest pre-mutation tenant mode, no upgrades and total eligible-admin invariants remain. The actual mutation trigger verifies the preheld target User fence and freshly refuses unknown/nonadmitting targets before mutation. No new scope, grant, Role variant or live endpoint follows. | + +Standard 05's `fn_identity_membership_admission_guard()` row replaces its final +timing sentence with: “Requires the actual target's exclusive User fence already +held when tenant authority is held; freshly verifies eligibility before permitting +mutation. A missing User key beneath tenant authority refuses; no User fields are +returned.” Its lock section adds that complete plans may prehold both ordered +families before the fresh actual-trigger check, while retaining continuous +transaction ownership. Add ADR-0074 to the derivation header only on acceptance. +The canonical algorithm stays in Standard 05; other carriers keep references. + +The existing Registered ordered-lock rule keeps that status until Step 4 delivers +actual app-role second-admin/shared-learner, held-lock closure/creation, missing- +fence, no-upgrade, isolation, timeout and rollback controls. No new Implemented +count or policy activation follows from this proposal. Independent proposal +reviews and mechanical checks are recorded below when actually completed. + +### ADR-0074 proposal review round 1 (2026-10-26) + +Two fresh read-only reviewers independently inspect the proposed four-document +package based on `111ca113`: ordered-lock safety (GPT-6 Astra, xhigh) and corpus/ +authority/proof ownership (GPT-6.1 Sol, xhigh). Both approve for maintainer +consideration without actionable findings. They verify the conflicting canonical +clauses, the continuous-fence argument, actual unimplemented contextual boundary +and PostgreSQL 18 locking/snapshot documentation. No build, suite or contextual +runtime proof is attributed to these reviews. The existing rule remains Registered; +no dependent code or Accepted authority changes. A second fresh proposal round +follows this documentation commit before requesting the maintainer's decision. + +### P03-1 Step 3 review round 2 and local closeout (2026-10-26) + +**Reviewed source:** `111ca113`, whole Step 3 diff from `e4a8a0a1`. Two new +read-only reviewers inspect the common owner/audit/security boundary (GPT-6 Astra, +xhigh) and foundation/schema/DI/deployment/corpus (GPT-6.1 Sol, xhigh). Both +approve their assigned runtime scopes without further actionable runtime +findings. The latter identifies two stale mutable descriptions: repository README +and Architecture 03 still call Identity marker-only. They now point to the +implemented global foundation and the module specification's remaining scope. +These reviews inspect real controls, but execute no suites; qualification below +is the parent's evidence. + +The complete Architecture rerun executes 559 cases: 558 pass, one fails, zero +skipped. The four prior job/delivery census failures are green. The remaining +failure correctly detects that IUserBindingStore is not counted by the existing +typed aggregate-port convention. It now derives from the existing +`IAggregateWriteStore` instead of adding an exemption. Add remains +its inherited creation operation; an explicit default UpdateAsync refuses with +a fixed diagnostic before touching a payload or persistence. No User mutation +grant or lifecycle writer is introduced. The foundation reviewer separately +checks this exact follow-up diff and its production-store/generic-interface +control, approving without additional findings. + +The final Release solution builds with zero warnings/errors. All 2,728 Unit +cases pass, including that additional refusal control. All 65 affected +Architecture cases pass, including the formerly failing aggregate census; +the real production creation/read/MUST-audit integration case passes again. +All have zero skips. The complete run remains recorded as 558/559 followed by +this narrow correction/requalification; it is not relabelled a complete green +rerun on a different tree. Earlier 362 distinct native cases and five Contract +cases remain their recorded results. Final source-bound full/shard/native A/B +qualification belongs to Step 6 after all implementation steps. + +Step 3 is locally complete after both fresh review rounds and verified fixes. +Step 4's contextual code has not started: the separately Proposed ADR-0074 +timing delta requires the maintainer's decision first. Global owners, storage and +audit need no reversal; no new HTTP/native-user activation or production +membership/closure authority is claimed. Scoped formatting and document/index/ +relative-link/whitespace checks run before the closeout commit. + +### ADR-0074 proposal review round 2 and readiness (2026-10-26) + +**Reviewed proposal:** `1c3fb969`. Two new read-only reviewers independently +inspect safety/viability (GPT-6 Astra, xhigh) and corpus/acceptance/proof ownership +(GPT-6.1 Sol, xhigh). Both approve for maintainer consideration without actionable +findings. They independently check the exact contradictory clauses and the +second-administrator case, PostgreSQL advisory-lock/snapshot primitives, actual +unimplemented contextual source, and the bounded acceptance instruments. +No edit, build, suite or contextual runtime qualification is attributed to them. + +The proposal is review-ready, remains Proposed and changes no active lock rule, +function/grant count, Accepted body or dependent runtime. The existing six-step +plan receives only its explicit Step 4 timing delta on approval. The actual +app-role race/negative/timeout/snapshot controls remain implementation closure +conditions, not evidence supplied by documentation review. + +### ADR-0074 maintainer review correction and acceptance (2026-10-26) + +The maintainer authorizes acceptance and continued implementation after verifying +and fixing the supplied review findings, without another approval request. Two +read-only verifiers (GPT-6 Astra / GPT-6.1 Sol, xhigh) independently check the +findings against `c4569ad5`, actual global DDL and canonical contracts. The +substantive gaps are valid; no additional product/authority choice is required. +Earlier scoped proposal verdicts remain history rather than a claim that this +later review contains no actionable findings. + +| Verified finding | Disposition | +|---|---| +| Missing ownership mechanism and limits | Standard 05 now names the exact current-PID/database/advisory/granted/exclusive/single-bigint observation and canonical signed key. The trigger uses no acquisition or try-lock probe. Historical order, transaction kind/lifetime and CLR admission are separate closed caller/source/receipt and completion controls. | +| Session-only SQL rejection | Not adopted as a claim: the view cannot distinguish it. An actual session hold satisfies the same predicate. Source/caller controls reject session APIs; dedicated observations expose the limit and real transaction-end tests prove lifetime. | +| Broad “Membership writers” and inconsistent optional checks | User fences are required for creation, Suspended-to-Active and all assignment additions. Fresh target checking is mandatory; profile-only/removal paths take no automatic User fence. “Before data-mutating statements” replaces ambiguous SQL-dispatch wording. | +| Fault versus target refusal | Fixed internal plan faults use the existing identity-free lock-refusal `fault` signal; expected unknown/nonadmitting target refusals do not invent acquisition faults. Both preserve the same fixed outward refusal. | +| Impossible closure competitor | Disposable fixtures explicitly accommodate both unconditional `tg_users_no_update` and owner CHECK policy, perform the fixed owner transition under User→affected-exclusive-Tenant order, restore in `finally`, and verify restored body/ACL/policy/trigger plus owner UPDATE denial. No production closure writer/grant is added. | +| First-admin example and confined alternative | The admitted `CreateFirstSeedAdminMembership` is explicit; second-admin subjects remain fixture-local. Candidate-only `fn_identity_admin_admission_state` cannot become an arbitrary new-target reader. | +| Exclusive mode, snapshots, keys and costs | Preserve existing per-User serialization rather than claiming shared locks cannot exclude closure. Cite VOLATILE query snapshots. Step 4 requires User/Tenant C#/SQL vectors, foreign/wrong/shared/namespace observations, profile/removal negatives and actual trigger-path p95/query/pool/contention qualification. | +| Acceptance carriers and instruments | ADR-0072/0073 receive navigation Amendments; their bodies/status/dates stay intact. ADR-0074 owns the bounded canonical Standard 05 timing change. Headers, index, phase Status/G3/P03-10, signals/security/spec and catalogue Source/Asserts are reconciled. Registered remains Registered. | + +A bounded mechanism probe uses the exact fixture pin `postgres:18.4-alpine`, +image digest `sha256:9a8afca54e7861fd90fab5fdf4c42477a6b1cb7d293595148e674e0a3181de15`, +actual version `180004`, with `learnstack_app` verified NOSUPERUSER/NOBYPASSRLS. +All fourteen checked predicate observations pass: positive/negative bigint keys, +wrong/shared-only/two-integer exclusions, foreign backend without acquisition, +transaction commit/rollback release, and the session hold surviving transaction +end. The owned socket-only/no-network container and foreign worker are cleaned +and joined; preexisting containers remain untouched. This is a mechanism probe, +not contextual schema/guard/race/performance qualification. Its source baseline +is `c4569ad51e8b52a2f89ce502abf20c9f5b10299f`; contextual code does not exist yet. + +ADR-0074 is Accepted on 2026-10-26 under that conditional authority. Its timing +delta is incorporated before dependent Step 4 code. The original six steps and +two fresh independent runtime review rounds per step remain: Step 4 implements +the five contextual tables, finite manifests, actual guards/commands and owned +provider-witness seed handoff. Step 5 activates existing-session binding; Step 6 +owns complete source-bound/shard/native A/B qualification and PR preparation. +HTTP/new-user BFF entry remains P03-3; production first-admin/rebind remains +P03-9 and closure fulfillment remains P03-10. + +Two independent read-only reviewers (GPT-6 Astra / GPT-6.1 Sol, xhigh) inspect +the complete eleven-file acceptance diff and approve without actionable findings. +They verify the precise predicate, its limits, narrowed admission scope, fixture +prerequisites/restoration, append-only navigation Amendments and complete carriers. +Neither review runs contextual tests or independently reruns the mechanism probe. +The five existing CorpusConsistencyTests pass in Release with zero skips; +document/index/fragment checks resolve 2,556 links, the seven ADR-status parser +tests pass, and whitespace, added relative targets and private-reference scans +are clean. No prior proposal/readiness/review record is rewritten and no +contextual control is promoted on the strength of this document or probe. + +### P03-1 Step 4 — Contextual foundation and owned seed (2026-10-26) + +**Authority:** jointly Accepted ADR-0072/0073 and ADR-0074's accepted timing +correction. This implements the contextual portion of the approved six-step +package; independent review rounds follow the implementation commit. No HTTP, +new-user BFF activation, live permission enforcement or closure writer is added. + +Five contextual tables join the existing Identity migration chain: Membership, +its Profile/Assignments, Role and grants. The applied census is 55 tables, six +chains, seven classes, eight central audit seams and exactly five Identity +SECURITY DEFINER functions. Exact applied bodies/owner/ACL/triggers and planted +widening controls include the new pair. The model census covers six contexts, +26 entities and 254 scalar properties, all explicitly classified. Compiled v1 +owns definitions, templates, kernel, fingerprints and generated SQL values. +Module-local identifiers cross Contracts as Guid; shared User/Tenant/Organization +identifiers remain typed. + +The complete plan derives from actual Role/parent facts, acquires ordered User +then strongest tenant fences, rechecks fresh state, and mutates only afterward. +Actual admission triggers observe their target fence and User eligibility; +last-admin, lifecycle, mirror, capability and complete-graph guards validate +before the common owner commits. The closed graph-save adapter temporarily +suspends automatic EF savepoints only for that save and restores the original +flag in finally. Any save failure poisons the whole unit. This preserves strict +same-top-transaction initial-Role evidence through graph preflight without a +released-subtransaction-lock heuristic. Ordinary/global saves retain their default; +success, real constraint refusal and cancellation prove restoration and rollback. +No general savepoint switch or partial repair path is admitted. + +The argument-free data Seeder remains the first application convergence pass. +The shared realm owner then reconciles/verifies, reads its final authenticated +provider facts, and awaits a second owned child while retaining the realm lock. +Only a versioned, bounded private stdin envelope carries the exact issuer and +four actor/opaque-subject pairs; no Admin credential, argv subject or public +result projection is added. The child qualifies the explicit selected authority, +adopts four bindings, then separately commits sixteen Role acts, two first-admin +and two learner Membership acts, and four profile acts. There are 28 additional +successful identity audit rows. Predispatch exact postconditions skip complete +acts; interrupted reruns create missing acts only. Edited, revoked, suspended or +upgraded authority refuses without repair. Yoga admin remains NULL-org in the +application while its provider branch claim remains untouched; Yoga learner is +in the default studio. The environment example supplies an explicit local +stable authority/issuer pair; existing private files must add the pair and must +match any installed registration. + +Qualification before implementation review: + +- Release solution builds with zero warnings/errors; all 2,748 Unit cases pass. +- All 51 affected Architecture cases pass, including compiled command/caller, + exact registry, classification, audit matrix and corpus controls. Three + Registered obligations now have actual owners and implementation; the catalogue + records 244 Implemented rules, 140 in the Architecture assembly, and 302 + method declarations. Final complete-source qualification remains Step 6. +- All 157 selected Integration cases pass with zero skips. These include actual + app-role scoped reads/writes and independent RLS dirty twins, unknown/Closing/ + Closed target refusals, first/last-admin and shared/exclusive races, real + competing commits, complete fixture guard/policy restoration, timeout/cancel + rollback and same-backend pool reuse, finite metrics, no-write/interrupted/ + conflict seed reruns, central MUST failure rollback and actual child snapshots/ + redacted profile diffs. Existing-root child changes remain in qualified diffs; + no unknown collection is newly represented as a complete snapshot. +- Eight realm Node files execute 409 cases; 228 native launcher/orchestration + controls pass. Provider-witness and C# execution controls retain their actual + scopes; final combined provider/browser/source-bound qualification remains + Step 6 rather than being inferred from these cases. + +A separate actual command-path experiment passes on two disposable databases. +Each executes the production pipeline's 24 contextual commits and observes a +real first-admin User wait before the competing COMMIT. The current-code +observation-cost counterfactual disables only the heldness function's observation +in its isolated database; it is not a historical or security-qualified baseline. +Both helpers still acquire their real locks. Exact function state is restored +and databases dropped. Four first-per-type and twenty subsequent-per-type samples +are reported separately; neither population means process-cold or pool-cold. +Measured warm p95 is 8 ms for the counterfactual and 11 ms with production guards, +against the 500 ms local budget. Production client-SQL-span p95 is 9.158 ms; +client command counts match, including internal trigger time rather than internal +statement enumeration. Each pool peaks at two used connections of four and +returns to zero. Observed acquired User waits are about 52/53 ms. The small local +sample establishes neither a speed ratio nor production capacity or throughput. +No identity, connection tag, SQL or function body is emitted by this experiment. + +Qualification corrected real issues rather than relabelling failures: explicit +CASE grouping in trigger SQL; actual EF savepoint versus strict initial-Role +freshness; test counts under organization RLS; old 50/three-function census and +User TRUNCATE proof preempted by new FKs; and per-flow test metric observation. +The initial 153-case run was 150/153, followed by those verified expectation +corrections and the final expanded green population above. Full-step reviews +have not yet run; no local-complete or packet-complete claim follows here. + +### P03-1 Step 4 review round 1 (2026-10-26) + +**Reviewed source:** `0495f2b2`, full Step 4 diff from `dce6cad2`. Three new +independent read-only reviewers inspect SQL/storage/ordered-lock correctness +(GPT-6 Astra, xhigh), Domain/Application/privacy/corpus boundaries (GPT-6.1 Sol, +xhigh), and owned tooling/Seeder/native handoff (GPT-6.1 Sol, xhigh). They read +actual source, contracts and scoped receipts; none executes builds/tests or edits +files. All approve assigned runtime scopes with no verified blocking/major issue. + +Two independently identify the same Minor current-spec drift: Identity's bottom +permission/audit/evidence inventory still calls contextual commands absent and +implemented seed/lock/classification controls pending. The current descriptions +now name actual owners and point to canonical catalogue/measurement records, +while preserving pending independent review and later live/HTTP/closure owners. +No Accepted body or historical delivery record changes. + +Candidates are not promoted into findings without supporting current behavior: +per-act Tenancy lifecycle transition races remain the explicitly named P03-3 +contract; no current value-bearing database-diagnostic leak is established; and +concurrent owner editing of the selected private file is an unreproduced +configuration-continuity caveat rather than a demonstrated authority bypass. +No speculative runtime change follows from those candidates. Full source/shard/ +integrated provider qualification remains Step 6. Document/corpus checks qualify +the verified correction before a second fresh full-step review round. + +### P03-1 Step 4 review round 2 and diagnostic correction (2026-10-26) + +**Reviewed source:** `9c9ec4a7`. Two new independent read-only reviewers inspect +storage/SQL/privileges/ordered-lock behavior (GPT-6 Astra, xhigh) and +Application/Domain/tooling/privacy/corpus boundaries (GPT-6.1 Sol, xhigh). Both +approve their assigned runtime scopes. Neither edits files or executes tests. +Verified Minor corrections reconcile Standard 19's already implemented types +and Standard 05's contextual table-class and current grant inventories. + +The Application review also identifies an evidence gap: the current module +inventory overstates Step 2's sink proof. Classification and generic baseline +controls do not establish neutral/nested value exclusion at Identity's actual +writer boundary. The Accepted package requires that proof before those writers; +it is completed here before Step 4 closes, rather than moved to Step 6. The +earlier review's absence of a demonstrated leak is not a safety proof. + +New source-reaching tests demonstrate a real failure before the correction: +PostgreSQL returns neutral/nested/sensitive synthetic values from a tracked +profile write, with provider error detail disabled. EF's pre-adapter event 10000 +(`SaveChangesFailed`) puts neutral/nested values into serialized Serilog and +the actual Sentry SDK envelope. The initial two-case run has one failure and +one passing validation control. Local archive and response exclusion alone do +not establish safety for the other sinks. This negative receipt is retained +separately from the subsequent successful run. + +The narrow fix replaces only IdentityDbContext's EF save-failure event with +fixed event 3191 (`IdentityStorageSaveFailed`), retaining ordinary command +diagnostics and other modules' save-failure events. Unexpected contextual +provider/save/preflight failures become a fixed provider exception with no +original inner payload; owned conflict/target/plan classifications and caller +cancellation retain their existing behavior. The global binding adapter keeps +its existing fixed failure boundary. No general logging scrub, new authority, +grant, schema or HTTP operation is introduced. + +Eight focused actual Integration cases pass with zero skips: immediate and +deferred profile failures, global binding failure, sibling-module confinement, +real validator attempted-value exclusion, and existing success/owned-conflict/ +cancellation controls. Provider-side witnesses establish source reach; nonempty +positive controls establish serialized Serilog, real local archive, real Sentry +SDK envelope and L1 response execution before every canary exclusion assertion. +Sentry delivery uses an in-memory transport; the actual SDK serializes its +envelope, and the existing L1 handler writes response bytes directly. No remote +Sentry delivery or production HTTP endpoint is claimed. All 51 affected +Architecture and 191 affected Unit controls pass, with zero skips. Fresh scoped +independent verification of this correction remains required before local Step 4 closeout; complete +source/shard/provider qualification remains Step 6. + +### P03-1 Step 4 exported trace correction (2026-10-26) + +**Reviewed source:** `f814d97e`. Two fresh scoped read-only reviewers inspect the +diagnostic correction: privacy/source-reaching sinks (GPT-6 Astra, xhigh) and +storage/integration/corpus behavior (GPT-6.1 Sol, xhigh). The privacy slice +approves the four named sink controls. The integration slice identifies a +separate exported-trace path in the pinned EF instrumentation: its CommandError +handler copies the original provider message into span StatusDescription before +the adapter can translate it. This is a verified review finding only after a +new actual exporter reproduces it; the initial four-sink result alone does not +establish trace safety. + +The actual API tracing composition now drives a synchronous test exporter that +serializes at Export time. The pre-fix immediate profile case exports an EF +Error span containing every planted synthetic value; the negative log/TRX is +retained separately. The deferred preflight uses direct Npgsql, which the current +tracing composition does not subscribe to; it still reaches real L1 exception +spans. Neither absence of that driver span nor later mutation is a proof of +exclusion from an already exported span. + +The bounded correction marks only the actual Identity EF command Activity from +its DbContext interceptor, using a private object custom property with no values, +exported tags or inheritance. An API processor registered before exporters +replaces only marked EF Error descriptions with fixed text. Error status, +ordinary command evidence, trace parents and unmarked sibling descriptions stay +intact. It adds no SQL-text classifier, global scrub or new authority. + +All eight focused Integration cases pass with the expanded trace assertions. +Immediate profile and global binding errors export fixed EF descriptions; +deferred failure exports two nonempty L1 Error spans with the fixed translated +type. A sibling-module Error description still equals its actual provider +message. Caller Activity restoration and EF trace parent checks pass. The +existing serialized log/local/Sentry/response controls remain green. +All 51 affected Architecture controls and 194 affected Unit controls pass with +zero skips; the latter selection also includes the existing tenant span +processor's three controls. No remote OTLP or Sentry delivery is claimed. + +### P03-1 Step 4 local closeout (2026-10-26) + +The same two independent diagnostic reviewers recheck `67d75e62` read-only. +Both approve the trace correction with no remaining verified runtime finding. +They confirm source-owned marker confinement, processor ordering, serialization +at Export, nonempty immediate/global and deferred L1 controls, sibling evidence +and Activity restoration. Their one Minor receipt correction is closed by a +rebuilt CI/Release run against the exact committed source: 8/8 Integration, +zero skips. The normal commit formatter reordered test imports after the earlier +hash; the earlier receipt remains intact and the committed-source hashes/result +are appended separately. Prior qualification is not silently relabelled. + +Step 4 is locally complete after both full-step independent review rounds, +verified corrections, the actual diagnostic negative/positive controls and the +additional scoped verification above. Its original 157-case contextual selection +and later eight-case diagnostic/regression selection retain their separate +source/scope; their overlapping cases are not summed into a new total. Final +complete-suite, source-bound shard and combined provider/native qualification +remain Step 6. No HTTP/bootstrap, live authorization or closure delivery is +claimed. Implementation proceeds automatically to Step 5's approved existing +binding admission, with new-user transport still owned by P03-3. + +### P03-1 Step 5 — Existing-binding API admission (2026-10-26) + +The approved API handoff is implemented: stock validation produces immutable +`VerifiedProviderSubject`, whose optional actor remains compatibility evidence. +The existing credential gate and unchanged issuer/subject quota precede the new +existing-binding stage. Only an Active matching stored binding supplies the +nonnull `ValidatedTenantIdentity` actor before the route-independent resolver. +Unknown, conflicting, nonadmitting and unavailable bindings return the existing +fixed 401/Bearer response, including on credential-bearing public reads. The +closed internal outage reason is `binding_store_unavailable`. Ordinary HTTP +never creates, adopts or repairs a User and adds no endpoint or SDK operation. + +The API-owned startup service qualifies the immutable deployment pair. Its +resolver lazily constructs the module reader only for admitted credentials; +anonymous and construction/schema hosts buy no identity connection. A short +physically READ ONLY global owner finishes before tenant reconciliation. Reentry +retains the original verified-subject quota provenance, clears any normalized +identity and rereads the binding; missing or replaced evidence cannot borrow an +earlier identity or permit. Caller cancellation and arbitrary unexpected faults +retain their existing exception handling. + +Real provider fixtures use isolated databases per issuer on their owned +PostgreSQL container, not anchor rebinding. Authenticated provider readback feeds +the actual foundation runner before API startup and audit baselines. The warm +provider and native BFF preserve complete identity, refresh and logout contracts. +A real-provider control removes only a known persona's compatibility actor, +proves the signed access token lacks it, and still reads AccountSite with its +stored actor. Profile/credential restoration and a fresh complete-token positive +follow. This is not native actorless/new-user publication. + +Local launchers preserve the selected authority/issuer pair only in API +configuration and conflict-check each input source. Web startup does not consume +that pair. Native subject validation aligns to 255 characters while retaining +the complete actor/tenant publication contract. + +Qualification before implementation review: + +- CI/Release solution build has zero warnings/errors. All 2,770 Unit, 306 + Docker-free Integration and five Contract cases pass with zero skips. +- The initial complete Architecture run is 563/570 with seven failures and + zero skips. Those failures identify missed foundation census backfills: + five synchronous contextual tables need explicit asynchronous-inventory + exclusions; the sixth Organization SQL reader needs exact command/signature/ + binding controls; genuine typed Role/seed DTO readers need method-level read + enumeration; and pure stdin-parser tests belong outside the Docker-only + directory. The corrected classes run 90/90 with zero skips, preserving old + predicates and adding dirty controls. No new aggregate write exception or + production SQL change follows. These are separate receipts, not a relabelled + all-green full run; final source-bound complete qualification remains Step 6. +- The first real-provider/native selection is 50/51. Its one failure is an + exact fixture binding map omitting three legitimate acquisition-cleanup + subjects. Only those names are added; unknown/actor-conflict refusal remains. + All five quota cases rerun green together with ten actual binding HTTP cases + (15/15, zero skips). Overlapping cases are not summed into a new population. +- Actual binding cases prove actorless/equal success, unknown/conflicting/ + Closing/Closed/collision refusal without allocation, early/quota precedence, + physically read-only app-role/GUC ownership, startup missing/mismatched/wrong- + role refusal, real store outage with serialized fixed diagnostics, and cleanup + after a blocked lookup cancellation. One physical connector is reused only + after identity/tenant GUCs and lock/transaction ownership are cleared. +- Four final cases pass for the matched measurement control and the relocated + pure parser. Collision setup first proves the digest CHECK rejects mismatch, + temporarily removes only that exact constraint in its isolated fixture, + restores it and proves the independent constraint/trigger/policy/privilege + state again. An EXPLAIN numeric-format assumption and stronger early authority + configuration refusal are corrected in tests, without changing production. +- All 264 focused frontend cases pass, including signed 255/256 subject + boundaries and API-only authority projection. Web typecheck and lint pass. + +The small local measurement uses 32 audited bindings and twelve interleaved +samples per authenticated lane after warmup. A current-code observational control +returns one independently witnessed Existing result only for the exact verified +input; all other authentication, quota and tenant reading remain real. It is +neither historical nor security-qualified. Median control/production latency is +5.68/8.33 ms, a 2.65 ms observed difference. Driver statement totals are 60/108; +production includes twelve binding SELECTs and one observer proof SELECT per +lookup. The separate anonymous lane totals 60 statements. The unforced small- +population plan is Limit/Seq Scan, one actual row; planning/execution is +0.324/0.039 ms. Eight concurrent HTTP requests occupy four of four bounded pool +slots, then leave zero active/transaction owners. No production percentile, +capacity, throughput or speed-ratio guarantee follows. + +Both fresh implementation review rounds remain required before Step 5 closes. +Complete source/shard/discovery and complementary A/B CI evidence remain Step 6. + +### P03-1 Step 5 review round 1 and read-diagnostic correction (2026-10-26) + +**Reviewed source:** `5f7a0625`. Three fresh independent read-only reviewers +inspect API authentication/quota/reentry (GPT-6 Astra, xhigh), binding storage/ +cleanup/measurement (GPT-6.1 Sol, xhigh), and native/frontend/fixture/corpus +handoff (GPT-6.1 Sol, xhigh). None edits files or executes builds/tests. The API +slice approves. The storage slice requests one Major correction; the native +slice approves runtime and identifies Minor stale implementation-status text. + +The verified Major is EF `QueryIterationFailed` (10100), emitted before the +binding adapter translates the provider exception. The earlier permission-fault +receipt proves raw exception logging but contains none of its selected personal +canaries. A new actual HTTP case independently reproduces value disclosure: +a restrictive fixture-only RLS function raises a PostgreSQL error containing +the retained subject's neutral/nested/sensitive values. HTTP still returns 401, +but pre-fix serialized Serilog contains those values. The negative receipt is +retained separately; trace/response exclusion alone is not log safety. + +Identity now replaces only its EF query-failure event, alongside the existing +save-event replacement. Its command interceptor emits fixed event 3192 +(`IdentityStorageReadFailed`) for LINQ/FromSql read failures without the provider +exception or payload. Sync/async paths retain an operational signal; the adapter +still owns the original failure, cancellation and uniform HTTP refusal. No +binding-store query, authentication mapping or global/sibling logging changes. + +Fresh post-format CI/Release qualification passes 26 Integration, 51 Architecture +and 216 Unit cases, with zero skips. The actual HTTP canary reaches the provider +fault, returns 401 and exports a nonempty fixed Identity Error span, with no raw +provider type, SQLSTATE or canary in serialized logs, exported traces or response. +The RLS policy/function inventory is restored exactly and a fresh HTTP positive +passes. Separate sibling iteration-event/span and sync/async FromSql controls +remain positive. Existing save-failure, cancellation, connector reuse and cleanup +regressions are included; overlapping populations are not summed with earlier +receipts. + +Current glossary, Data Protection, Security 11 and Identity module descriptions +now match implemented storage/proof ownership, preserving historical records. +The Contract factory's exact identity startup-worker removal was tested in the +working tree but accidentally omitted from the initial implementation commit. +It is included in this correction; an exact committed-source Contract rerun +follows before the second fresh full-step review. No production startup bypass +is added. Final complete-source/shard/provider qualification remains Step 6. + +### P03-1 Step 5 review round 2 and local closeout (2026-10-26) + +**Reviewed source:** `cb5937a8`, full Step 5 range from `7d29843a`. Two new +independent read-only reviewers inspect API/storage/quota/reentry and the +diagnostic correction (GPT-6 Astra, xhigh), and native/frontend/fixture/privacy/ +corpus boundaries (GPT-6.1 Sol, xhigh). Both approve their assigned slices with +no verified actionable finding. Neither edits source or executes tests. Both +independently match committed-source/receipt hashes; the exact committed +Contract rerun passes 5/5 and the binding/diagnostic/cleanup selection 26/26, +with zero skips. Normal commit formatting reordered test imports, so these +receipts are appended separately rather than relabeling earlier source hashes. + +The parent also runs the complete guarded frontend population. Its first result +is 2,272/2,277 in the first package: five migration-build controls still expect +alphabetic module order after Tenancy/Platform. The approved Makefile correctly +places Audit then Identity before the remaining discovered modules because of +the central creation witness. Only the independent test expectation gains those +two named priorities. The native/privacy reviewer separately approves this +test-only correction; discovery, added-chain, exact argv, credential confinement, +fresh build and failure propagation controls remain intact. All ten focused +cases and the complete guarded frontend rerun pass: 2,380 cases in two packages, +zero skips/todos. The failed full run remains a separate failed receipt. + +Step 5 is locally complete after both fresh full-step review rounds, verified +corrections and committed-source requalification. Step 6 now owns the complete +source-bound suite/shard/discovery and PostgreSQL/Keycloak/native/browser/A–B +qualification, final current-corpus sweep and reviewable PR. Inherited Standard +05/06 current-state wording is included in that sweep. No packet-complete or +later onboarding/permission/closure delivery claim follows from local Step 5. + +### P03-1 Step 6 — Complete qualification inventories (2026-10-26) + +The final step reconciles the source-bound CI inventory and current carriers +before freezing the hosted qualification source. The actual fixture census grows +from 119 to 130 classes: eleven new Identity fixture consumers are added, with +none removed. Architecture/ordinary shard counts remain 6/12; algorithms, salt, +weights, filters, required contexts and all time/cleanup ceilings are unchanged. +This witness-only edit moves no case in either layout on the same manifest. + +Actual local Release VSTest discovery supplies 6,394 cases: 3,651 non-Docker and +2,743 Docker, with the latter split into 2,712 ordinary and 31 native cases. +Production discovery parsing, manifest/union/selector predicates and both +assignment algorithms validate every case exactly once. A and B have genuinely +different co-membership, including shared-fixture selectors. This is local +discovery/assignment proof, not hosted execution, cleanup or wall-fit evidence. +Unmeasured method weights keep their existing advisory default. + +The fresh local CI/Release solution build passes with zero warnings/errors; +all 2,770 Unit, 306 Docker-free Integration and five Contract cases pass with +zero skips. Frontend typecheck/lint and the Step 5 complete guarded 2,380-case +population pass. The eight-file development realm census passes all 409 cases. +Plan/result controls pass 72/30; native owner/provisioning controls pass 87/18; +the existing supply-chain, realm-gate, native-environment, ADR, fragment, roadmap +and log-index controls pass. OpenAPI and generated SDK snapshots are byte-equal +to current `main`. + +The complete local ordinary run is still executing at this entry. It identifies +an obsolete reversal preflight: the test expects Step 3's 50 tables/five total +Identity functions, while Step 4 installs 55/twelve. That first failure occurs +before reversal, so it establishes no Down failure. Only the independent expected +counts and explanations change; real reversal, empty-policy/function checks, +reapplication and app-role positive evidence remain required before closeout. +No migration or production behavior changes in this correction. + +A read-only current-corpus sweep verifies stale preimplementation claims against +the actual source and Step 3/4/5 records. Database/Testing/Permissions standards, +the test catalogue, isolation/audit/cross-cutting architecture and Identity's +audit matrix now describe implemented foundation subjects. Canonical discovery +and the phase Status block replace duplicated obsolete population/review state. +Accepted bodies and dated history remain intact; later live permission, +HTTP/new-user, operator and closure owners remain P03-2/3/9/10. + +Both fresh Step 6 review rounds, actual reversal qualification, complete +Architecture/ordinary/native/provider/browser results and source-bound complete +hosted A/B qualification remain required. This entry does not close the packet. + +### P03-1 Step 6 review round 1 and carrier correction (2026-10-26) + +**Reviewed source:** `124ff4a`, whose tree equals `6c379f12`. Two fresh independent +read-only reviewers inspect CI/source/discovery accounting (GPT-6 Astra, xhigh) +and current corpus/reversal/authority boundaries (GPT-6.1 Sol, xhigh). Neither +edits files or executes tests. The CI slice approves: raw discovery messages +match every retained manifest part, both assignments are exact and genuinely +different, and the fixture-only edit cannot select, omit or move cases. The +reversal slice confirms the independent 55-table/twelve-function expectations +and unchanged removal/reapply controls, with actual execution still required. + +One grouped Major corpus finding is verified: active standard introductions, +the standards index, catalogue introduction and conceptual hierarchy still say +Identity implementation/registry/Role or migration work is absent. These +contradict the real foundation and the corrected detailed sections. The stale +tails now yield to actual implementation facts and canonical current-state +pointers. The Permissions standard remains **Adopted** consistently in header +and index: the finite foundation exists, while live enforcement remains P03-2. +The conceptual relationship diagram exposes only the User key and links actual +columns to their owner, rather than implying unused email/raw-issuer storage. +Mutable decision-index pending tails also become owner pointers. No Accepted +ADR body, dated history or later-phase authority changes. + +Before this round, the merged PR #37 ancestry is reconciled on `development` +without changing a file. `origin/main` at `7cad8402` and already incorporated +ancestor `b1f19f5b` have the identical tree +`9eb11ced9d70f66dc84ad629f409801f1aeebbcf`. The ancestry-only merge preserves the +complete current tree and makes the PR comparison contain only subsequent work; +no rebase, force push or branch switch is used. + +Documentation/corpus checks qualify the verified carrier correction before a +second fresh source-review round. Running local ordinary work and final-source +hosted A/B/full-suite qualification retain their separate source and result +boundaries. This source review does not establish successful execution or close +Step 6. + +### P03-1 Step 6 full ordinary failures and bounded corrections (2026-10-26) + +The initial complete local ordinary run finishes in 47m08s: **2,630 Passed, +82 Failed, zero skipped, 2,712 total**. It uses the already built pre-correction +source from `83f701df`; intervening source edits do not requalify that binary. +The original log/TRX and per-case failure classification remain intact. This is +not a successful complete-suite receipt, and corrected subsets are not relabeled +as one. + +Verified failures form these groups: + +- Two migration-census cases retain Step 3 table/function expectations. The + independent full reversal expectation and Platform-only surviving-table union + now include the contextual subjects. Actual reversal, six-history-only empty + schema, zero functions/policies and reapplication/app-role positives pass. +- Forty-six worker/default-delivery cases reach the new mandatory Identity + startup service without owning an authority configuration. Three dedicated + messaging factories exclude only that named unrelated hosted service. Actual + producer/delivery workers, credentials, guards, health, deadlines and cleanup + assertions remain intact. Production startup and real identity fixtures retain + mandatory qualification. +- Twenty-six parent-scope structural cases find the two undeclared Membership + children. The detector now joins both actual Identity EF relations and the + independent applied schema, retaining all earlier Education/job predicates. + Twenty-two added clean/dirty/restoration cases cover missing/wrong FKs, model/ + declaration omissions, trigger metadata, exact invoker body, timing, locks, + tenant/parent/null comparison, SQLSTATE and classification metadata. +- Eight diagnostic cases expose additional actual EF spans. Distinct tracing + compositions create nested spans for one command; marking only the innermost + leaves outer provider messages unprotected. The full receipt's additional + subscribers are not attributed to a guessed lifetime fault. A deliberate + two-composition control establishes the defect independently. + +The parent census also verifies an implementation mismatch with the existing +canonical `23514` parent-scope contract. A narrow forward migration replaces +only `fn_identity_contextual_mutation_guard`: missing/mismatched Membership +parents use `23514` with fixed `membership_parent_scope` constraint metadata; +revoked-parent and other existing `P0304` classifications stay. That metadata +preserves the adapter's existing fixed Graph descriptor rather than producing +a provider outage. Original migration output is byte-identical; no table, +trigger, grant, owner or data changes. A real fresh/predecessor/head/down/head +control proves exact function identity/OID, ACL, owner, invoker/volatility/search +path and unchanged siblings, with app-role error witnesses at every version. + +Fresh qualification passes **363 Integration and 28 Architecture cases**, zero +skips, including all seven affected structural/worker/membership/rollback classes. +The added migration case and parent-census rows require refreshed final discovery. +The first CA1859 build error is retained separately from the corrected build. + +For diagnostics, four sync/async × standalone/real nested-Tenancy controls first +fail on unchanged trace-boundary source. Both actual production tracing +compositions serialize two distinct Identity Error spans for one independently +witnessed provider command: the outer span contains neutral/nested/token +canaries. Independent started/stopped IDs, exporter coverage and ancestry +checks run before the failing exclusion assertion. No remote telemetry delivery +is claimed. + +The correction uses a per-IdentityDbContext interceptor. It captures command ID +and the exact caller before synchronous command creation, consumes only the +matching post-broadcast creation event, validates the complete EF-only interval +and marks only its newly created spans. The existing caller is never marked, +including a real EF command from another module. The before-export processor +is unchanged. No SQL classifier, global scrub/registry, SDK reset or discarded/ +deduplicated span supplies the proof. + +All **23 diagnostic plus seven cleanup controls**, **216 Unit** and **51 +Architecture** cases pass, zero skips. Both exporters cover every independently +observed EF ID; all Identity Error spans are fixed and canary-free. The actual +nested Tenancy command keeps its original provider message, and caller status, +ancestry and Activity restoration remain intact. These focused populations +retain their scopes rather than replacing the failed full run. A further 81 +corpus/inventory/FK Architecture cases pass after the current-carrier updates. +Backend setup guidance now names the installed authority/runtime configuration +prerequisite and the managed local launcher. + +Committed-source requalification, the fresh second Step 6 review round and +complete source-bound hosted A/B execution remain required before closeout. + +### P03-1 Step 6 review round 2 and complete parent-stack correction (2026-10-26) + +Two fresh independent read-only reviewers inspect `4fc7e1a7`: the SQL/privacy +slice (GPT-6 Astra, xhigh) and accounting/corpus/reversal slice (GPT-6.1 Sol, +xhigh). Both find the same remaining parent classification defect. The +admission trigger runs before the mutation guard for assignment INSERTs, so +missing or RLS-hidden Membership parents still return `P0302`. The prior +visible-parent mismatch witness did not exercise that branch. A real app-role +six-case control first reproduces the defect: four pass, two fail. The retained +committed-source selection also reports **409 Passed, five Failed, zero skipped, +414 total**; all five failures are the schema inspector expecting the original +function body because it reads only the first two migrations. + +A second forward migration replaces only +`fn_identity_membership_admission_guard`. Missing/hidden Membership parents now +use the same fixed `23514` / `membership_parent_scope` refusal as the mutation +guard. Actual unknown or nonadmitting User targets retain `P0302`. No function, +table, trigger, data, owner or grant is added. Original migration SQL remains +byte-identical. Each correction's real round-trip control pins its own exact +migration version, preserves function OID/owner/ACL/security mode/volatility/ +search path and sibling definitions, then converges with the fresh latest chain. + +The inspector now derives effective function definitions from every compiled +Identity migration in actual EF order. It recognizes replacements by normalized +signature and retains the final body; duplicate creates, undeclared replacements +and unsupported declarations fail. Exact body/privilege/caller checks and the +twelve-function/five-definer/eighteen-caller census remain. Nine independent +parser controls exercise replacement order and rejected forms. The stale +Security introduction now points to the canonical phase Status block while +retaining P03-2 ownership of live membership execution. + +The corrected parent-stack, function-schema, reversal and parent-structure +selection passes **159/159**, zero skips. Both child tables have missing, +RLS-hidden and visible NULL-organization-mismatch controls, each with an actual +app-role positive write before refusal. These focused results do not replace +complete source-bound qualification or imply packet closeout. + +An additional **77/77 Integration** startup/worker/binding/diagnostic cases and +**28/28 Architecture** cases pass, zero skips. These selections remain separate +receipts; overlapping earlier populations are not added into a new suite total. + +### P03-1 Step 6 correction approvals and first hosted assignment (2026-10-26) + +Both second-round reviewers independently approve correction commit `3754e4ea`. +They verify source/artifact hashes, the exact two negative failures, corrected +rows and historical SQL equality without executing tests themselves. No concrete +actionable source finding remains in those correction verifications. Complete +Release compilation passes with zero warnings/errors. Fresh local Unit **2,770**, +offline Integration **306** and Contract **five** cases pass with zero skips. +Actual Release discovery contains **6,437** unique cases: 3,651 non-Docker and +2,786 Docker (2,755 ordinary plus 31 native). Both assignments cover the exact +population once and genuinely change co-membership. Local discovery is not a +hosted-execution or wall-fit receipt. + +The first complete hosted A assignment is +[run 40270967586, attempt 1](https://github.com/HodeTech/LearnStack/actions/runs/40270967586), +on `3754e4ea`. **24 jobs succeed; ordinary-6, ordinary-9 and the Integration +aggregate fail.** All Architecture pieces, the backend aggregate, native proof, +frontend, meta, secret scan, OpenAPI and public demo pass. Retained immutable +archives and actual case IDs show **6,401 Passed, one Failed and 35 without a +result**. No complete-suite success is inferred from the passing pieces. + +Both ordinary owners reach their unchanged deadline and require forced cleanup. +Ordinary-6 continues to pass renderer cases until 31.66 seconds before that +deadline; its remaining serialized public/diagnostic cases are queued. Actual +fresh account fixtures also successfully qualify Identity startup. Two read-only +source/evidence investigations find no shared Identity startup deadlock. This +does not prove that every unfinished case started. The original artifacts and +incomplete cleanup/ownership outcomes remain intact. + +Ordinary-9 additionally contains a real browser failure after 28.38 seconds: +`browser-devtools-missing`. The owned stock Chrome remains live during the +ten-second readiness window but does not create its port file. This is before +CDP attachment, page navigation or authentication. The lower-level cause is not +established by the closed diagnostic; it is not labeled transient or repaired +by a blind retry. + +A separate verified fixture dependency is corrected: the BFF browser now uses +`--password-store=basic` and `--use-mock-keychain`, matching the existing admission +fixture and +[Chrome 155's own test launcher](https://chromium.googlesource.com/chromium/src/+/refs/tags/155.0.8059.39/chrome/test/base/test_launcher_utils.cc#56). +Chrome's source explicitly avoids native password-store UI/timeouts in tests. +This two-line isolation correction changes no sandbox, HOME, readiness or +cleanup limit and adds no fallback. It does not establish causality for the +first hosted browser failure. Existing focused frontend controls pass **89/89**; +the actual local browser positive/history-counter case passes **1/1**, zero +skips. Actual Ubuntu browser and complete complementary A/B execution remain +required before closeout. + +### P03-1 Step 6 measured timing revision (2026-10-26) + +[ADR-0063's reviewed-plan mechanism](../decisions/0063-complete-bounded-ci-test-shards.md#versioned-plan-and-independence) +owns this timing-only revision. All 24 first-attempt archives are retained with +API digests and exact source/run/attempt identity. Selected discovery IDs bind +every completed row; complete passing owners also have exact TRX/prefix equality. +Of 1,577 observed selector groups, 1,563 are fully Passed and fourteen are +censored. An interrupted owner is never treated as a complete successful owner. + +Weights use ceiling milliseconds of the complete selector's case-duration sum, +minimum one. Complete passing ordinary owners supply their current observations. +For interrupted ordinary owners, fully observed passing groups may add missing +measurements or increase existing measured weights; they never reduce an existing +measurement. Failed/partially observed groups retain their old weight or unknown +default. Historical slower Architecture observations remain floors. Each used +source names the run, source SHA, owner, artifact ID, entry digest, unit and scope; +the two interrupted JSONL prefixes are explicitly distinguished from complete +passing TRX receipts. + +The revision measures 189 previously unknown selectors; five remain unknown. +Only `weights` and `sources` change. Literal JSON values for counts, algorithm, +salt, default, argument bounds, fixed-cost observations and the 130 fixture +classes are byte-identical. The same twenty execution owners, twenty-minute +whole-job ceilings and seven required names remain. No selector, trait or case +is removed. Both assignments retain all 6,437 unique cases exactly once, with +independent Architecture/ordinary/shared-fixture co-membership witnesses. + +The reviewed plan digest is +`7e3357bf961f6ed215a306a72d8b616c7bf7462b098205c1094885d422062804`; +manifest digest remains +`29ded01d790e2f1ecdcc4dc73c349d67e52206afa4034c4e1240c751278be2b5`. +The full assignment diff moves 2,961 cases in A and 2,947 in B. Mixed advisory +ordinary maxima become 649.438s and 719.914s, respectively; these sums are not +execution-wall bounds. Actual first-attempt pre-owner/setup/discovery intervals, +test-process versus case-body differences and unobserved fixture costs remain +separate. The failed browser observation is not reduced into a cheaper positive +weight. Both full variants on the new final source remain required; neither +these estimates nor the preceding-head successes establish fit or close Step 6. + +### P03-1 Step 6 qualification closeout and PR handoff (2026-10-26) + +All six implementation steps complete their two fresh independent review rounds. +Verified correction reviews approve `3754e4ea`; supplemental reviews approve the +bounded browser fixture change `e05ba3ad` and timing revision `193d61cc`. +The preceding entries retain failed runs, actual corrections and proof limits. +No new decision or implementation scope is inferred from a passing test. + +The final implementation source is `193d61cc17ab66e9c392039d5da2ad112b33bb8f`. +[Run 40274315368](https://github.com/HodeTech/LearnStack/actions/runs/40274315368) +completes **attempt 1 (A) and attempt 2 (B)** on that same source, workflow, +reviewed plan, test population, SDK/console and adapter identities. Both full +attempts have **27/27 successful jobs**, including the seven required contexts. +Each supplies 25 immutable, API-digest-verified artifacts and twenty producer +packages with complete natural ownership/cleanup, no forced stop, exact actual +TRX/completed-case identities and zero skips. Pure production aggregate +validators independently reproduce both protected results from retained data; +this does not simulate hosted execution on the workstation. + +Each attempt passes **6,437 .NET cases**: + +- 2,770 Unit, 570 Architecture, 306 offline Integration and five Contract cases; +- 2,755 ordinary Docker and 31 native cases. + +Both complete frontend guards independently report **2,380 Passed in two +packages**, zero skips/todos, with lint, typecheck, production build and native +ingress controls. Both actual public-demo receipts qualify nine linked pages, +27 Lighthouse JSON/HTML report pairs, budgets and completed process/Compose/ +private-file/environment/lock cleanup. Actual provider/native tests remain +separate from mocked protocol unit controls; serialized Sentry/telemetry proof +does not claim remote delivery or full manual accessibility coverage. + +The two assignments genuinely change selector co-membership: A-only/B-only pairs +are **6,143/6,469 Architecture**, **61,057/66,502 ordinary** and **60,766/66,203 +shared-fixture**. Base/native membership stays identical. The longest complete +job is **997s in A / 976s in B**, within the existing applicable ceilings. +The real browser positive/history-counter and two-host warm-realm refresh/logout +journeys pass under both arrangements. These successes do not retrospectively +establish the lower-level cause of the first hosted browser failure. + +The plan digest is +`7e3357bf961f6ed215a306a72d8b616c7bf7462b098205c1094885d422062804`; +manifest digest is +`29ded01d790e2f1ecdcc4dc73c349d67e52206afa4034c4e1240c751278be2b5`. +Retained full verification receipts hash to +`8572744e36430812c476c8e59ef2ba9c77c262bb2038e03bf640652b2b595161` +(A) and +`b0cc4a5c0eff90852f5de763ff94c39ec1e79496f27d4d1a8cd23d089278d0e9` +(B). Original API metadata, archives, raw result rows and reports retain their +own source/attempt identity rather than being relabeled as another head. + +The independent accounting reviewer verifies both attempts directly: all fifty +archive digests/sizes, package byte equality, actual TRX/JSONL/discovery outcomes, +disjoint artifact identities, natural cleanup, toolchain hashes, native/provider/ +browser witnesses, public-demo report hashes and the three co-membership +comparisons. The cross-attempt audit reports no finding and explicitly limits +its qualification to `193d61cc`. + +Only closeout evidence/status documentation changes after the qualified +implementation source. The final documentation head requires normal complete +PR qualification; the recorded A/B receipts remain explicitly bound to +`193d61cc`. The PR comparison uses `origin/main`, including the already recorded +ancestry reconciliation, and every non-merge commit passes the actual strict +commit-message hook. No branch switch, published-history rewrite or unrelated +worktree cleanup is performed. + +P03-1 delivers audited global storage/common creation, contextual storage/seed, +existing-binding admission and privacy/diagnostic foundation. It opens no new +HTTP/SDK operation. Live membership/permission execution remains P03-2; usable +new-user HTTP/BFF onboarding remains P03-3; production first-admin/rebind and +global closure/redaction remain P03-9/P03-10. P03-2 is the next packet, not part +of this implementation. The phase Status block owns review/merge state. + +### P03-1 PR 38 review corrections (2026-10-26) + +Two maintainer-supplied reports review the `7cad8402` → `d32f3101` PR population. +Their findings are review data, not authority to change Accepted decisions. Three +independent verification slices check tooling/domain, SQL/audit and mutable +carriers against `d32f3101`; their source review does not claim executed suites. +The correction pass preserves ADR-0072/0073/0074 and the separately owned future +gates. No new HTTP route, role, owner function, tenant setter, credential claim, +creation budget or distributed-session policy is admitted. + +| Finding population | Verified correction or disposition | +|---|---| +| P0-1, tooling source selection | `make migrate` now delegates execution to a bounded owner. The migration connection and optional authority pair come from one complete source; partial/mixed selections refuse before any .NET child. Complete process input takes precedence over file defaults. Installer children receive only the selected credential/pair and tooling prerequisites. Actual recipe controls cover both sources, schema-only input, refusals, build/order and private-environment isolation. | +| P0-2, first report's three documentation findings | Mutable navigation/model/startup carriers are reconciled to accepted Identity storage and Phase 03 Status. Direct API startup requires the installed matching authority even for anonymous reads; it does not load root `.env`. Unused global email/profile, triple-key roots, persisted Platform roles and unqualified contact/custom-field claims no longer describe the delivered foundation. Future field/UI decisions retain their named gates. | +| P0-3 | Actual app-role global audit INSERT controls now exercise eleven malformed attribution/scope cases with valid committed twins, owner/platform refusals, and an independently isolated WITH CHECK control. Missing scope can reach the BEFORE guard first; the proof does not require every refusal to be 42501. | +| P1-1 | The two-second transaction timeout remains. Save/preflight contention maps to the existing fixed conflict refusal, including Npgsql's exact transient execution-strategy wrapper. Real held-row tests exercise both adapter and seed handler, rollback-only state and no partial profile. Physical COMMIT uncertainty is unchanged. The report's claim that the existing provider exception maps to HTTP 500 is incorrect; it maps to 503 and current writers are internal seed commands. | +| P1-2 | Completed ordinary binding lookups dispose their transaction and return the physical connector before tenant dispatch, retaining the scoped connection object for its next owner. A one-slot real pool admits a second HTTP binding/tenant read while the first request's scope remains held; the original request subsequently reopens its own tenant owner. Cancellation/clean connector reuse remains covered. | +| P1-4 | An unclassified global creation releases its prepared owner before returning the central deployment error; the binding service no longer reports that configuration defect as storage availability. Created success additionally requires the common owner's recorded Committed outcome. | +| P1-6 | Ordered SQL operation digests pin the four existing Identity migrations' Up/Down output despite their shared helpers. The forward correction preserves the original helper outputs and model; current/predecessor transition controls compare exact function identity/body/ACL. | +| P1-7 | The profile seed declaration now binds its expected User and single Role assignment through closed admission. Both are checked before/after waiting; replaced User/assignment controls refuse without mutation. The retained v1 fingerprint algorithm and fixed non-null persona profiles are unchanged. Generic both-null profiles are not part of this seed contract. | +| P1-10 | Real competing first-admin commands now prove one successful graph/MUST row; final-admin checks have globally eligible/ineligible twins. Restrictive organization UPDATE/DELETE controls remove only the target policy and retain the independent WITH CHECK/parent guard, distinguishing normal zero-row filtering from the resulting closed exception before restoration. Exact per-command permission mapping detects a swap that preserves the distinct registry set. | +| 5.1–5.4, remaining source corrections | Already-cancelled requests perform no binding call; verified provider evidence has fixed formatting; disposed global-unit state clears. Nonstorable subject text refuses before hashing/storage; BFF code/refresh align whitespace and UTF-16 limits while preserving exact valid non-ASCII subjects. Membership targets require UUIDv7. An unused SQL-string property is removed. Ingress requires complete pairs per participating source; identity-child failures use the closed identity stage and the unchanged total pass budget. | + +The child-write/revocation race in 5.2 is reproduced with actual PostgreSQL 18 +app-role sessions: `FOR KEY SHARE` permits a new assignment to commit alongside +an uncommitted non-key revocation; final state is Revoked with that new child. +The forward, function-only migration +`20261026102944_serialize_identity_parent_lifecycle` changes the parent locking +read to `FOR NO KEY UPDATE`. The real tracked `Membership.Revoke` regression +then observes the waiting inserter refuse after the revocation commits. Its +predecessor twin still reproduces the defect. Revocation retains its shared +tenant plan and acquires no new User fence. No historical migration is rewritten. + +Several requested changes are not current defects or would select new policy: + +- Accepted ADR bodies and source-bound dated readiness/proof entries remain + historical records. Mutable summaries are corrected; historical pending text + is not rewritten into a live dashboard. +- Exact function bodies, five definers/eighteen callers and the Audit→Identity + migration-order control already exist. The primary catalogue description is + corrected; the existing configuration-construction scanner is not described + as a census of every physical connection checkout. +- Audit-owned witness installation from the Identity chain, confined Boolean + owner functions, broad contextual UPDATE grants, cross-module root-FK absence + and the SQL-credential threat boundary are explicitly accepted. No newly + demonstrated sanctioned writer bypass warrants redesigning those contracts. +- A typed tenant sentinel does not reserve the same bits in every identifier + type. Qualification is startup-only and fail-closed; a new retry/readiness or + public 503 policy is not inferred from the uniform-401 diagnostic. Provenance + remains available to enforce re-entry without another subject debit. +- Neither all Error events nor arbitrary provider inners have been shown to + escape the closed global boundary in this review. No ad hoc module tracker + capture is added in conflict with L1 ownership. Deployment alert thresholds + remain Phase 11; production Identity lifecycle/permission writers retain + P03-2/3/9/10 ownership. Extra database UUID checks, new creation-attribution + immutability and additional display-name restrictions are not silently adopted. +- Both A/B attempts retain twenty-five original archives each. Rehashing all + fifty against original API metadata, extracted package bytes and twenty-seven + Lighthouse report pairs per attempt supports the existing source-bound claims. + Remote retrieval limits do not invalidate retained evidence. The intermediate + 159/77 TRX populations and both separately dated timing observations exist; + the reports' unlocated 197/256 claim supplies no correction target. + +Local qualification records 2,779 unit passes, 195 selected real Identity/API/ +PostgreSQL/Keycloak passes, and 2,402 guarded frontend passes in two packages, +with zero skips/todos in those completed runs. Final local follow-ups pass the +44 Identity/auth/corpus architecture cases, 306 Docker-free integration cases +and five contract cases, with a zero-warning Release solution build. The full +571-case Release run precedes the final global-wrapper refinement; its affected +architecture population is the separately rerun 44-case set. The two additional +private-file recipe controls pass in the final 24-case tooling selection. +The local command sample observes +production-guard warm p95 7 ms (twenty warm samples; four cold samples), versus +12 ms in its same-code observation-only counterfactual, with peak two/four pool +slots and final zero busy slots. This is a local observation, not an enforced +CI SLO, historical baseline, production capacity or proof of a speedup. + +Failed qualification is retained separately: the first selected real run has +188 passes/two failures exposing EF's contention wrapper. Its corrected run +passes 193/193 including the subsequently added organization controls. The final +195/195 run additionally covers real transient global EF read/write failures +with personal-data canaries and the EF-generated forward migration; the model +snapshot remains byte-identical. The global storage boundary translates only +Npgsql's exact transient wrapper shapes, preserving unrelated invalid operations +and cancellation. An +initial Debug architecture run is interrupted after repeated compiled-boundary +failures; the canonical Release controls pass, and the full Release suite +passes 571/571 separately. An initial guarded frontend run overlaps the architecture +mutation census and fails two cold-development RSC proofs. Focused clean and +trace-mutant controls, then the entire serial guarded run pass without timeout +or protocol changes. Resource contention is plausible, not established as the +original failure's sole cause. The local test guide now uses CI's Release +configuration and serial heavy qualification. + +The correction commit still requires two fresh independent review rounds and +current-source hosted checks. These local results do not relabel the earlier +`193d61cc` A/B receipts or claim a new hosted execution. + +### P03-1 PR 38 correction review round 1 (2026-10-26) + +Two fresh independent reviewers inspect committed `413c9bde` against `d32f3101`: +Astra/xhigh covers every backend diff and surrounding ownership/proofs; +Sol/high covers tooling, frontend and mutable documentation. Neither reviewer +edits source or executes .NET suites. Both request changes, rather than treating +the preceding local passes as exhaustive proof. + +The tooling reviewer reproduces an explicitly empty process authority key being +discarded into schema-only mode. Presence now differs from absence; empty identity +keys refuse before any .NET child, while the existing empty migration-connection +sentinel can still select a complete private file. Four additional actual-recipe +controls pass in the 28-case selection. The reviewer also finds the remaining +triple-key/organization-owned-role wording in Risks and one grammatical error; +both mutable sentences are corrected without changing historical ADR text. + +The backend reviewer identifies non-owned transient EF wrappers that bypass the +contextual save translation. A real 55000 provider canary gives three passes/one +failure on `413c9bde`, then four/four passes with the exact wrapper sanitized to +`IdentityStorageProviderException`. Owned mutation conflicts, cancellation, +programming failures and physical COMMIT classification retain their meanings. +The same G19 contract already covers seven production seed read methods; one +confined provider-only read boundary and real source/sink controls complete that +population. No public read endpoint or current HTTP disclosure is inferred. + +A separately retained synthetic 53300 observation breaks the Npgsql connector +and makes direct rollback produce a secondary exception containing its original +provider cause. The common owner still preserves the primary failure. Its +secondary rollback diagnostic now drops the exception for declared Identity +operations or the fixed Identity storage provider descriptor, including read +queries; an ordinary-operation control retains the preceding diagnostic behavior. +This is diagnostic confinement, not new transaction authority or a changed +rollback/COMMIT outcome. + +Hosted run [40311209276](https://github.com/HodeTech/LearnStack/actions/runs/40311209276) +tests head `413c9bde` through merge source `4b8dbe33`. Twenty jobs pass, including +all architecture producers, backend aggregate, frontend/native ingress, public +demo, OpenAPI and metadata gates. Six ordinary producers and their integration +aggregate fail: the independent whole-body parent-guard expectation still names +`FOR KEY SHARE` after the new forward correction. The workload reports +`tests_failed`; failed ownership/forced-cleanup receipts are not accepted as +complete qualification. The expectation now independently requires the stronger +Membership-parent lock, and a planted downgrade back to KEY SHARE must fail. +The full 96-case parent/read/sink selection passes locally after this correction; +its output remains separate from the failed hosted attempt. + +Full current-source qualification and a second fresh review round follow the +correction commit. The earlier A/B receipts remain bound to their recorded source. + +The round-1 follow-up passes 2,782 unit cases, 281 selected real Identity/ +parent-scope/provider/diagnostic cases, 45 related architecture cases and the +complete guarded frontend population of 2,408 cases in two packages. Frontend +lint/typecheck and documentation checks pass. These are local results with zero +skips/todos, not a replacement for current-source hosted qualification. + +### P03-1 PR 38 correction review round 2 (2026-10-26) + +Two new independent reviewers inspect `d32f3101` → `26923143`: Astra/xhigh +reviews all changed backend production/test files and surrounding ownership; +Sol/high reviews tooling, frontend and mutable documentation. Neither executes +.NET or provider/browser qualification. The backend reviewer approves with no +concrete residual finding, explicitly limiting that verdict to source review. + +The tooling reviewer finds that the shared migration-role parser accepts the +first recognized username assignment even when another alias follows. That +ambiguity now refuses without printing credentials, before any .NET child. +Four actual-recipe negative controls cover duplicate/synonymous assignments, +including equal duplicate values; a quoted password containing a role-like +segment remains valid. The focused migration/demo selection passes 227/227. +This establishes refusal before child execution, without making an unmeasured +claim about Npgsql's duplicate-alias precedence. + +The same reviewer narrowly rechecks the parser, refusal-before-child path, +controls and Status edit, confirms both findings closed, and reports no residual +issue in that scope. This recheck does not claim a new full review or suite run. + +The reviewer also identifies the Status row's unqualified completion wording. +It now distinguishes implemented work from pending correction qualification; +the earlier six-step closeout and its source-bound A/B receipts remain history. +Both fresh correction review rounds are complete. Current-source hosted +qualification remains required and is not inferred from reviewer approval or +the focused local checks. + +The final guarded frontend run passes 2,413 cases in two packages with zero +skips/todos; canonical frontend lint/typecheck and the documentation gates pass. + +### P03-1 PR 38 correction fixture census (2026-10-26) + +Hosted run [40317627293](https://github.com/HodeTech/LearnStack/actions/runs/40317627293) +at `492f3f67` rejects the metadata control because the new real contextual-read +sink class is absent from the closed shared-fixture census. The census now +includes that actual class. Shard counts, assignment algorithm, weights, +resource limits and time ceilings are unchanged; no producer is omitted to +obtain a pass. All 72 planner controls pass before the next push, and the +tooling reviewer independently confirms the exact source/census match and +status/evidence wording in a narrow read-only recheck. Because this +changes the plan digest, final qualification requires both complete A/B layouts +at the same correction source; the original `193d61cc` A/B evidence is not +relabeled. The phase Status block records committed implementation and review +state without predicting the current-head checks' result. + +### P03-1 PR 38 measured timing correction (2026-10-26) + +Run [40318359878](https://github.com/HodeTech/LearnStack/actions/runs/40318359878) +tests head `c14ec6a7` through tree-equivalent merge source `5e02e3cc`. Complete +A passes all 27 jobs and 6,490 distinct .NET cases: 2,782 unit, 571 architecture, +3,132 integration and five contract cases. Twenty owners finish naturally; +all 25 original archives, package bytes and 27 Lighthouse JSON/HTML report pairs +are retained and independently checked with the production aggregate validators. + +Full B is not qualified. Twenty-five jobs pass; `ordinary-7` reaches the existing +deadline and its integration aggregate refuses. Its 194/231 completed cases all +pass; 37 have no result. Across B, 6,453 cases pass. The failed receipt reports +forced cleanup, incomplete ownership and `dockerAbsent=false`; +`cleanupOwnershipComplete=true` does not turn this into natural cleanup. +All 24 B archives and raw metadata are retained and independently audited. +The failure is not labeled an assertion failure or a proven transient flake. + +The timing-only correction uses the maximum measured duration from complete +A/B selector groups. It measures 17 previously unweighted selectors and raises +23 existing ordinary weights whose measured sum exceeds their prior value by +at least ten seconds. No prior measured weight decreases. B's partial Seeder +method (11/20 cases) and 21 methods without completed cases contribute no B +estimate; A's complete observations remain available. Every changed weight names its original +TRX or exact completed-case prefix digest, run/attempt, artifact and source. +The 72 planner and 30 aggregate controls pass. Architecture weights, all shard +counts, salt, assignment algorithm, default weight and resource/time limits +remain unchanged. + +The plan digest changes from +`c9437dbd00f644fd1b13c2ff21c038abd1f359595283d5c5a6d0f4d0db0c84fb` +to `b61cda34c8c8a762cef07baaa22862da1299bd56fbbdc895577ded8e76b90719`. +The same 6,490-case manifest remains +`e113e14c162b7691f80e2e4afae75b0fca0435335920a727db7f97fba17b00e3`. +On that unchanged manifest, the planner moves 2,527 cases in A and 2,426 in B; +architecture, ordinary and shared-fixture co-membership remain genuinely distinct. The +observed maximum case-body envelope for B falls from 901 to 681 seconds in the +read-only comparison. These sums can overlap and exclude setup, discovery, +fixture, export and cleanup costs; they do not prove wall-clock fit or establish +the failure's sole cause. Two complete attempts at the revised source/plan +remain the required qualification. Historical successful receipts are not +reused as that qualification. + +### P03-1 PR 38 independent mutation collections (2026-10-26) + +At head `dfdf9cab`, run +[40326601181](https://github.com/HodeTech/LearnStack/actions/runs/40326601181) +passes complete A: 27 jobs and 6,490 cases. Independent original-archive +validation confirms all 25 ZIPs, 147 producer-package files, twenty natural +owners and 27 public report pairs. Full B is not qualified: `architecture-4` +reports `deadline_exhausted` after 76/77 passing cases; `ordinary-0` reports +`unit_observation_failed` near the owner budget after 350/355 passing cases. +Their dependent aggregates refuse. All 23 B original archives are retained; +the six cases without results are not described as failed assertions or skips. +The observation refusal alone does not identify its lower-level cause. + +Further measured-weight alternatives do not establish fit for both layouts. +With xUnit's class collections, multiple independent long-running mutation +Facts in one class serialize. The rejected alternatives retain an observed +771-second class body path before setup/discovery/other work; changing only +method weights does not remove that class constraint. + +Nineteen independent mutation methods are grouped by concern into separate +class collections. Each method already owns and disposes its own Cecil graph. +Declaration-only moves preserve exact body bytes; wrapped companions change +only uniform indentation, with exact dedented bodies and all 48 recurrence +InlineData attributes preserved. Their clean, dirty and restored predicate +passes, canonical catalogue rule names and the two-thread cap remain unchanged. +No detector, resolution-walk algorithm or cache change is included. + +| Predecessor nested class | Independent nested class | Existing method concern | +|---|---|---| +| `JobExecutionMutationTests` | `JobOwnerMutationTests` | Owner admission and retained scope | +| `JobExecutionMutationTests` | `JobOrchestrationMutationTests` | External orchestration and resource carriers | +| `JobLifecycleMutationTests` | `JobCapacityMutationTests` | Capacity and checkpoint authority | +| `JobLifecycleMutationTests` | `JobRecipientMutationTests` | Recipient admission and fences | +| `JobLifecycleMutationTests` | `HangfireRuntimeMutationTests` | Runtime fatal/constructor boundaries | +| `OutboxDispatchConventionTests` | `JobRecurrenceMutationTests` | Recurrence authority and cleanup; 48 cases | +| `OutboxDispatchConventionTests` | `ResolutionMutationTests` | Resolution graph mutation controls | +| `JobAuthorityMutationTests` | `JobAuthorityCensusMutationTests` | Authority activation and live guards | +| `OutboxDispatchConventionTests` | `CleanupOwnerMutationTests` | Privileged cleanup ownership | +| `OutboxDispatchConventionTests` | `DeliveryLifecycleMutationTests` | Delivery lifecycle graph | +| `OutboxDispatchConventionTests` | `BridgeCredentialMutationTests` | Two bridge credential controls | +| `OutboxDispatchConventionTests` | `CredentialBindingMutationTests` | Two credential binding controls | +| `OutboxDispatchConventionTests` | `IntegrationInvocationMutationTests` | Integration invocation graph | +| `OutboxDispatchConventionTests` | `DeliveryCredentialMutationTests` | Delivery credential consumers | +| `OutboxDispatchConventionTests` | `JobOrchestrationDeclarationMutationTests` | Finite orchestration declarations | +| `OutboxDispatchConventionTests` | `JobMetricMutationTests` | Two metric callback/census controls | + +The plan adopts 39 source-bound, complete-group timing observations from the +last actual A/B evidence and explicitly aliases the nineteen renamed selectors. +Eight aliases overlap those timing changes: 50 semantic methods are affected. +Alias source cards retain predecessor measurement identity and disclose that +the new selector name has not yet executed in hosted CI. The 95 source records +remain within the existing cap. No incomplete method contributes a duration; +the earlier large current-source reset is not adopted. + +Actual local Release VSTest discovery confirms 6,490 cases, with exactly 66 +old IDs replaced by 66 new IDs and 6,424 byte-equal case records unchanged. +The manifest digest is +`8d017042f7e439273a7164326d9a1ae7ef3ea4ea3dea9a1bfa4c315a133bef21`; +the plan digest is +`115e474202360d0d7d99e1a8c69a0b40f7eb84669364b23ce90c94341969113b`. +Both actual discovered assignments cover the exact union and retain distinct +architecture, ordinary and shared-fixture co-membership. Shard counts, salt, +assignment algorithm, quotas and all resource/time ceilings remain unchanged. +Release build passes with zero warnings/errors. The five declaration-only +mutation Facts pass 5/5 locally, and the two wrapped companions pass 49/49, +including all recurrence variants. The remaining twelve moved companions pass +12/12; all 66 cases pass with zero skips. Full runtime and two-layout hosted +qualification remain required; source/body equality is not that proof. + +The full 303-method census, rather than one candidate assignment alone, checks +remaining class serialization. Its maximum complete-observation class envelope +is 617 seconds across all methods in each class; every assigned class plus the +historical fixed-time proxy is below the existing nominal owner window. These +are advisory scheduling diagnostics, not a future wall-time guarantee. The +actual complete A/B runs remain the acceptance witness for hosted fit. + + +### P03-1 PR #38 current-source A/B and ordinary window proposal (2026-10-26) + +**Source and outcome.** Complete run +[40382715371](https://github.com/HodeTech/LearnStack/actions/runs/40382715371) +uses head `7aabc6d8a3e2109a6e6dfa0c439442b0dcd008d9`, actual merge checkout +`2c692b51adc5feb7fb0c843d4124938a61775a7b` and common tree +`217d237966b20215ed25a15d5440c4d05a18717c`. Its frozen plan and manifest are +those recorded in the preceding mutation-collection entry. Attempt 1 selects +literal A; attempt 2 selects literal B. The attempts are retained separately. + +A succeeds in all 27 jobs, with 6,490 .NET passes, zero skips and exact case +unions. All 25 original archives are retained. Independent offline audit by +`pr38_layout_r2_plan` verifies API source/attempt identity, archive size/digest +and CRC, 147 original producer files, production aggregate validation, all twenty +natural execution owners and 27 public JSON/HTML report pairs. This audit is +source-bound A evidence, not a second assignment or a new runtime execution. + +B succeeds in 24 jobs; all Architecture producers and the backend aggregate +pass. Two ordinary producers report `deadline_exhausted`: + +| Producer / actual job | Selected | Completed Passed | No result | +|---|---:|---:|---:| +| [ordinary-3](https://github.com/HodeTech/LearnStack/actions/runs/40382715371/job/121796927865) | 262 | 259 | 3 | +| [ordinary-7](https://github.com/HodeTech/LearnStack/actions/runs/40382715371/job/121796928433) | 267 | 264 | 3 | + +The dependent integration aggregate refuses. Whole B contains 6,484 completed +passing cases and six without results. Both failed producers report forced +cleanup and no proved Docker absence; ownership of forced cleanup is not natural +completion. No assertion failure is observed in completed cases; the censored +cases establish neither a pass nor an assertion failure. All 24 available B +original ZIPs, API metadata and extracted proof are retained under +`artifacts/p031-step6/hosted/40382715371/2/`; A is retained under sibling `1/`. +Raw receipts remain private verification artifacts, not committed source. +No complete current-source A/B qualification is claimed. + +**Decision boundary.** [ADR-0075](../decisions/0075-ordinary-ci-job-window.md) +is Proposed. It recommends only an ordinary Docker whole-job window of +25 minutes, preserving the other ADR-0063 limits. Its Context owns the budget +arithmetic, censored-tail limitation and alternatives. Source-bound complete +A and failed B expose a remaining wall-time limit; more weight tuning is not a +substitute for final-source qualification. No policy or runtime implementation +is authorized by this proposal. Maintainer approval is required because the +maintainer requested review before implementing each new ADR. + +**Acceptance text prepared for ADR-0063 — not appended there while Proposed:** + +> Amendment 1 — Ordinary Docker whole-job window (acceptance date) +> +> The maintainer accepts ADR-0075's bounded supersession of the ordinary +> Docker portion of the Decision sentence, “Each execution keeps its +> twenty-minute whole-job ceiling”, and the execution rule, “Keep each +> twenty-minute ceiling and a finite cleanup/upload reserve.” Ordinary Docker +> producers instead have a twenty-five-minute whole-job ceiling. The +> “No … ceiling increase … is authorized” plan clause remains the prohibition +> on unapproved expansion; this explicitly approved ordinary exception is its +> only change. +> +> All other ADR-0063 decisions remain in force: the existing producer count +> ranges and twenty-VM cap, complete selector ownership and two-layout +> qualification, algorithm/salt/weights/filters, resource ownership/accounting, +> cleanup and upload reserves, all other job ceilings and the seven required names. +> Expected verified producer identity controls the longer interval; a receipt +> cannot choose it. Acceptance authorizes dependent work, not actual hosted +> fit. ADR-0075 and the Phase 03 delivery log own the new decision and its +> implementation/qualification receipts. Historical text and metadata above +> remain intact. + +The amendment number is checked again at acceptance; ADR-0063 currently has no +Amendments section. The acceptance date records actual approval rather than +backdating this proposal. This is a policy change, not an ADR-0041 correction. + +**Three-step implementation plan, pending approval:** + +1. Accept ADR-0075 and append ADR-0063's dated amendment; reconcile Testing 06 + and Infrastructure Stack 20's corresponding ordinary-ceiling statement, + the existing `CI_Test_Shards_Are_Complete_And_Bounded` catalogue Source/Asserts, + the decision index and Phase 03 Status block. Keep the catalogue's prior + implementation distinct from the not-yet-delivered extension. +2. Apply the closed expected-owner budget policy in the ordinary workflow, + launcher, fixture preparation and receipt/API/workflow verifiers named in + ADR-0075. Add positive and counterfactual controls for exact thresholds, + unknown modes, forged partitions, invalid indices and mismatched job identity. + Run the relevant existing Python suites and documentation guards; no test + population, resource policy, assignment or reserve change is included. +3. Qualify two complete fresh same-final-source A/B attempts. Require every + job, exact full discovered unions, zero skips, complete original packages and + natural lifecycle evidence, followed by independent cross-attempt audit. + Retain each attempt before rerunning all jobs. Historical A cannot qualify + the changed policy source. Update closeout and PR evidence only from actual + completed results. + +Every step is committed and receives two fresh independent review rounds; +verified findings are fixed, committed and revalidated before advancing. The +proposal itself receives two fresh document-review rounds before the maintainer +question. No new catalogue rule or Implemented extension is claimed by authoring +this decision package. PR #38 remains open for review and is not merge-qualified. + + +### ADR-0075 proposal review round 1 (2026-10-26) + +Two fresh independent read-only reviewers inspect proposal commit `2d2a6f94`: +`pr38_adr75_r1_source` (GPT-6 Astra, xhigh) checks actual budget authorities and +preserved source contracts; `pr38_adr75_r1_evidence` (GPT-6.1 Sol, high) checks +retained original artifacts, source/assignment identity, arithmetic and decision +instruments. Neither executes .NET, starts services or changes the worktree. + +The source review finds two valid documentation issues: Infrastructure Stack 20 +also carries the twenty-minute statement and must be reconciled at acceptance; +the draft's claimed 3 GB/four-CPU child quotas are absent from the launcher, +which owns processes and accounts CPU/memory without those numeric limits. +Both are corrected: the acceptance list names Standard 20; ADR and package +preserve resource ownership/accounting without adding or claiming quotas. The +reviewer narrowly rechecks and closes both. Its remaining index wording is also +changed from quotas to resource policy. Phase Status explicitly names measured +source `7aabc6d8`, and the count alternative states that it keeps six Architecture +producers. No runtime policy changes result. + +The evidence reviewer independently verifies all 49 original ZIP sizes, SHA-256 +digests and CRCs, producer-file equality, both selected unions and the exact +6,490/6,484 completed outcomes. It recomputes source/tree/plan/manifest identity, +twenty natural A owners and the 997-to-1,297-second arithmetic, with no finding. +The historical 617-second advisory class envelope is outside that reviewer's +reconstruction; it supplies no qualification claim. Root separately rechecks +all archive digests/sizes/CRCs and unique case totals. These are offline evidence +checks, not another hosted run. Fresh second-round review remains required. + + +### ADR-0075 proposal review round 2 (2026-10-26) + +Two different fresh independent read-only reviewers inspect corrected proposal +commit `e50e6d13`: `pr38_adr75_r2_source` (GPT-6.1 Sol, high) traces all +launcher/leaf, API/receipt, workflow and image-preparation budget authorities; +`pr38_adr75_r2_evidence` (GPT-6 Astra, high) independently recomputes the retained +archive/case/source evidence and checks acceptance governance. Both approve with +no remaining concrete finding. Neither edits files, starts services or executes +.NET tests. + +The source reviewer confirms closed expected-owner authority, retained reserves, +other ceilings, counts, runner tier and test-specific deadlines, plus the +Standard 20 and resource-accounting corrections. Only the four proposal/carrier +documents differ from measured code source `7aabc6d8`; no policy implementation +precedes approval. The evidence reviewer independently checks all 49 original +ZIP hashes/sizes/CRCs and extracted-file equality, exact A/B selected and +completed unions, twenty natural A owners, identities and budget arithmetic. +It does not reconstruct the advisory class-envelope analysis or rerun aggregate +validation; those limitations do not become new qualification claims. + +Whole-tree Markdown fragments, roadmap structure, current delivery indexes, +ADR lifecycle parsing and whitespace checks pass. ADR-0075 remains Proposed; +maintainer approval is the next policy gate. After approval, the three-step plan +above still requires actual implementation reviews and fresh complete hosted +A/B. These document reviews do not establish twenty-five-minute fit. + + +### ADR-0075 maintainer review and revised package (2026-10-27) + +**Authority.** The maintainer supplies two review reports against proposal head +`b048412d`; the response requests pre-acceptance clarification rather than +accepting the decision. ADR-0075 remains Proposed. This entry replaces only the +acceptance carrier list and interval clarification in the +[original three-step proposal](#p03-1-pr-38-current-source-ab-and-ordinary-window-proposal-2026-10-26). +Its historical draft and review receipts stay intact. No Accepted ADR, workflow +or executable budget policy changes before approval. + +**Verified disposition against current source:** + +| Finding | Disposition | +|---|---| +| ADR-0062 Amendment 1 still says all execution jobs keep twenty minutes | Valid. Acceptance now owes its own dated ordinary-only amendment in ADR-0062 as well as ADR-0063. Native remains twenty minutes. Both append-ready texts follow. | +| Five minutes could be read as a whole-workflow feedback bound | Valid. ADR-0075 now limits the statement to additional running time per ordinary job; queueing/concurrency determine total feedback delay. | +| B1: twenty-five minutes is a judgement choice | Already disclosed; strengthened to name maintainer acceptance of headroom, with no proved minimum or safe margin. Fresh final-source A/B remains mandatory. | +| B2: A passes, so “failure of both assignments” is not observed | Valid clarification. Reopening follows ADR-0063's separate envelope-exhaustion clause and requirement to qualify both layouts; the proposal claims neither that both fail nor that a change is pre-authorized. | +| B3: continuity with ADR-0063's rejected ceiling option | Valid clarification. The ordinary-only part of its previously valid, unselected alternative is now explicitly named. | +| M1: globally changing `finite_seconds` to 1,500 would weaken other producers | Valid. Observational bounds are supplied only from independently verified expected-owner identity, across receipt and measurement validation. Nonordinary remains 1,200. | +| M1: retain every ordinary measurement at 1,200 | Not adopted. `shard_workload` records its whole worker interval and assembly invocation walls; these are observations under the enclosing job deadline, not separate operation limits. A 1,250-second workload with short pre-owner work can fit 1,500 minus the unchanged 203-second reserve. A separate measurement cap would add a workload policy. Actual test/fixture operation deadlines remain unchanged. | +| M2: fixture preparation shares the launcher's duration source | Valid; explicit single-policy ownership is added. Its total 110 seconds, per-image 55 seconds and two-minute step remain fixed. | +| M3: `verify_jobs` must use expected owner in either aggregate scope | Valid; explicitly stated, including base/native inside integration. A prefix or receipt partition cannot grant the longer window. | +| Owner setup arithmetic provenance | Valid clarification. The ADR names the observed `result.json.setupSeconds` values 0.191/0.198 rather than an unexplained approximate constant. | +| Option 5 and the no-unapproved-increase clause | Clarified together with B1/B2. Neither twenty-two/twenty-three nor twenty-five has measured fit yet; accepting this bounded exception leaves all other expansion unapproved. | + +The M1 distinction is checked against `ci-native-tests.py`'s actual +`shard_workload`, `leaf` and `deadlines`, and `ci-test-shard-results.py`'s +`verify_receipt`/`finite_seconds`. Nested measurement observations are not summed +as extra disjoint time. Only the four disjoint receipt intervals sum below the +verified owner's ceiling. No runtime changes or new deadline semantics are +implemented by documenting this distinction. + +**Revised acceptance text for ADR-0062 — not appended while Proposed:** + +> Amendment 2 — Ordinary Docker execution window (acceptance date) +> +> Accepted ADR-0075 supplies an ordinary-only exception to Amendment 1's +> statement, “All execution jobs keep twenty-minute ceilings”. Verified +> ordinary Docker producers have a twenty-five-minute whole-job ceiling; +> native, base and Architecture execution retain twenty minutes. ADR-0063 +> receives its own dated amendment for the same bounded change. +> +> Native collector authority, excluded-host rules, process/Docker ownership, +> unchanged cleanup/export/upload reserve, complete result requirements and +> the other decisions above remain intact. Expected verified producer identity +> controls the longer observation/whole-job window; no receipt chooses it. +> Acceptance is not implementation or actual hosted fit. ADR-0075 and the +> Phase 03 delivery log own the dependent implementation and fresh two-layout +> qualification receipts. The historical text, metadata and Amendment 1 are +> retained without rewriting. This is a bounded decision change, not an +> ADR-0041 factual correction. + +**Revised acceptance text for ADR-0063 — not appended while Proposed:** + +> Amendment 1 — Ordinary Docker whole-job window (acceptance date) +> +> Accepted ADR-0075 supplies an ordinary-only exception to the Decision's +> “Each execution keeps its twenty-minute whole-job ceiling” and the rule, +> “Keep each twenty-minute ceiling and a finite cleanup/upload reserve.” +> Verified ordinary Docker producers instead have a twenty-five-minute +> whole-job ceiling. This also qualifies the inherited ordinary requirement +> in the Exact relationship to ADR-0062 section; ADR-0062 receives its own +> dated amendment. Native, base and Architecture retain twenty minutes. +> The plan's prohibition on unapproved ceiling increases keeps only this +> explicitly approved ordinary exception. +> +> All other decisions remain in force: producer count ranges and the +> twenty-VM cap, selector ownership and two-layout qualification, +> algorithm/salt/weights/filters, resource ownership/accounting, the +> unchanged cleanup/export/upload reserve, other job ceilings and the +> seven required names. Expected verified producer identity controls the +> longer enclosing interval; a receipt cannot choose it. Actual operation +> deadlines remain unchanged. Acceptance authorizes dependent work, not +> actual hosted fit; the Phase 03 delivery log owns its implementation and +> qualification receipts. Historical text and metadata remain intact. + +Both amendment numbers are checked again at acceptance. Actual acceptance dates +replace the placeholders; they are not backdated to proposal or review dates. + +**Revised three-step plan, pending maintainer acceptance:** + +1. Accept ADR-0075, append the two own-record amendments above and reconcile + Testing 06, Infrastructure Stack 20, the existing CI catalogue Source/Asserts, + decision index and Phase 03 Status. The existing catalogue implementation + does not imply the not-yet-delivered extension. +2. Implement the one closed expected-owner budget policy across launcher/leaf, + fixture preparation, workflow and API/receipt/observation validation. Include + positive ordinary observations above 1,200 within the longer enclosing job, + negative nonordinary/forged-owner controls, unchanged operation caps and + finite/threshold checks. The population, plan, reserve and other boundaries + stay fixed; run the relevant Python suites and documentation guards. +3. Qualify complete fresh same-final-source A and B, retain original packages + before rerunning all jobs, independently cross-audit exact full unions and + natural completion, then update actual closeout and PR evidence. Historical + A or failed B cannot stand in for these new proofs. + +Each step retains commits and two fresh independent review rounds before +advancing. The revised proposal also receives two fresh review rounds before +being returned for approval. Acceptance and executable implementation remain +pending; this package is not new hosted qualification. + + +### ADR-0075 revised proposal review round 1 (2026-10-27) + +Two fresh independent read-only reviewers inspect revision `d5ebab86`: +`pr38_adr75_maintainer_r1_intervals` (GPT-6.1 Sol, high) traces enclosing +measurement/deadline semantics and expected-owner budget authority; +`pr38_adr75_maintainer_r1_docs` (GPT-6 Astra, high) checks the amendment texts, +predecessor decisions, retained boundaries, Proposed status and plan consistency. +Both approve with no remaining actionable finding. Neither changes files, +starts services, executes .NET or reruns hosted jobs or archive validation. + +Both verify the partial M1 disposition against actual instrumentation: worker +and assembly observations can legitimately exceed 1,200 within the proposed +ordinary enclosing budget; a separate cap would add a workload restriction. +Other producers and actual operation deadlines stay unchanged. Both own-record +amendments, native twenty minutes, per-job feedback cost and the explicit +A-passes/B-fails reopening rationale are confirmed. This establishes reviewed +proposal semantics, not maintainer acceptance, implementation or hosted fit. +A fresh second review round remains required before returning the package. + + +### ADR-0075 revised proposal review round 2 (2026-10-27) + +Two different fresh independent read-only reviewers inspect revision `9ba876f3`: +`pr38_adr75_maintainer_r2_source` (GPT-6 Astra, high) traces enclosing execution, +operation caps, observations and counterfactual obligations; +`pr38_adr75_maintainer_r2_docs` (GPT-6.1 Sol, high) checks own-record amendments, +predecessor/standard consistency, status and historical preservation. Both +approve with no remaining actionable finding. + +The source review confirms that a 1,250-second worker/assembly observation can +fit the proposed window when pre-owner/setup work is short, supporting the +recorded partial M1 disposition. Both verify that expected identity, not a +receipt or prefix, selects observational and whole-job bounds; nonordinary, +actual operation caps and the 203-second reserve stay fixed. The corpus review +confirms historical delivery text is preserved and both Accepted predecessor +files, Standards 06/20/21, executable carriers, workflow and plan remain +byte-identical to `b048412d`. Only four proposal/carrier documents differ. + +Whole-tree document/roadmap/index guards, ADR Proposed parsing and whitespace +checks pass. Neither reviewer changes files, starts services, executes .NET, +reruns hosted jobs or repeats archive qualification. This closes the revised +proposal reviews; maintainer acceptance, implementation reviews and fresh full +A/B remain required. No twenty-five-minute hosted fit is claimed. + + +### ADR-0075 acceptance and Step 1 (2026-10-27) + +**Maintainer acceptance.** The maintainer explicitly approves the revised +ADR-0075 and three-step plan at `c274fa6e` with “Revize ADR ve planı +onaylıyorum; uygula”. Acceptance covers the revised interval distinction: +ordinary enclosing observations follow independently verified 1,500-second job +identity; nonordinary remains 1,200, actual operation deadlines and the +203-second reserve stay unchanged. It accepts per-job extra running time and +no overall workflow-delay or hosted-fit guarantee. + +Step 1 records ADR-0075 as Accepted, appends own-record dated amendments to +ADR-0062 and ADR-0063, moves the index row to Active and reconciles Testing 06, +Infrastructure Stack 20, the existing CI catalogue Source/Asserts and Phase 03 +Status. Existing catalogue enforcement stays Implemented; its ADR-0075 extension +is explicitly pending implementation. Historical Accepted bodies/metadata and +prior delivery records remain intact. No workflow, plan or executable budget +changes occur in this step. + +The [revised package](#adr-0075-maintainer-review-and-revised-package-2026-10-27) +is now the accepted three-step implementation authority. Each step receives a +commit and two fresh independent review rounds, with verified fixes committed +and revalidated before advancing. Step 2 implements and locally proves the +closed expected-owner policy; Step 3 requires fresh complete same-final-source +A/B and independent original-evidence cross-audit. Earlier A and failed B remain +historical evidence and do not qualify the changed source. Acceptance is neither +implementation nor actual twenty-five-minute hosted fit. + + +### ADR-0075 Step 1 review round 1 (2026-10-27) + +Fresh independent reviewers `adr75_step1_r1_records` (GPT-6.1 Sol, high) and +`adr75_step1_r1_contract` (GPT-6 Astra, high) inspect `c274fa6e..2a1917cf`. +Both approve with no actionable finding. The records reviewer reconstructs the +predecessor bytes by removing only new amendment blocks and compares both +amendments to the accepted package. Historical delivery text is preserved +outside the generated index. Both confirm the nine-file documentation-only +scope, accepted index/status, pending catalogue extension and separation of +acceptance from implementation/hosted fit. Document, lifecycle and whitespace +checks pass. Neither reviewer mutates files, starts services, executes .NET or +revalidates original hosted evidence. Fresh second-round review remains. + + +### ADR-0075 Step 1 review round 2 and closeout (2026-10-27) + +Fresh reviewers `adr75_step1_r2_records` (GPT-6 Astra, high) and +`adr75_step1_r2_contract` (GPT-6.1 Sol, high) independently inspect +`c274fa6e..7dc3f8b7`; both approve with no actionable finding. Both reconstruct +predecessor bytes, check the accepted amendment texts and verify every carrier +keeps implementation and new hosted fit pending. Historical delivery text is +preserved outside its generated index. Lifecycle, fragments, roadmap/index and +whitespace checks pass. Neither executes runtime tests, starts services or +requalifies archives. Step 1 is complete; Step 2 may now implement the approved +closed policy. This closeout supplies no executable or hosted-fit evidence. + + +### ADR-0075 Step 2 closed budget implementation (2026-10-27) + +One `job_seconds(mode, job, counts)` policy in `ci-native-tests.py` owns the +1,500-second ordinary and 1,200-second other execution windows. It refuses +unknown/prefix/alias modes, wrong job identity and out-of-plan indices. Both +owner and leaf deadlines charge the same pre-checkout clock and retain every +component of the 203-second reserve. No environment budget override is added. + +The result owner uses this same policy for expected-owner API running walls, +workflow topology, four disjoint receipt intervals and enclosing measurement +observations. Receipt identity is bound before selecting its limit. The finite +observation helper requires an explicit verified ceiling; no global widening +or self-declared partition selects ordinary authority. Nonordinary remains +1,200 even inside integration; nested measurement observations are not summed +as additional disjoint work. + +Only the ordinary job ceiling changes to twenty-five minutes. Fixture +preparation now receives the exact matrix mode and the same source/workflow +metadata as execution, validates the real existing identity path before image +I/O, and uses the common budget. Its 110-second total, 55-second per-image and +two-minute step caps stay unchanged. Topology requires the two metadata maps to +agree; real runtime identity still independently rejects corrupted metadata. +The CLI accepts exactly one mode argument for preparation and retains exact +arity elsewhere. Counts, plan, salt, algorithm, population, other job ceilings, +resource policy, protection names and application code remain unchanged. + +**Local validation.** The combined plan/result suite passes 81 controls +(including 38 aggregate controls) in approximately 5.2 seconds under a local +27-second guard, within meta's existing 30-second allocation. The complete real +launcher offline suite passes 89 controls in approximately 22.2 seconds. After +self-review makes the long-observation positive fixture's nested intervals +coherent, the complete combined suite passes again. Counterexamples cover +expected identity, exact thresholds/strict sums, nonfinite/boolean/negative +fields, longer ordinary worker/assembly observations, nonordinary refusals, +preparation context/pull caps and workflow/CLI drift. Topology, Python compile, +document guards and whitespace checks pass. Private logs are under +`artifacts/pr38-review/adr75-step2/`. + +These are offline source/policy controls using disposable seams, not systemd, +Docker lifecycle or hosted-fit evidence. No .NET/application test source or +runtime is changed; fresh full hosted A/B remains Step 3's required witness. +Step 2's two independent review rounds remain before that qualification starts. + + +### ADR-0075 Step 2 review round 1 (2026-10-27) + +Fresh independent reviewers `adr75_step2_r1_source` (GPT-6 Astra, xhigh) and +`adr75_step2_r1_tests` (GPT-6.1 Sol, high) inspect `1d609d30..c2695f2d`. +Both approve with no actionable finding. The source reviewer traces exact +mode/job/index authority, full preparation source/runner identity before Docker, +owner/leaf clock/reserve, expected-owner observation bounds and one-hop +artifact/CLI/failure paths. The tests reviewer confirms preserved controls, +coherent long ordinary positives and meaningful forged-identity/threshold/ +nonfinite counterexamples; it independently reruns all 81 combined controls in +5.010 seconds and all 89 native-owner controls in 23.371 seconds, both passing. +The plan, application/population source and nonordinary limits stay unchanged. +These are read-only source/offline reviews; no services, .NET or hosted +qualification occur. A fresh second round remains before Step 3. + + +### ADR-0075 Step 2 review round 2 and qualification handoff (2026-10-27) + +Fresh independent reviewers `adr75_step2_r2_source` (GPT-6.1 Sol, high) and +`adr75_step2_r2_proof` (GPT-6 Astra, high) inspect `1d609d30..6bb91ede`. +Both approve with no actionable finding. The source reviewer follows identity, +source checks, owner/leaf environment and deadlines, cleanup, CLI and artifact +paths. The proof reviewer verifies meaningful complete-evidence counterfactuals +and preservation of every existing method: launcher 87 to 89, plan 42 to 43, +results 30 to 38. Only ordinary workflow time grows; preparation and operation +caps, reserve, counts, plan, population source and meta allocation stay fixed. +Neither mutates files, starts services or reruns .NET/hosted execution; no +redundant suite rerun is needed after unchanged passing local/R1 controls. +Document/whitespace checks pass. Step 2 is complete. + +**Step 3 handoff.** Freeze this reviewed source and push it for a complete A +attempt. Preserve the original current-attempt API metadata and all producer, +aggregate and auxiliary packages before a full rerun for literal B. Both must +use the same head/merge source, plan, toolchain and complete 6,490-case population, +with every job successful, exact disjoint unions and twenty natural owners. +Only then can independent two-round evidence review close Step 3. No current +hosted-fit claim follows from this handoff; all earlier source receipts remain +historical. + + +### ADR-0075 Step 3 fresh hosted A/B evidence (2026-10-27) + +**Qualified implementation source.** +[Run 40412041726](https://github.com/HodeTech/LearnStack/actions/runs/40412041726) +executes head `ea114d25266d7db7729d276c07d0011a7ba180fd` and actual merge checkout +`c633763c0a8fb086c1f8fd09231075e8149da1c4`. Their common tree is +`53daaf89c9527ccf370f108ef8dfb0f7bca8edfe`. These hashes identify different +commits with equal trees. The same source, plan, manifest, toolchain and image +identities qualify both attempts; no code, weight or assignment change occurs +between them. A is attempt 1; B is a full rerun, attempt 2. + +| Actual evidence | A | B | +|---|---:|---:| +| Successful jobs | 27 / 27 | 27 / 27 | +| Passing .NET cases; zero skips | 6,490 | 6,490 | +| Exact backend / Docker union | 3,664 / 2,826 | 3,664 / 2,826 | +| Ordinary / native cases | 2,795 / 31 | 2,795 / 31 | +| Original immutable archives retained | 25 | 25 | +| Natural complete execution owners | 20 | 20 | +| Public JSON/HTML report pairs | 27 | 27 | +| Maximum execution-producer API wall | 938 seconds (ordinary-2) | 1,058 seconds (ordinary-11) | + +A's original API metadata and packages are retained and production-validated +before requesting B with Re-run all jobs. GitHub's latest artifact listing after +B contains only B's packages; the retained original A snapshots and ZIPs are +therefore necessary, not reconstructed from B or job logs. Private originals, +producer files and verification receipts live under +`artifacts/p031-step6/hosted/40412041726/{1,2}/`. Short-lived download URL files +are removed after acquisition. No runner environment or execution is simulated. + +The production validators independently recompute each attempt's exact selected +and completed/TRX unions from actual immutable packages and API jobs. Root also +checks all fifty ZIP sizes, SHA-256 digests and CRCs, producer-file equality, +source/attempt/toolchain/images, natural completion and all public report +JSON/HTML digest pairs. The six IDs missing from the preceding twenty-minute B +all complete Passed in the new B; historical failed evidence remains unchanged. + +Actual A/B co-membership differs in both directions: Architecture has 6,203 +A-only and 6,915 B-only method pairs; ordinary has 62,463 / 65,656; SharedSchema +methods within its actual 85-class collection have 40,173 / 42,648. The wider +131-class fixture-bearing plan census has 62,165 / 65,388. These are materially +different complete assignments, not bin renumbering. The plan remains +`115e474202360d0d7d99e1a8c69a0b40f7eb84669364b23ce90c94341969113b` and manifest +`8d017042f7e439273a7164326d9a1ae7ef3ea4ea3dea9a1bfa4c315a133bef21`. + +This establishes observed fit for the exact implementation source and two +assignments, not a measured minimum, a future fit guarantee or a five-minute +whole-workflow delay bound. Every other ceiling, reserve, operation cap, VM +count and natural-cleanup requirement remains unchanged. The documentation +closeout has its own later commit identity and must pass normal current-head +protected checks; these execution receipts are never relabelled as that commit. +Step 3's two fresh independent evidence-review rounds remain before closeout. + + +### ADR-0075 Step 3 review round 1 (2026-10-27) + +Fresh independent reviewers `adr75_step3_r1_archives` (GPT-6.1 Sol, high) and +`adr75_step3_r1_lifecycle` (GPT-6 Astra, high) inspect evidence record `0db4b42f` +and original run 40412041726 attempts 1/2 for implementation source `ea114d25`. +Both approve with no actionable finding. They do not trust prepared summary +JSON as authority: original API metadata, ZIPs, producer files and public report +contents supply their checks. + +The archive reviewer freshly extracts all forty producer archives through the +production safe unpacker, verifies 147 byte-identical producer files per +attempt, recomputes both production aggregate scopes and checks API job/artifact +bindings. Both reviewers verify all fifty archive sizes/SHA-256/CRCs, exact +6,490-case selected/completed/TRX unions, twenty natural owners per attempt, +all thirteen Docker-owner absence flags, native confinement/core/crash evidence, +source/merge parents/tree, toolchain/images, plan/manifest and actual different +co-membership. Both confirm the six previously missing exact IDs now pass. + +The lifecycle reviewer additionally checks all 54 public JSON/HTML pairs across +A/B against digest, URL/run/source/build identity, full configured inventory, +category weights, accessibility/JS/CLS gates and successful cleanup. Expected +producer budgets hold, maxima are 938/1,058 seconds, and meta/aggregates remain +below 300 seconds. Original acquisition ordering is corroborated by filesystem +birth times (last A archive 22:49:25 UTC; verification 22:49:28; B starts +22:50:09) and the contemporaneous tool-call sequence; those local timestamps are +not independently signed chronology. Neither reviewer reruns hosted work, +starts services or changes repository files. This qualifies observed evidence, +not a minimum ceiling or future fit. Fresh second-round review remains. + + +### ADR-0075 Step 3 review round 2 correction (2026-10-27) + +Fresh independent reviewers `adr75_step3_r2_union` (GPT-6 Astra, high) and +`adr75_step3_r2_public` (GPT-6.1 Sol, high) inspect record `146f743b` and the raw +A/B packages for qualified source `ea114d25`. Both verify the hosted +qualification; the union reviewer finds one minor documentation error before +this closeout is shipped. The earlier draft labels the plan's wider 131-class +fixture-bearing pair count as SharedSchema. Root independently reproduces both +populations: fixture-bearing pairs are 62,165 / 65,388, while the actual +85-class SharedSchema collection has 40,173 / 42,648. The unshipped Step 3 record +is corrected to report both; prior reviewed revisions remain in git history. +No source, plan, package, execution or qualification result changes. A narrow +post-fix check remains before final closeout. + +Both reviewers independently check all fifty original ZIP sizes/SHA-256/CRCs, +fresh producer files and API/attempt/source bindings; exact complete A/B +selected/completed/TRX unions and natural lifecycle evidence pass. The public +reviewer additionally verifies all 54 JSON/HTML pairs, embedded LHR identity, +complete configured audit inventories/category weights, accessibility score 1, +JS payload below 200,000 bytes, CLS 0, TLS/timeout refusals and cleanup. It +recomputes meta/backend/integration aggregate walls: A 113/22/29 seconds; +B 88/18/38, all below 300. The six historical missing IDs pass in both new +attempts. Proof limits remain explicit: actual source qualification is not +later documentation-head qualification, signed acquisition chronology or a +future fit guarantee. No reviewer edits the repository, executes .NET, starts +services or reruns hosted work. + + +### ADR-0075 three-step closeout (2026-10-27) + +All three approved steps and both independent review rounds per step are +complete. Step 1 records maintainer acceptance, each predecessor's own dated +amendment and current carriers. Step 2 supplies one verified expected-owner +policy for ordinary-only twenty-five-minute whole-job/enclosing observations, +with 81 combined plan/result and 89 launcher controls. Other ceilings, the +203-second reserve, operation caps, plan, counts, population and resource policy +stay unchanged. + +Step 3 qualifies implementation source `ea114d25` / actual merge `c633763c` +with complete run 40412041726 A/B: each 27 successful jobs, 6,490 Passed cases, +zero skips, twenty natural owners and 25 original archives. All fifty originals +and exact API/result/public/lifecycle evidence are retained and independently +recomputed in two fresh review rounds. The historical six missing IDs pass in +both attempts. Observed producer maxima are 938/1,058 seconds; these establish +neither a minimum ceiling nor future fit. + +R2's one minor evidence-label finding is fixed in `468e9c65`. The original +reporter `adr75_step3_r2_union` and the public/lifecycle reviewer narrowly +recheck and approve the corrected 85-class SharedSchema versus 131-class +fixture-bearing populations; no actionable finding remains. No code, plan, +package or execution changes after qualification. Whole-tree document/index/ +roadmap/lifecycle and whitespace checks pass. + +This later documentation closeout has a distinct commit identity and is not +relabelled as the executed source. Its normal current-head protected checks +remain mandatory before merge; actual results belong to that check run rather +than a prediction here. PR #38 remains open for maintainer review and merge. +No merge is performed. P03-2 is not started; P03-3 still owns new-user HTTP/BFF +activation. This CI correction changes no application authority or deployment. diff --git a/docs/roadmap/phase-03-identity-admin.md b/docs/roadmap/phase-03-identity-admin.md index 6418ca781..f74d5afd8 100644 --- a/docs/roadmap/phase-03-identity-admin.md +++ b/docs/roadmap/phase-03-identity-admin.md @@ -1,9 +1,46 @@ # Phase 03: Identity Domain, Authorization, and Admin Foundation +> **Status (2026-10-27).** Entry preparation and P03-1's joint ADR approval +> are complete. P03-1's six implementation steps and both review rounds are +> complete; its implementation source has passed complementary full A/B +> qualification ([Step 6 closeout](phase-03-delivery-log.md#p03-1-step-6-qualification-closeout-and-pr-handoff-2026-10-26)). +> [PR review corrections](phase-03-delivery-log.md#p03-1-pr-38-review-corrections-2026-10-26) +> are committed with both independent review rounds complete. Correction source +> `7aabc6d8` passed A but left B incomplete. After accepted +> [ADR-0075](../decisions/0075-ordinary-ci-job-window.md), implementation source +> `ea114d25` passes fresh full A/B; the +> [three-step correction](phase-03-delivery-log.md#adr-0075-three-step-closeout-2026-10-27) +> and both independent review rounds per step are complete. Qualification is +> source-bound to `ea114d25`; later documentation heads retain their own normal +> protected checks before merge. PR review and merge remain required. The +> [ADR-0074 timing delta](../decisions/0074-membership-admission-under-ordered-locks.md) +> is Accepted; existing-binding API admission is implemented. This is the current +> critical-path phase after +> [Phase 02b](phase-02b-events-auth.md). +> The [decision register](#the-decision-register) owns gate state; +> the [P03-1 acceptance](phase-03-delivery-log.md#p03-1-joint-acceptance-and-step-1-2026-10-25) +> authorizes its six-step implementation. +> Dated records live in the [delivery log](phase-03-delivery-log.md). +> +> | Packet | Title | State | +> |---|---|---| +> | P03-0 | Entry preparation | Complete — [reconciliation](phase-03-delivery-log.md#entry-preparation-2026-10-25) | +> | P03-1 | Identity authority and membership foundation | Implemented; PR review/merge pending — [six-step closeout](phase-03-delivery-log.md#p03-1-step-6-qualification-closeout-and-pr-handoff-2026-10-26), [review corrections](phase-03-delivery-log.md#p03-1-pr-38-review-corrections-2026-10-26) and [ADR-0075 closeout](phase-03-delivery-log.md#adr-0075-three-step-closeout-2026-10-27); source `ea114d25` passes fresh full A/B, both independent review rounds per step complete; normal current-head protected checks remain mandatory; HTTP/new-user BFF activation belongs to P03-3 | +> | P03-2 | Live membership and authorization | Not started | +> | P03-3 | Protected Studio and membership administration | Not started | +> | P03-4 | Invitations and bounded delivery | Not started | +> | P03-5 | Custom fields and privacy classification | Not started | +> | P03-6 | Provider event ingress and audit mirror | Not started | +> | P03-7 | Back-channel session revocation | Not started | +> | P03-8 | Tenant federation | Not started | +> | P03-9 | Platform authority and operational recovery | Not started | +> | P03-10 | DSAR and global account closure | Not started | +> | P03-11 | Exit enforcement | Not started | + ## Goal -Build LearnStack's identity domain (users, memberships with triple-key -`(user_id, tenant_id, organization_id)`, roles, permissions, invitations) on top of +Build LearnStack's identity domain (global users, contextual memberships, roles, +permissions and invitations) on top of the Keycloak OIDC integration delivered in [Phase 02b](phase-02b-events-auth.md), and ship the first admin experience. @@ -18,11 +55,9 @@ The audit module and its capture pipeline were wired in [Phase 02a Packet 9](phase-02a-kernel-tenancy.md). This phase delivers the LearnStack-side identity domain on top of those primitives. -This phase also settles a question the corpus has been carrying unanswered: **which -identity data belongs to a tenant and which belongs to the person**. Every earlier -phase could avoid it because no tenant admin could write a person's attributes yet. -From this phase forward one can, and the answer has to exist before the first custom -field is stored. +The [ownership boundary](#tenant-data-ownership-dsar-boundary-and-pii-classification) +keeps global identity separate from tenant-authored data. This phase makes that +boundary executable before a tenant admin can write a person's attributes. **P02b-5 handoff — 2026-10-19.** [ADR-0064](../decisions/0064-tenant-api-authentication-boundary.md) delivers only @@ -52,27 +87,118 @@ packet, before that currently unreachable path becomes exposed. ## Scope +### Packets and decision gates + +Each packet is independently reviewable and mergeable. Its decision pass +re-verifies the current code, corpus and pinned provider before accepting its +coupled gates, per [Decision Timing](README.md#decision-timing). A migration, +provider attribute writer or dormant adapter is a first writer too; route +activation is not the only decision boundary. + +| Packet | Result | Dependencies | Gates before the first affected writer | +|---|---|---|---| +| P03-0 | Reconciled plan, packet boundaries, decision register and proof ownership | Completed 02a/02d/02b | Documentation preparation only; no new runtime authority | +| P03-1 | Durable identity storage/common creation authority, existing-binding admission, membership/profile/role foundation and fixed seed adoption; no new HTTP | P03-0 | G1, G2 contract, G3, G4 storage/issuance implications, G5 schema/bootstrap, G19; resolve any invitation/closure invariant that changes these first tables under G8/G16 | +| P03-2 | Live membership, permission registry/behavior, runtime default-deny gate, scoped reads and audit enrichment | P03-1 | G2 execution, G5 enforcement, G6 policy ordering, G7; complete denied controls before protected activation | +| P03-3 | Bounded authenticated web operations, new-user bootstrap/no-session entry, tenant/org switching, member/role screens, organization endpoints and defined member settings | P03-2; production onboarding also waits for P03-9 | G1 activation, G4 transition, G6 transport/UI, G5 delegation; retain existing AccountSite ceiling | +| P03-4 | Secure new/existing invitee acceptance, revocation/resend and usable bounded delivery | P03-1–3 | G8; G1 supplies bootstrap; move delivery/provider gates earlier if this mechanism requires them | +| P03-5 | Customization-owned field definitions, revision-aware values, definition editor and membership form | P03-2–3 | G9; G19 covers diagnostic/PII baseline before any earlier personal-data writer | +| P03-6 | Authenticated durable provider ingress and attributed, deduplicated Audit mirror | P03-1–2 | G10; G13 before any privileged/global intake the chosen mechanism requires | +| P03-7 | Registered, authenticated back-channel logout with bounded provider/session indexes | P03-3 | G11; provider event mirroring is a distinct contract, not a prerequisite by filename | +| P03-8 | Usable tenant SAML/OIDC configuration with safe linking and recovery | P03-3 | G12; G1/G4/G5 still bound issued identity and authority | +| P03-9 | Admitted Platform gate, production first-admin/issuer-rebind authority, killswitch, fenced recovery and dashboard | P03-2 | G13, G14; privileged execution remains closed until this contract ships | +| P03-10 | Subject-scoped DSAR, usable export, tenant erasure and separately authorized global closure/redaction | P03-3, P03-5, P03-9 | G15, G16; G10 only if this workflow consumes provider ingress; integrate all applicable delivered stores | +| P03-11 | Complete source-bound evidence, gateway scaffold correction and analyzer escalation | All implementation packets | G17, G18; no pending mandatory deliverable or unqualified production subject | + +The table is a dependency plan, not a total execution order. Federation does not +gate platform recovery; back-channel revocation does not require the Audit mirror. +P03-1 decides shared schema implications without implementing later workflows. +The maintainer places new-user HTTP bootstrap and BFF entry in P03-3. G1/G6 +requires provider registration policy, durable creation admission, explicit +session/no-session completion and exact transport outcomes before activation. +P03-1 qualifies the common storage/audit owner and fixed seed adoption, while +existing-session API admission remains route-independent. It opens no new route. +Do not create Invitation, custom-field or DSAR tables there merely for convenience. +If a chosen mechanism needs a later packet's capability, close that gate and +deliver the minimum prerequisite before its first consumer; never introduce a +forward dependency or silently broaden an earlier packet's authority. + +#### The decision register + +Contract answers use an ADR or bounded dated disclosure where an existing +Accepted record is affected. A changed decision requires its own superseding +record; an existing interface or historical example is not acceptance. Detail +lands in its owning standard/module spec and the packet's dated decision package. +Do not reserve amendment numbers in advance. Split gates close only for the +named part, and the register links each explicit acceptance and vehicle. + +| Gate | Question | Existing boundary / required answer | First consumer | Vehicle | Status | +|---|---|---|---|---|---| +| G1 | Who establishes issuer + opaque `sub` → stable `UserId` and proves actor association before an accepted login? | Preserve seeded/provider IDs, reject substitution/email merging, name trusted pre-membership admission, first User-writer audit attribution, concurrency and cross-system reconciliation; self-registration alone grants no membership/session; new-user HTTP activation also requires provider registration and durable creation budgets | P03-1 storage/seed; P03-3 activation | Identity authority ADR; bounded ADR-0064/0070 disclosures if affected; Identity spec | Accepted foundation; P03-3 activation Open | +| G2 | How do membership and permission readers reach data before resolved tenant SQL exists, and how does authorized `app.scope` reach EF/RLS? | Decide exact principal, grants, candidate-scope read and transaction/setter ownership before schema; implement step-5/step-6 handoff later; rows 6/9 still need live authorization; qualify rows 7/10/14 and successful claim-only header-mismatch evidence separately from host-tenant budgets | P03-1 contract; P03-2 execution | ADR-0036/0040 authority; Security/Database standards and closed-set tests | Accepted contract; P03-2 execution Open | +| G3 | What are membership/profile/role-binding boundaries, nullable natural keys, lifecycle and global-user projections? | Decide active uniqueness, tenant/org grant composition, profile granularity, archive/reinvite and last-admin/org invariants, same-module composite FKs and Tenancy lifecycle contracts; no cross-module Organization FK/join | P03-1 | Identity module spec; ADR for aggregate/ownership changes; database class declaration | Accepted foundation and [ADR-0074 timing delta](../decisions/0074-membership-admission-under-ordered-locks.md); foundation and per-act lifecycle proofs implemented/reviewed in Step 4; archive/closure transition activation remains P03-3/10 | +| G4 | How are active tenant/org claims issued per session, discovered and switched safely? | Current mappers use user-global attributes and ordinary BFF refresh preserves scope; decide storage implications first, then token reissue, callbacks/hosts, no-membership entry and switch/logout/refresh races | P03-1 implications; P03-3 transition | Provider/session ADR and applicable ADR-0070 disclosure; auth architecture | Accepted storage boundary; P03-3 transition Open | +| G5 | What identifies a scoped permission, who may delegate it, and when do revocations take effect? | Reconcile disabled-default versus Tenant Admin seed expansion; decide registry shape, closed-role defaults, bootstrap/recovery, grant ceilings, last-admin concurrency, finite SystemActor permissions, anonymous Portal Public and API/UI freshness | P03-1 schema/bootstrap; P03-2 enforcement; P03-3 UI | ADR-0017/0064-derived permission contract; Standard 19 and module matrices | Accepted foundation; P03-2 enforcement Open | +| G6 | Which protected endpoint/application policies and native web/SDK operations are admitted? | Decide denial precedence/resource lookup first; then exact routes/methods, Origin/CSRF, input/deadline/no-store bounds, ETag/conflict, actor/scope-bound idempotent replay and cache cleanup; no generic proxy or Server Action implied | P03-2 policy ordering; P03-3 transport | API/BFF contract; ADR-0064/0070/0071 disclosures if affected; Standards 04/07 | Accepted P03-3 staging; policy/transport decisions Open | +| G7 | Who audits HTTP/application/resource denials and supplies trusted actor/request context? | One evidence owner per refusal, MUST sensitive reads, membership/role/platform/operator/route provenance, trusted IP and bounded user-agent; preserve refusal on audit failure; no generic ADR-0065 budget | P03-2 | ADR-0033/0044; Audit spec, enrichment port and matrices | Accepted global creation slice; denials/reads Open | +| G8 | What makes invitation acceptance and delivery authoritative and recoverable? | Verified current provider email, hashed single-use token, GET inspection only, explicit mutating act, current delegation, accept/revoke/expiry/resend races, aggregate atomicity and bounded delivery independent of Phase 08a | P03-1 only if shared aggregate shape changes; P03-4 writer | Invitation contract; ADR-0042 successor if an exception changes; phase package and delivery handoff | Open | +| G9 | How do field definitions and values preserve schema/classification history? | Decide revision pins/active uniqueness, scalar-field compatibility with the existing admitted object profile, nested data, required/default/retire/reclassify/key-reuse behavior, consent and supported localized forms; no raw JSONB bypass | P03-5 before its schema | Customization/privacy contract; ADR-0043 disclosure or successor if needed; module specs | Open | +| 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 | Open | +| 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 | Open | +| G12 | How is realm-level tenant federation confined and safely activated? | Provider ownership, write-only credentials, bounded egress, linking/verified-email trust, MFA assurance, test/activate/rollback and last-login recovery; email/broker claims alone grant no membership | P03-8 | Identity-provider contract under ADR-0004/0064; permission/audit matrices | 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 | Open | +| G14 | Which dashboard/replay/job-recovery transitions and grants are allowed? | Separate producer reset from targeted subscriber replay; exact permission, reason, stale fences, MUST result audit and runbook; immutable facts and uncertain external reservations survive; dated ADR-0015 disclosure before dashboard admission | P03-9 operational writer | ADR-0046/0047 recovery contract; ADR-0015 disclosure and bounded migrations | Open | +| G15 | Who may request which person's data in which tenant/org scope and for which recipient/purpose? | Separate self/admin/delegate authority, subject predicates and org boundaries; category is not disclosure authority; resolve third-party data, holds, eligibility and post-erasure status access | P03-10 request writer | Data Protection/Identity request contract and module matrices | Open | +| G16 | How do exports, closure and privileged redaction finish durably? | Decide artifact delivery/reauthorization/expiry, job/storage prerequisites, participant inventory/write fence, last-membership case and provider finalization; exact erasure grants/order/immutable references, user-reference locators and result-audit/inbox reconciliation | P03-1 only for shared closure-fence invariants; P03-10 workflow | Data Protection and ADR-0044/0046 privileged contract; migrations, module participation and phase package | Accepted shared fence; P03-10 workflow Open | +| G17 | Which real production subjects and product journeys prove complete phase exit? | All deliverables/criteria, inherited catalogue clauses, no skips/empty censuses, real provider/native/app-role paths, manual accessibility and complete source-bound CI; analyzer escalation stays at exit | P03-11; packets retain their own proof | Phase package, evidence index, catalogue and existing test owners | Open | +| G18 | Which gateway scaffold corrections ship without activating the gateway? | Apply Architecture 30 Rules 1–3: explicit version paths/priorities and separated credentials; retain disabled OIDC; reviewed per-public-read allowlist, lint and activation stay Phase 11 | P03-11 config writer | Phase package and Architecture 30; ADR-0035 trigger unchanged | Open | +| G19 | How is personal-data classification and diagnostic redaction established before the first identity writer? | Census current PII-bearing subjects and missing-annotation control; distinguish snapshot markers from logs/errors; fixed descriptors and value canaries, including arbitrary nested values; custom-field history remains G9 | P03-1 first personal-data writer; P03-5 extends it | Data Protection, ADR-0044/0057 boundaries and module PII/audit specs | Accepted; current/global/contextual model classification and actual Identity diagnostic sink controls implemented and reviewed; custom-field history remains G9 | + +### Entry and activation boundaries + +- P03-1 opens with G1/G2/G3/G19 and the schema-affecting parts of G4/G5. + Resolve G8/G16 in that pass only where a different answer changes those tables. +- If bootstrap requires provider ingress, privileged access or a new global-audit + path, the affected G10/G13/G7 part also closes before that first writer. Move its + minimum implementation earlier; an unresolved tenant or future packet grants + neither an audit exemption nor an implied bypass. +- A gate's question remains Open until explicit acceptance links its vehicle. + Preparation does not replace the packet's decision pass or authorize code. +- Preserve the closed tenant bearer profile, AccountSite host ceiling, public + anonymous reads, canonical pipeline, four-role model and existing setter set + until the relevant bounded decision and enforcement ship together. +- New Identity/global tables declare their database class, principal and grants; + calling a table global does not make an app-role directory or platform bypass. +- A packet adds its module specification, permission/audit matrix and catalogue + subjects with its first implementation; no test-only subject establishes a + production capability. Do not invent module-loader interfaces from sketches. + ### Identity Model -- `User` — global identity mirrored from Keycloak (`sub`, canonical email, global - display name). One row per human across the whole platform. -- `Membership` — per-tenant **and per-organization** relationship; triple key - `(user_id, tenant_id, organization_id)` per - [ADR-0017](../decisions/0017-tenant-organization-hierarchy.md). Carries roles. A user - can hold memberships in multiple tenants and in multiple organizations within one - tenant. -- `MembershipProfile` — the tenant-owned profile record attached to a `Membership`: - per-tenant display name, tenant-visible contact fields, locale preference, - per-tenant consent flags, and the tenant-defined `custom_fields` JSONB column. -- `Role` — Platform / Tenant / Organization-scoped per the scope catalogue in - [Permission Standards](../standards/19-permissions.md). -- `Permission` — fine-grained capability inside a role with an explicit scope - (Platform / Tenant / Organization). -- `Invitation` — pending membership offer, bound to email + tenant + organization. - -The aggregate previously named `UserProfile` is split by the ownership rules below: the -attributes a person owns stay on `User`, and everything a tenant authors moves to -`MembershipProfile`. There is no single profile aggregate straddling both. +The accepted [Identity module contract](../modules/identity/README.md#aggregate-and-storage-contract) +owns exact tables, keys, lifecycle and contained state: + +- `User` is the permanent global application binding under + [ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md), without an + email/verification or unused global-profile mirror. P03-1 supplies fixed seed + adoption and existing-binding admission; new-user HTTP/BFF entry remains P03-3. +- `Membership` is a contextual root with a stable ID, current null-safe natural + uniqueness, a contained profile and assignments. Revoked memberships retire; + rejoin creates a successor under + [ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md). +- `MembershipProfile` holds contextual display name and locale preference. P03-3/G6 + decides self/admin DTOs; P03-5/G9 owns dynamic fields and revision history. + No dormant contact/custom-field column or editable consent Boolean is admitted. +- `Role` is a tenant-wide template with Tenant or Organization capability scope; + assignments derive exact organization authority from Membership. Platform + authority remains P03-9/G13. +- Permission definitions and finite foundation grants belong to + [Permission Standards](../standards/19-permissions.md#identity-foundation-contract). +- `Invitation` remains a P03-4/G8 membership offer; its first writer requires that + packet's accepted contract. + +There is no global `UserProfile` aggregate. Tenant-authored profile data belongs +inside Membership; later mirrors and workflows require their named gates. > **Audit ownership.** The `AuditEntry` aggregate lives in the **Audit** module, not in > Identity. Identity's commands flow through the shared `AuditLogBehavior`, and @@ -93,52 +219,30 @@ attributes a person owns stay on `User`, and everything a tenant authors moves t > / archive at tenant-admin scope, under `tenancy.organization.*` ([Permission > Standards](../standards/19-permissions.md)) — authored in > `LearnStack.Modules.Tenancy.Application` against the Packet 6 aggregate. Only the -> owning module moved; the phase did not. Phase 06 builds the org switcher and the list -> / detail / create UI on top of them. +> owning module moved; the phase did not. This phase builds the organization switcher. +> Phase 06 builds organization list / detail / create UI on these endpoints. +> G3/G5 settle the org-admin own-org variant before exposing it; the tenant-wide +> read hatch does not widen organization UPDATE/DELETE authority. ### Tenant Data Ownership, DSAR Boundary, and PII Classification -The corpus currently conflates the global `User` aggregate with tenant-owned profile -data, and three concrete defects follow from it: - -- **Custom fields on `User` leak across tenants.** - [Tenant Customization Model § Custom fields on built-in entities](../architecture/32-tenant-customization-model.md) - adds `custom_fields jsonb` to the `users` table and lets a `TenantCustomFieldDef` with - `target_entity = "User"` write into it. `users` is a global table with no - `tenant_id`, no query filter and no Row Level Security policy. A learner enrolled in - a language school and a yoga studio would carry both tenants' fields in one blob that - both tenants read. -- **A tenant-scoped data request needs separate authority from global closure.** - [Data Protection](../architecture/23-data-protection.md#right-to-erasure-right-to-be-forgotten) - separates those workflows. This phase implements that boundary: invalidating - Keycloak from a tenant-admin request would destroy an identity other tenants - actively use. -- **JSONB columns carry no PII metadata.** Data Protection requires every aggregate to - declare a PII category and claims a CI check over columns named like `email` or - `phone`. A `custom_fields` blob is one column whose keys are authored by tenants at - runtime; column-level classification cannot see inside it. Retention, export and - redaction are therefore undefined for exactly the data most likely to be personal. - -This phase resolves all three. One marking the audit capture is waiting on is sequenced -by the first writer rather than by this phase. `[PiiSensitive]`, the capture's redaction -marker ([ADR-0044 § 8 and Amendment 4 § 1](../decisions/0044-audit-write-path.md)), is -on no property as of Phase 02a Packet 9, because no shipped aggregate holds personal -data. `TenantSetting.Value` — a tenant-authored document on a MUST-class operation, -whose whole value the marker would replace — is the first candidate. Whether it carries -the marker is decided before the first command writing `tenant_settings` lands, -whichever phase ships it. [Phase 02d](phase-02d-walking-skeleton.md) plans that command, -so the question is G17 in -[Phase 02d's decision register](phase-02d-walking-skeleton.md#the-decision-register), -answered in the decision pass of the packet that ships it, per -[Roadmap § Decision Timing](README.md#decision-timing). If Phase 02d stops shipping the -command, the decision returns to this phase. - -**Decision update — 2026-10-02.** The [accepted P02d-2 G17 -answer](phase-02d-delivery-log.md#p02d-2-accepted-answers) selects whole-value -`[PiiSensitive]` for generic `TenantSetting.Value` before its first writer; P02d-2 Step -2 implements both the marker and the bounded branding writer. This phase still owns -identity-backed access, DSAR and the marketplace purpose/recipient boundary; a public -theme allowlist never permits exporting arbitrary tenant settings. +The [Customization model](../architecture/32-tenant-customization-model.md#5-custom-fields-on-built-in-entities) +already places membership fields on `membership_profiles`, never global `users`. +The [Data Protection boundary](../architecture/23-data-protection.md#right-to-erasure-right-to-be-forgotten) +already separates tenant requests from global closure. This phase implements both. + +The [Data Protection classification census](../architecture/23-data-protection.md#identity-foundation-and-classification-ownership) +enforces explicit declarations for every mapped EF scalar property, with a +planted neutral-name omission control. SQL-only, control and vendor stores retain +their separate inventories. Dynamic-value classification additionally needs +revision-aware definitions under G9; the census does not infer PII from stored +text or authorize disclosure to a recipient. + +The [accepted P02d-2 G17 answer](phase-02d-delivery-log.md#p02d-2-accepted-answers) +and its writer already supply whole-value `[PiiSensitive]` on `TenantSetting.Value`. +This phase consumes that baseline for identity-backed access and DSAR; a public +theme allowlist never permits exporting arbitrary tenant settings. Marketplace +purpose/recipient decisions remain subject to the Proposed boundary below. **Attribute ownership.** Each attribute has exactly one owner, and the owner determines the table it lives in and who may write it. @@ -147,19 +251,21 @@ the table it lives in and who may write it. |---|---|---|---| | Provider credentials, MFA factors, token issuance | Keycloak | Keycloak realm `learnstack` | Keycloak only | | BFF token custody | Native web session owner | Process-local store under [ADR-0070](../decisions/0070-owned-tenant-bff-sessions.md) | The closed BFF owner only | -| `sub`, canonical email, email-verified flag | Keycloak | mirrored onto `users` | The mirror handler only | -| Global display name, avatar, preferred UI locale, global account status | The person | `users` | The person; platform admin under an audited `EnterPlatformAdminScope(reason)` | -| Roles and permissions inside a tenant | Tenant | `memberships` | Tenant / organization admin of that tenant | -| Per-tenant display name, contact fields, consent flags, locale preference | Tenant | `membership_profiles` | Tenant / organization admin of that tenant, and the person within that tenant | -| Tenant-defined custom fields | Tenant | `membership_profiles.custom_fields` | Tenant / organization admin of that tenant | +| Global application binding and admission lifecycle | Identity under [ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md) | `users` and the deployment authority under the [Database contract](../standards/05-database.md#identity-storage-contract) | Admitted creation owner; global closure remains P03-10/G16 | +| Canonical provider email/verification mirror, if selected | Provider source | No P03-1 mirror storage; P03-6/G10 or an earlier proven consumer decides fields/source/freshness | Its separately admitted mirror owner; never email-based identity merging | +| Roles and permissions inside a tenant | Tenant | Membership/role bindings under G3/G5 | Admin within the decided delegation ceiling and scope | +| Contextual display name and locale preference | Tenant / membership context | Contained `membership_profiles` under the [Identity contract](../modules/identity/README.md#lifecycle-profile-and-admission) | Closed seed owner; P03-3/G6 decides self/admin edits | +| Consent evidence | The person for the stated purpose | Append-only contract in [Data Protection](../architecture/23-data-protection.md#consent-management) | G3/G9 decide references and authorized capture; a profile edit cannot fabricate consent | +| Tenant-defined custom fields | Tenant | P03-5/G9 decides revision-aware Membership values; no foundation column | P03-5/G9 decides authorized writers | | Learning behaviour (progress, attempts, attendance) | Tenant | per-module tenant-owned tables | The owning module | Two rules make the table enforceable: - **`users` carries no `custom_fields` column and no tenant-authored column of any - kind.** A `TenantCustomFieldDef` whose `target_entity` is `User` resolves to - `membership_profiles`, not to `users`. The field is defined once per tenant and - stored once per membership. + kind.** The supported target is `Membership`, with values in + `membership_profiles`. `User` is not a new-write target. G9 must explicitly + identify any legacy label/migration input before accepting it; it never stores + a value on `users`. Definition revisions preserve existing value interpretation. - **`MembershipProfile` is `[TenantOwned]` and `[OrganizationScoped]`**, with an EF global query filter and a Row Level Security policy built from the canonical template in [Database Standards](../standards/05-database.md). It is an ordinary tenant table @@ -179,22 +285,28 @@ by this note. | Request | Initiated by | Scope | Effect on other tenants | |---|---|---|---| -| Tenant-scoped export | Tenant admin, or the person acting inside that tenant | Rows where `tenant_id = ` | None | -| Tenant-scoped erasure | Tenant admin, or the person acting inside that tenant | The membership, its profile, and that tenant's behaviour rows | None | -| Global account closure | The person, through the platform account surface | The `users` row, the Keycloak user, and a fan-out to every membership | All of them, by design | +| Tenant-scoped export | Authorized admin, or the person inside that tenant | The named subject's data within authorized tenant/org and recipient/purpose boundaries | None | +| Tenant-scoped erasure | Authorized admin, or the person inside that tenant | The subject's authorized memberships/profiles and behavior, with eligibility/retention constraints | None | +| Global account closure | The person through a separately admitted account request | Global identity/provider finalization and all membership participants under G16 | All of them, by design; execution requires separate platform authority | - A tenant-scoped export is produced by running the export handlers **inside that - tenant's `ITenantContext`, connected as `learnstack_app`**. Row Level Security is the - mechanism that bounds the bundle, not a `WHERE tenant_id = …` clause a developer can - forget in one of a dozen modules. + tenant's `ITenantContext`, connected as `learnstack_app`**. RLS bounds tenant/org + isolation; every module also applies the named subject and permitted disclosure + predicates. A second person in the same tenant must not appear in the bundle. + 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`, 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. The `users` row - survives for as long as any membership remains anywhere. -- **Global account closure has no tenant-admin endpoint.** It is a platform-scoped - operation. It fans out `UserAnonymisationRequestedV1` to every tenant the person - belongs to and reconciles completion per Data Protection's 30-day workflow. + metadata remain subject to the first-writer decision below. 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. - 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. @@ -224,9 +336,10 @@ not defer this phase's DSAR or redaction implementation. Studio editor forces a choice at definition time, and the definition cannot be saved without one. -- Export, redaction and retention walk the **definitions**, not the blob. Without the - per-key classification an export either dumps the whole column — leaking values that - should have been redacted — or drops it entirely, which fails the portability right. +- Export, redaction and retention use the value's applicable **definition revision**, + subject and recipient/purpose contract. PII category alone grants no export + authority. Retired definitions or reclassification cannot orphan existing values + or make them safe to log. G9 decides nested values, key reuse and migrations. - Log and error-tracking redaction is category-driven. `SensitiveTokenCatalog` from [Phase 02a Packet 3](phase-02a-kernel-tenancy.md) matches on property **names**, and the names inside `custom_fields` are authored by tenants at runtime, so it cannot @@ -258,9 +371,11 @@ membership admin screen in this phase, and its correctness depends entirely on t ownership split above — shipping the table three packets before the rule that governs what may be written into it invites exactly the leak this phase closes. -- `tenant_custom_field_defs` with `UNIQUE (tenant_id, target_entity, key)`, the - required `pii_category` column, the field's JSON Schema, and `is_required` / `sort` - presentation metadata. +- Customization owns `TenantCustomFieldDef`; Identity consumes its application + contract and owns membership values. G9 decides immutable definition revisions, + target-qualified version identity, one active definition per concept and value + pins before the first schema. Include required `pii_category`, field schema and + `is_required` / `sort` metadata without an unversioned unique key blocking history. - Allowed `target_entity` values **in this phase**: `Membership` only. The remaining targets light up with their owning phases — `Course` and `Lesson` in [Phase 05](phase-05-education-learning-content.md), @@ -269,9 +384,16 @@ what may be written into it invites exactly the leak this phase closes. whose phase has not shipped is rejected at save time rather than silently stored. - Values are validated against the field's JSON Schema on every write, and rejected through `Result.Fail(validation_failed)` — never by throwing. +- The existing `IJsonSchemaValidator` admission requires a nonempty root + `properties` object. G9 decides how field schemas use that profile or a separately + approved bounded extension; scalar fields cannot bypass admission. It also + decides required-field introduction, null/default/unknown-key behavior, schema + retirement, consent for sensitive values and supported localized form types. - Permission keys per [Permission Standards](../standards/19-permissions.md): `customization.custom_field.admin` (Tenant scope) to define fields; - `identity.membership.write` (Tenant / Organization scope) to set their values. + `identity.membership_profile.write` (Tenant / Organization scope) to set their + values under the ADR-0073 profile permission contract; G9 still owns + dynamic-value activation. - Studio surface: a definition editor and a schema-driven form on the membership detail page. The visual schema builder is [Phase 06](phase-06-renderer-admin-studio.md). @@ -299,9 +421,18 @@ wires LearnStack into that flow: permission integration here rather than implementing session custody again. - Post-login membership lookup: resolve memberships for the authenticated user and surface the active tenant via a host + claim cross-check. +- G1 establishes required actor claims before the accepted callback needs them; + no first-login mirror relaxes the API profile. G4 decides discovery for zero or + multiple memberships and session-specific scope issuance. Editing a shared + provider user attribute is not evidence of independent A/B sessions: both must + keep their own scope through real refresh. Switching preserves host-only cookie, + callback/return allowlists and late-publication fences. - Tenant-specific Keycloak federation surface in Admin Studio (configure SAML / OIDC - IdP per tenant) — UI delivered here, runtime in Keycloak. -- Mapping of Keycloak `sub` to LearnStack `UserId`; idempotent on first login. + IdP per tenant), delivered under G12 with a confined runtime adapter. Broker + ownership, secret write-only handling, bounded egress, safe account linking, + MFA trust, test/activate/rollback and last-login recovery are part of delivery. +- Durable issuer + `sub` to `UserId` mapping under G1, with retry/concurrency and + provider/DB reconciliation. Existing seed IDs and credentials remain preserved. LearnStack does **not** implement password hashing, password reset email rendering, or provider brute-force protection; Keycloak owns those capabilities and token @@ -324,6 +455,15 @@ an authenticated principal without the required permission cannot dispatch the handler. Keep the endpoint census as an independent structural check, alongside tenant membership, permission and resource-scope enforcement. +G2 settles pre-context app-role lookup and the authorization/transaction handoff: +the resolver asks membership before installing context, and authorization is step +5 before the ordinary step-6 transaction. Neither a normal unresolved repository +nor an unrecorded bypass/new GUC setter supplies that capability. A matching +host/token on rows 6/9 does not exempt a protected act from live membership checks. +G5 specifies the committed-revocation boundary, already-admitted work, delegation +ceilings, recovery/bootstrap and finite SystemActor permissions. Realm-role claims +and provider token refresh alone cannot establish application permission freshness. + - Role-based authorization. - Permission-based authorization. - Tenant-scoped permission checks (`Membership.Roles → Permissions`). @@ -338,6 +478,8 @@ tenant membership, permission and resource-scope enforcement. [Phase 02d](phase-02d-walking-skeleton.md) ships included. - Permission keys for those public reads, granted to the `Portal Public` role of [Permissions Standards § Built-in Roles](../standards/19-permissions.md#built-in-roles). + G5 supplies that anonymous capability model without requiring a stored membership + or promoting `HostOnly` to protected authority. - **Lights up the [Phase 02a Packet 3](phase-02a-kernel-tenancy.md) `AuthorizationBehavior` shell** — resolves each command's `[Authorize(Policy)]`, calls `IAuthorizationService.AuthorizeAsync` against the tenant + @@ -384,8 +526,44 @@ Authorization is the third layer, not the first. A permission check that passes runs under the tenant's `ITenantContext` and under Row Level Security; a deny is a better error message, not the isolation boundary. +### Protected web and API operations + +The delivered authenticated caller accepts only `GET /api/v1/account/site`. +P03-3 extends native credential custody through exact generated SDK operations +under G6; the public caller stays anonymous. A generic proxy, browser bearer, +Server Action or tenant/org selector is not admitted by adding an admin screen. + +- Decide endpoint/application/resource policy ordering before activation. HTTP + denials occur before the MediatR audit frame; G7 assigns their evidence owner. + Application policy metadata respects module/core dependency boundaries. +- Define route/method/input limits, verified host/source, Origin/CSRF, no-store, + deadline/cancellation and closed error/recovery outcomes, preserving + [ADR-0071](../decisions/0071-uncertain-account-site-refusals.md) unless explicitly + changed by the packet's decision. +- Use cursor pagination/indexed member projections and ETag/If-Match for edits. + Idempotent side effects retain authorization on replay; tenant-wide key storage + must not let another actor replay sensitive responses or bypass revocation. +- Key protected client/server state by applicable actor, tenant, org and locale; + fence late responses and clear stale protected state on switch/logout. +- Deliver empty/loading/error/conflict states, scope labels and deliberate + unsaved-edit handling. Apply localization and manual keyboard/focus/form/error/ + reflow/contrast checks to new screens now; the full Playwright/axe expansion + remains [Phase 06](phase-06-renderer-admin-studio.md). + ### Operator recovery and dashboard admission +P03-9/G13 also owns the production first-admin and controlled issuer-rebind +authority defined by ADR-0072/0073. Before production onboarding, +qualify an admitted operator creating the finite Role templates in separate +transactions, then the first tenant-wide admin Membership with MUST audit. +Specify authorized retry after partial setup, wrong-tenant/operator denial, +unknown-COMMIT reconciliation and recovery without the development seed +capability. Tenancy provisioning remains its Tenant/default Organization pair. +An issuer rebind needs proven provider continuity and frozen admission, preserving +AuthorityId, actor IDs and tombstones; no production rename path exists before +this contract is accepted and delivered. Seed-backed P03-3 journeys may be +qualified earlier; they are not production onboarding proof. + Phase 02b supplies internal targeted subscriber replay and no operator route. This phase owns the operator outbox/dead-letter/subscriber-replay and job-recovery surface. Before its first writer, settle the URL space under ADR-0036, exact @@ -405,98 +583,94 @@ an admitted scope's entry row is not evidence of a denied attempt. ### Gateway Configuration Corrections -The APISIX gateway **adapter** is demand-gated to -[Phase 11](phase-11-production-hardening.md) per -[ADR-0035](../decisions/0035-demand-gated-infrastructure.md); until then the equivalent -concerns are handled by ASP.NET middleware. The published route table in -[API Gateway](../architecture/30-api-gateway.md) is nevertheless corrected **here**, -because that file is what an operator will paste into a live gateway the first time one -is needed, and both defects below are silent when read and severe when deployed. - -**Route priority.** Every route declares an explicit integer `priority`, and every -anonymous route whose path is matched by the authenticated catch-all declares a -strictly higher value than it. - -- The published table describes priority bands in comments (`# priority 1`, - `# priority 99`, `# priority 100`) but no route carries a `priority` field. APISIX - defaults an omitted priority to `0`, so every band ties. -- `GET /api/v*/localization/*` and the authenticated catch-all `/api/v*/**` both match - `GET /api/v1/localization/en`. When the catch-all wins the tie, `openid-connect` with - `bearer_only: true` returns 401 to a request that has no token and is not supposed to - need one. -- The rule is not specific to localization. Every anonymous read the public renderer - makes — the `[PublicSurface]` request types enumerated in - [API Standards § Public surface](../standards/04-api-design.md#public-surface), whose - first rows come from [Phase 02d](phase-02d-walking-skeleton.md) — and the public CMS - reads from [Phase 04](phase-04-cms-media-pages.md) are matched by the authenticated - catch-all, so each needs a public-band route that outranks it. - -**Route 100's `client_secret_ref` is deleted.** The line currently reads -`client_secret_ref: vault://learnstack/hub/internal-api-hmac-key`, binding the -gateway's Keycloak OIDC client secret to the Hub internal-API HMAC signing key. It is -wrong twice: - -- **Functionally** — the `learnstack-gateway` client's secret in the `learnstack` realm - is not the Hub signing key, so the OIDC handshake cannot succeed with that value. -- **Structurally** — it collapses two trust domains into one secret. The HMAC key signs - `/api/internal/*` request bodies in the Hub auth chain - ([ADR-0034](../decisions/0034-hub-contract-surface-invariant.md)). Distributing it - into edge-proxy configuration — and, on failure, into edge-proxy error logs — hands - anyone who can read either the ability to forge a signed - `PUT /api/internal/tenants/{id}/entitlements` or - `PUT /api/internal/tenants/{id}/host-mappings` for **any** tenant: granting themselves - any plan, or pointing a tenant's hostname somewhere else. The repository's secret-scan - check does not catch it, because the committed value is a Vault path rather than a - secret. - -The correction: route 100 references the gateway's own OIDC client secret at its own -path, and the Hub HMAC key appears in no gateway configuration at any priority. It is -held only by the `IEntitlementProvider` / `IUsageReporter` / `IHubTenantSync` adapters -ADR-0034 names as the sole Hub-facing callers. +G18 applies [API Gateway Rules 1–3](../architecture/30-api-gateway.md#4-route-table) +to the committed `infra/apisix/apisix.yaml` scaffold. The architecture example +already declares explicit priorities and removes the historical Hub-secret +reference. The scaffold has priorities and no such reference, but still uses the +version-wildcard spelling Rule 1 rejects. Its OIDC block remains disabled. + +- Use explicit version paths and method sets, retain explicit priorities and keep + the gateway independent of the Hub HMAC secret. The bearer-only target needs no + substitute code-exchange client secret under Architecture Rule 3. +- Do not claim HMAC possession alone defeats the internal chain: compromising + that secret permits forged body signatures; accepted mTLS and service JWT + checks remain independent requirements under + [Security Standards](../standards/11-security.md#hub-contract-surface). +- [Phase 11](phase-11-production-hardening.md) owns the reviewed route for every + enumerated public read, anonymous-over-catch-all precedence, route lint and + gateway activation. This phase corrects the scaffold without enabling OIDC or + copying the architecture's full target table into a live configuration. + +The APISIX adapter's owning phase and +[ADR-0035](../decisions/0035-demand-gated-infrastructure.md) trigger are unchanged. ### Invitation Flow -- Tenant admin invites a user (email + role + organization). -- Invitation token bound to the email; a mismatched signup is rejected. -- A new invitee is redirected to Keycloak signup with a prefilled email; an existing - user is redirected to Keycloak login. -- After callback, LearnStack creates the `Membership` and marks the invitation - accepted. -- Invitation expiry (default 14 days), accept and revoke endpoints. - -An invitation creates a membership in one tenant. It never creates, modifies or deletes -the global `User` row beyond the first-login mirror. +G8 closes before the Invitation schema or acceptance writer. G1 supplies the +actor/bootstrap contract; a new invitee cannot already be assumed to hold the +membership they are accepting. + +- An authorized admin offers email + role + organization within their current + delegation ceiling. Bind a random single-use token to a stored one-way verifier; + a prefilled email is not proof of the authenticated person's current verified + provider email. G8 decides exact matching and email-change behavior. +- GET inspects an offer without accepting it. The admitted mutating act uses the + chosen authenticated continuation and CSRF/transaction binding. Keep tokens out + of diagnostic payloads and arbitrary return URLs. +- Define pending/accepted/revoked/expired/resend states, default 14-day expiry, + existing-member behavior, current inviter grant/org lifecycle checks and + accept/accept, accept/revoke and accept/expiry races. +- Membership/grant creation and invitation consumption need one authoritative + outcome. G8 decides aggregate boundaries and atomicity/reconciliation under + [ADR-0042](../decisions/0042-tenant-provisioning-cross-aggregate-transaction.md); + the ambient transaction alone grants no new multi-root exception. +- Deliver a usable bounded invitation handoff in this phase. G8 decides its + email/provider or explicit admin-handoff mechanism, delivery/retry/idempotency + and truthful queued/sent/failed/resend UX. Do not wait implicitly for Phase 08a, + display a fake sent result or put raw email/token data in identifier-only events. + +An invitation grants authority in one tenant/org only. It does not let an admin +edit global `User` or provider attributes; G1's trusted mirror is separate. ### Admin Foundation (identity-management screens only) -This phase ships the identity-management surface in Admin Studio. CMS, page-builder and -catalog screens are owned by [Phase 06](phase-06-renderer-admin-studio.md). +This phase ships the identity-management surface in Admin Studio. CMS/media +screens belong to Phase 04 and catalog screens to Phase 05; Phase 06 owns full +renderer/Studio expansion and the +[screen ownership table](phase-06-renderer-admin-studio.md#admin-studio--screen-ownership). - Login (delegates to Keycloak). -- Tenant switcher (for multi-tenant operators) and organization switcher. +- Tenant switcher for people with memberships in multiple tenants, and the + organization switcher. Platform-operator admission is separate under G13. - Users list and detail, scoped to the acting tenant and organization. - Roles and permissions management. - Invitations. - Custom field definitions and the schema-driven membership form. -- Tenant member settings basics. +- Membership profile/preferences under the decided self/admin field contract. - 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. +- 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 + setting or provider-secret authoring is not implied by member preferences. ### Audit Coverage Wiring -Identity emits the following MUST-class audit operations through the central pipeline; -`AuditLogBehavior` enrols the row in the same transaction as the business write per -[ADR-0033](../decisions/0033-audit-durability-model.md). Identity itself never touches -`audit_log` directly. +The owning Identity, Tenancy and Customization commands declare the following +MUST-class audit operations through their module catalogues. The central pipeline +writes mutation evidence in the business transaction under +[ADR-0033](../decisions/0033-audit-durability-model.md). Identity never touches +`audit_log` directly or owns another module's command. - Membership created / removed (per `(user_id, tenant_id, organization_id)`). - Role assigned / revoked. - Permission set changed. - Invitation created / accepted / revoked. -- Tenant setting changed. -- Custom field definition created / changed / deleted — a schema change alters what - personal data the tenant stores, so the definition history is itself compliance - evidence. +- Tenant setting changed — Tenancy-owned. +- Custom field definition created / changed / deleted — Customization-owned; + schema history records changes to the personal data the tenant can store. - Tenant-scoped export requested / completed, tenant-scoped erasure requested / completed. - Global account closure requested — recorded against every affected tenant. @@ -504,17 +678,30 @@ Identity emits the following MUST-class audit operations through the central pip `reason`). - Hub-operator access to a tenant resource (`actor.hubOperator = true`). -Keycloak owns its own audit stream for login success and failure, password reset, MFA -enrolment, and account lock. The Identity module **subscribes** to Keycloak webhooks -and re-publishes the relevant events as `learnstack.identity.user` integration events -through `IEventBus`; the Audit module consumes them through `IInboxGuard`-protected -handlers. `IEventBus` resolves to `InProcessEventBus` from -[Phase 02a Packet 5](phase-02a-kernel-tenancy.md); the Dapr-backed transport is -demand-gated to [Phase 11](phase-11-production-hardening.md) per -[ADR-0035](../decisions/0035-demand-gated-infrastructure.md), and the handler contract -is identical either way. See -[Audit Coverage Standards](../standards/18-audit-coverage.md) for the MUST / SHOULD / -MAY matrix. +Keycloak owns login/failure, reset, MFA and lock events in its own stream. G10 +selects the authenticated listener/webhook or pull mechanism, stable provider +event identity, durable acknowledgement, ordering and attribution before an +ingress is written. Known multi-membership users, unknown users, tenantless facts +and post-erasure events need explicit routing/privacy outcomes; provider +authentication alone does not authorize a tenant supplied in its payload. + +Identity enqueues the approved `learnstack.identity.user` facts through `IOutbox`. +The confined dispatcher publishes through `IEventBus`; the Audit subscription +uses the transport-owned shared inbox under +[ADR-0046](../decisions/0046-durable-event-delivery-and-recovery.md). A direct +business `PublishAsync`, raw provider payload copy or invented event tenant is not +admitted. Name any new global intake storage/principal/retention explicitly. +`InProcessEventBus` remains the working transport; Dapr stays demand-gated to +[Phase 11](phase-11-production-hardening.md). Provider development retention is +not the application's security-event retention. + +G7 supplies the request-context port and enumerates its trusted population sites: +actor email, membership/roles, Platform/Hub flags, correlation/route, verified IP +and bounded untrusted user-agent. Core Application acquires no ASP.NET dependency. +Complete actual HTTP/application denial evidence and classify member lists/details +and export/downloads as applicable MUST `read-sensitive` acts. No failed write is +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) @@ -534,6 +721,40 @@ permits only `actor_email`, `ip_address`, `user_agent`, `before_state`, those boundaries until the bounded decision and any required migration ship. Redacting the six columns alone does not establish complete anonymisation. +### DSAR fulfillment and global closure + +G15/G16 close before request/workflow writers; shared identity schema implications +close in G3's first pass. The [canonical Data Protection inventory](../architecture/23-data-protection.md#durable-asynchronous-store-inventory) +and [Audit redaction boundary](../architecture/31-audit-subsystem.md#10-gdpr--pii-redaction) +remain their respective authorities. + +- Define request identity, immutable subject/participant snapshot, idempotency, + eligibility/holds, progress, partial failure, retry and durable completion. + Removing membership must not strand authorized pending work or its status view. +- The export target includes a usable private downloadable artifact and expiry. + G16 names the required Phase 03 storage/delivery slice or an explicitly approved + replacement, with size/lifetime/reauthorization/revocation/cleanup. Full media + remains Phase 04; full notification orchestration remains Phase 08a. +- Register required typed jobs/recurrences and execution profiles against + ADR-0047. Name framework/system authority and retries; an ordinary system job + cannot obtain privileged erasure rights. There is no implicit Phase 04 job + prerequisite for a Phase 03 deliverable. +- Global closure fences new memberships/invite acceptance and delayed mirror + recreation, settles the last-membership case, reconciles all participants and + performs one final provider-account transition. Distinguish requesting person, + human approver where required, service actor and privileged executor. + 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). + Final-admin recovery/termination still requires its separately accepted contract. +- Implement `IUserReferenceLocator` registration for applicable modules, exact + privileged result-audit access, idempotent result identity and inbox/commit + reconciliation. A crash after platform commit must not duplicate result audit. +- Preserve immutable transport/audit facts, replay floors, unresolved external + reservations and minimum grants; extend the inventory for new Identity tables, + artifacts and copied responses. Phase 11 owns retained-copy/purge extensions, + not this phase's missing fulfillment. Status explains any retained references. + ### Cross-cutting follow-up at phase exit - **Escalate both analyzers from Warning to Error** — `LS0001` @@ -556,90 +777,84 @@ Redacting the six columns alone does not establish complete anonymisation. ## Deliverables -- Identity domain — `User` (global), `Membership` (triple-keyed), `MembershipProfile` - (tenant-owned, organization-scoped), `Role` and `Permission` with explicit scope, - `Invitation` — on top of Keycloak. -- Written attribute-ownership table, enforced by `User_Aggregate_Has_No_TenantScoped_Columns`. -- Tenant-scoped DSAR export and erasure, with business handlers running under - `ITenantContext` as `learnstack_app`; separate platform-scoped global closure - and audit redaction after the bounded first-writer decisions above. -- `TenantCustomFieldDef` with a mandatory `pii_category`, the `Membership` target, the - definition editor, and the schema-driven membership form. -- Category-driven redaction of custom-field values in logs and error-tracking payloads. -- `AuthorizationBehavior` as a real implementation, replacing the Phase 02a shell. -- The [runtime authorization gate](#authorization), decided and installed before - the first permission-sensitive route, with real denied-dispatch controls. -- The Platform-scope permission gate replacing `DenyAllPlatformAdminGate`, with the - killswitch toggle command, its permission key and its runbook. -- Operator recovery and Hangfire dashboard admission under the - [bounded first-writer decisions](#operator-recovery-and-dashboard-admission), - including denied-route, fencing, reason and audit controls. -- Admin login, tenant switcher and organization switcher via OIDC PKCE. -- Tenant- and organization-aware user management screens. -- Invitation flow end to end, tenant and organization bound. -- Identity events wired through the central audit pipeline; Keycloak webhook → - `IEventBus` → Audit consumer working end to end. -- Authenticated OIDC back-channel logout ingress and provider-session lookup into - `BffSessionStore`, with signature/audience/time/replay validation and fenced - local revocation, before immediate disable/sign-out-everywhere is promised. -- Corrected APISIX route table: explicit priorities on every route, and no Hub HMAC - reference anywhere in gateway configuration. -- `LS0001` and `LS0002` escalated to Error. +Every row is mandatory. Its packet owns implementation and the linked criterion +identifies observable proof; a later packet completes dependent end-to-end paths. + +| ID | Delivered result | Packet | Completion criteria | +|---|---|---|---| +| D01 | Stable global `User` storage/common creation authority, existing-binding admission, scoped Membership/Profile and Role/Permission foundation, fixed seed adoption | P03-1 | C01–C03, C10 | +| D02 | Live membership/permission enforcement, runtime gate, `app.scope` carrier and real denied controls | P03-2 | C03–C05, C19 | +| D03 | Bounded authenticated native/SDK operations, usable new-user bootstrap/no-session entry and member/role management screens | P03-3 | C01, C06–C07, C20 | +| D04 | Membership-aware tenant and organization switchers through newly validated scope | P03-3 | C07 | +| D05 | Tenancy-owned organization CRUD/archive endpoints, member/profile preferences and identity-backed admission for named existing Tenancy commands | P03-3 | C02, C06, C16, C20 | +| D06 | Secure tenant/org invitation lifecycle and usable bounded delivery/handoff | P03-4 | C01, C08, C20 | +| D07 | Customization-owned versioned field definitions, mandatory PII category, membership values, editor and schema-driven form | P03-5 | C09, C10, C20 | +| D08 | PII census and diagnostic/snapshot redaction, extended for arbitrary custom values | P03-1; P03-5 extension | C10 | +| D09 | Authenticated durable provider-event ingress, identifier-only outbox facts and deduplicated Audit mirror | P03-6 | C11, C19 | +| D10 | Authenticated OIDC back-channel logout, provider/session indexes and fenced local revocation | P03-7 | C12 | +| D11 | Confined tenant federation configuration, safe linking, test/activate/rollback and recovery | P03-8 | C13, C20 | +| D12 | Platform-scope identity/permission gate, production first-admin/issuer rebind, attributed bypass, killswitch writer and runbook | P03-9 | C14, C19 | +| D13 | Fenced operator recovery and application Hangfire dashboard admission, exact permissions/grants/audit/runbooks | P03-9 | C15, C19 | +| D14 | Self/admin tenant-scoped DSAR requests, usable export/erasure, separate person-authorized global closure and privileged redaction | P03-10 | C17, C18, C20 | +| D15 | Trusted audit request/actor enrichment, sensitive-read/denied coverage and user-reference locators | P03-2; P03-10 locator/redaction completion | C19 | +| D16 | Corrected inactive gateway scaffold, LS0001/LS0002 Error, complete catalogue and source-bound exit evidence | P03-11 | C21 | ## Completion Criteria -- A tenant admin sees only users from their tenant; an organization admin sees only - users from their organization. -- No attribute a tenant authored about a person is visible to any other tenant. An - integration test creates one person with memberships in both - [Phase 02a Packet 7](phase-02a-kernel-tenancy.md) seed tenants, sets a custom field - in each, and asserts as `learnstack_app` that neither tenant can read the other's - value. -- `users` has no `custom_fields` column and no tenant-authored column; - `User_Aggregate_Has_No_TenantScoped_Columns` is green. -- A tenant-scoped erasure removes that tenant's membership, profile and behaviour rows - and leaves the person's membership in the other tenant fully functional, including - the ability to log in. -- No tenant-admin endpoint can delete or anonymise the global `User` row or the - Keycloak user. -- DSAR and audit redaction account for the canonical durable-copy inventory and - satisfy their bounded first-writer decisions. Tests preserve immutable facts, - replay/deduplication floors, unresolved reservations and same-transaction MUST - evidence; six-column redaction alone is not proof of complete anonymisation. -- Every `TenantCustomFieldDef` row carries a `pii_category`; a definition with category - `Payment` is rejected; the export bundle contains exactly the fields the categories - permit. -- A custom-field value classified `PII-Identity` does not appear in any log line or - error-tracking payload. -- Role and permission changes are enforced by both API and UI; a permission-scope - rejection (Tenant vs Organization) returns the correct Problem Details code. -- Unauthorized users cannot reach admin endpoints, and a denied command returns - `Result.Fail(forbidden)` rather than throwing. -- Dashboard and recovery routes remain absent until their application permission - and dated decisions ship. Cross-scope/unauthorized recovery cannot reset producer - state, bypass subscriber deduplication, release uncertain job capacity or reuse - a completed privileged connection. -- The [runtime authorization gate](#authorization) refuses an unclassified protected - endpoint and a valid principal lacking its permission before handler execution; - explicit public routes still work anonymously. Updating the static route census - alone cannot make either negative control pass. -- Invitation flow is covered by integration tests, including email mismatch, revoked, - expired, and cross-organization cases. -- Real signed back-channel logout revokes only the intended provider/session - owners. Invalid signatures, issuer/audience/time claims and replay are refused; - unrelated users/sessions and newer logins outside the validated target remain - unaffected. Shared provider SSO is not mistaken for independent host sessions. - A held callback/refresh cannot republish after revocation, and unsettled work - retains its ownership until actual completion. Provider ingress/mirrored audit - evidence is distinguished from local-only session events. -- MUST-class identity audit entries commit in the same transaction as the write they - describe, with before / after snapshots where applicable; no Identity-owned `audit_*` - table exists. -- Cross-tenant operations from a platform-admin role are audited with the required - `reason`; Hub-operator actions are audited with `actor.hubOperator = true`. -- The committed APISIX route table declares a priority on every route, the anonymous - localization route outranks the authenticated catch-all, and - `internal-api-hmac-key` appears nowhere in it. +Every criterion needs a legitimate positive and a negative that isolates the +claimed control. Ordinary isolation uses real PostgreSQL as `learnstack_app`, with +one person in both seed tenants and both organizations of one tenant, plus another +person in the same tenant. Use real pinned Keycloak and native HTTPS for issuance/ +session claims; controlled signed tokens separately isolate protocol refusals. +Test-only endpoints, fake grants or empty scans do not establish shipped behavior. + +| ID | Observable proof | Packet evidence | +|---|---|---| +| C01 | A real nonseed invitee obtains required actor claims and completes the permitted flow; concurrent first login and provider/DB retries preserve one mapping. Same-email/different-sub and conflicting/reserved actor values refuse; the four seed identities/credentials survive. | P03-1 internal foundation; P03-3 HTTP/native entry; P03-4 invitation path | +| C02 | Tenant/org directory and profile reads expose only authorized members/fields, including a guessed foreign global UserId. NULL-org uniqueness, archive/revoke/reinvite and profile granularity follow G3 with database race controls. | P03-1, P03-3, P03-5 | +| C03 | Org/self/invite grant escalation fails; legitimate delegation and bootstrap work. Concurrent last-admin changes preserve the decided invariant; registry upgrades grant only the accepted defaults. API revocation meets its declared boundary and stale UI cannot mutate; SystemActor has finite permissions. | P03-1–3 | +| C04 | Actual HTTP rejects an unclassified protected endpoint and an underprivileged valid principal before handler dispatch. Direct MediatR dispatch independently refuses; expected denials return `Result.Fail(forbidden)`. Explicit public reads remain anonymous. | P03-2 | +| C05 | Real rows 7/10/14 succeed only with active membership. Protected rows 6/9 also enforce revocation. Successful claim-only header mismatch has its separately decided evidence. The role-derived tenant read hatch affects EF/RLS consistently and cannot widen org UPDATE/DELETE or be set from request input. | P03-2 | +| C06 | Actual native/SDK member read/edit works with no browser bearer/raw profile. Wrong Origin/CSRF/provenance, forged scope, stale ETag and late old-session response refuse safely. Another actor or revoked actor cannot replay a sensitive idempotent response; paging/search and error states remain scoped. | P03-3 | +| C07 | One person's simultaneous A/B provider/BFF sessions retain independent scope across refresh; tenant/org switching works only through the accepted reissue transition. Held old refresh, wrong destination or revoked target cannot publish; zero-membership entry has usable recovery. | P03-3 | +| C08 | New/existing invitee acceptance checks current trusted verified email and delegation. Wrong/unverified/changed email, wrong org, revoked/expired offer and accept/revoke/expiry/resend races produce one reconciled outcome. GET cannot grant; delivery failure is visible/recoverable, without duplicate grants or unsupported external exactly-once claims. | P03-4 | +| C09 | Definition/value writes use actual admitted schemas and permitted targets; missing/invalid PII category and `Payment` refuse. Required/default/null, successor/retirement/reclassification/key reuse and sensitive-consent cases retain historical interpretation/exportability without orphaned values or raw write bypass. | P03-5 | +| C10 | The actual `users` model has no tenant-authored/custom-fields column. The PII census has a planted missing subject; sensitive value/token/link canaries remain absent from logs, validation errors, Sentry/local archives and audit snapshots, with positive redaction controls for nested custom values. | P03-1, P03-5 | +| C11 | Real provider ingress authenticates and durably acknowledges one stable provider event. Duplicate/reordered delivery and crash-after-accept reconcile once; unknown/no-/multi-membership subjects have the exact authorized routing/audit fan-out. No raw provider payload, direct business publication or invented tenant escapes the event contract. | P03-6 | +| C12 | Real signed back-channel logout and separate wrong-purpose/signature/issuer/audience/time/events/nonce/replay controls prove the selected profile. Shared/distinct SSO and later independent sessions have exact targets; held callbacks/refresh cannot republish. Replay/index retention and unsettled ownership stay bounded; actual provider-to-native reachability is shown. | P03-7 | +| C13 | Two tenant IdPs coexist in the real realm. One tenant cannot edit another broker/secret, use unauthorized egress or link a foreign admin via asserted email. Valid federation still issues the accepted profile; failed activation retains recovery and trusted MFA semantics. | P03-8 | +| C14 | A real operator with the specific Platform permission succeeds only on its admitted surface; tenant/wrong-purpose credentials fail before bypass acquisition. Human/service/executor/subject attribution, reason and correlation survive. A retained raw connection cannot execute autocommit after scope completion/abandonment. The chosen no-Hub baseline works without a Development bypass. Production first-admin setup/recovery and controlled issuer rebind have positive/denied, partial-commit and identity-continuity proof; seed authority is insufficient. | P03-9 | +| 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 | +| 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 | + +#### Inherited architecture obligations + +Use the canonical [Architecture Tests Catalogue](../standards/21-architecture-tests-catalogue.md) +names. These rows assign proof, not implementation status; the catalogue remains +the status authority. Preserve all existing isolation, module, aggregate, +context-writer/setter, role and public HostScope fences as subjects expand. + +| Obligation | Packet / proof | +|---|---| +| `User_Aggregate_Has_No_TenantScoped_Columns` | P03-1 / C10 | +| `Every_TenantCustomFieldDef_Declares_PiiCategory` | P03-5 / C09; behavioral lifecycle/privacy proof supplements NOT NULL | +| `Tenant_Scoped_Export_Contains_No_Foreign_Tenant_Rows` | P03-10 / C17, supplemented by same-tenant foreign-person/org cases | +| `Every_PII_Module_RegistersUserReferenceLocator` | P03-10 / C18–C19; applicable module census and planted missing registration | +| `Permission_Definitions_DeclareScope`, `Permission_Scope_Matches_Resource_Scope` | P03-2 / C03–C05 | +| `Permission_Keys_Match_Convention`, `Permission_Registry_Has_DeniedTest` | P03-2 / C03–C04; actual nonempty registration set | +| `MustClass_Audit_Writes_Share_The_Business_Transaction` | P03-2 / C19 completes the real authorization-denied clause | +| `Tenant_Scope_Widening_Is_Never_Set_From_Request_Input` | P03-2 / C05 replaces the vacuous carrier subject | +| `PlatformAdminScope_Entry_Requires_Platform_Permission` | P03-9 / C14 adds actual admitted and denied operators | +| `Provider_SDK_Types_NotImportedOutsideInfrastructure` | First actual runtime provider SDK, if introduced; direct HTTP alone does not close backfill | + +Each packet records exact source/configuration/provider versions, actual result +population and sanitized receipts in its delivery log. No production p95, full +WCAG conformance or external exactly-once effect is inferred from local fixtures. ## Risks @@ -664,8 +879,9 @@ Redacting the six columns alone does not establish complete anonymisation. definition ends up `None`, the classification is decorative and the export is wrong. The Studio editor asks the question in the field's own words, and the seed data sets a non-trivial category so the shape is exercised. -- **Designing the identity model around the first tenant.** Triple-key membership and - organization-scoped roles must serve every tenant shape, not only the language-school +- **Designing the identity model around the first tenant.** Stable Membership roots, + null-safe natural uniqueness and tenant-wide Role templates with scoped capabilities + must serve every tenant shape, not only the language-school showcase in [Phase 10](phase-10-english-learning-mvp.md). Both [Phase 02a Packet 7](phase-02a-kernel-tenancy.md) seed tenants get memberships in this phase. @@ -674,15 +890,21 @@ Redacting the six columns alone does not establish complete anonymisation. onto flat permissions touches every check. - **Relying on frontend checks for admin authorization.** The API enforces; the UI mirrors. A hidden button is a usability decision, never a security one. -- **Correcting the gateway config and then never deploying it.** The corrected table is - configuration for a component that does not run until - [Phase 11](phase-11-production-hardening.md). Phase 11 must adopt the corrected file - rather than re-deriving one from the architecture doc's older revision. +- **Scaffold correction mistaken for gateway activation.** Phase 11 consumes + explicit version paths and separated credentials, then qualifies the reviewed + public allowlist, precedence and OIDC/TLS/provenance. Copying a target example + into the scaffold does not establish any of those production controls. ## Phase Exit Decision [Phase 04](phase-04-cms-media-pages.md) begins when all of the following hold: +- Every D01–D16 deliverable and C01–C21 completion criterion has source-bound + evidence in the phase exit index, linking actual packet records and relevant + accepted vehicles. No mandatory invitation, federation, logout, operator, + organization, settings, audit-enrichment or DSAR path is omitted by summarizing + the phase as "RBAC complete". Every applicable first-writer gate is Accepted + for the part implemented; conditional SDK coverage retains its honest subject. - A person holding memberships in both seed tenants has their tenant-authored attributes stored per tenant, invisible across tenants, and provably so by an integration test running as `learnstack_app`. @@ -692,12 +914,14 @@ Redacting the six columns alone does not establish complete anonymisation. are implemented; surviving immutable references are explicitly reconciled. - Every `TenantCustomFieldDef` carries a PII category, and export, redaction and retention are driven by the definitions rather than by the JSONB blob. -- `AuthorizationBehavior` is a real implementation and every write endpoint carries an - explicit policy. +- `AuthorizationBehavior` and the runtime default-deny gate are real, with + independently proved HTTP/application denials. Every protected endpoint, + sensitive reads included, has its explicit policy and assigned audit evidence. - `LS0001` and `LS0002` are Errors, both removed from `WarningsNotAsErrors`, and the solution builds clean. -- The corrected APISIX route table is committed with explicit priorities and no Hub - HMAC reference. The gateway adapter itself remains +- The corrected APISIX scaffold is committed with explicit version paths and + priorities, no Hub-secret dependency and disabled OIDC. Reviewed public-route + allowlisting, lint and gateway activation remain [Phase 11](phase-11-production-hardening.md) work. - The identity, DSAR and custom-field architecture tests named above are registered in [Architecture Tests Catalogue](../standards/21-architecture-tests-catalogue.md) and diff --git a/docs/roadmap/phase-04-cms-media-pages.md b/docs/roadmap/phase-04-cms-media-pages.md index 9005d3281..25b3ecb36 100644 --- a/docs/roadmap/phase-04-cms-media-pages.md +++ b/docs/roadmap/phase-04-cms-media-pages.md @@ -298,6 +298,13 @@ The block system ships with: ### Media Library and the Transcoding Pipeline +This phase owns the full media/storage surface below. +[Phase 03 G16](phase-03-identity-admin.md#the-decision-register) must explicitly +deliver any minimum private-export artifact/storage prerequisite its earlier +DSAR workflow requires, or accept a replacement delivery contract. That slice is +not a Phase 04 media library, and this phase adopts its decided provider/access +boundary rather than making Phase 03 fulfillment depend on an undelivered engine. + Storage and asset management: - Upload to SeaweedFS through `IStorageProvider` diff --git a/docs/roadmap/phase-06-renderer-admin-studio.md b/docs/roadmap/phase-06-renderer-admin-studio.md index 83ecdb65c..d780ede8c 100644 --- a/docs/roadmap/phase-06-renderer-admin-studio.md +++ b/docs/roadmap/phase-06-renderer-admin-studio.md @@ -146,9 +146,11 @@ that tree is descriptive, not a delivery plan. | Screen group | Owning phase | |---|---| | Studio shell, login, tenant switcher, org switcher, dashboard chrome, users, roles, invitations, `TenantCustomFieldDef` editor, tenant IdP federation surface | [Phase 03](phase-03-identity-admin.md) | +| Member/profile preferences, tenant-scoped self/admin data-request status and separate account-closure request surface under their admitted authority | [Phase 03](phase-03-identity-admin.md) | | Content types, content entries, pages, page builder, `TenantPageBlock` editor, media library, navigation editor, publish / preview controls | [Phase 04](phase-04-cms-media-pages.md) | | Programs, courses, course structure, modules, lessons, lesson items, `TenantLessonItemType` editor, `TenantLevelTaxonomy` editor, `TenantCompletionRule` editor, course publish flow | [Phase 05](phase-05-education-learning-content.md) | | Branding and theme configuration, per-organization branding override, tenant settings (feature-flag overrides, read-only entitlement projection viewer, read-only custom-domain status), audit log viewer, **audit coverage override editor**, the customization editor consolidation, cross-phase Studio information architecture | **Phase 06** | +| Organization list / detail / create screens over the Phase 03 Tenancy endpoints; the organization switcher remains Phase 03 | **Phase 06** | | Notification template library (`TenantTemplateLibrary`), assessment and question-bank screens, `TenantScoringRule` editor | [Phase 08a](phase-08a-assessment-notifications.md) | | Instructor availability, session and booking management | [Phase 08b](phase-08b-scheduling.md) | | Classroom session monitoring and recording metadata | [Phase 08c](phase-08c-classroom.md) | diff --git a/docs/roadmap/phase-08a-assessment-notifications.md b/docs/roadmap/phase-08a-assessment-notifications.md index d80ee54e1..baa089d24 100644 --- a/docs/roadmap/phase-08a-assessment-notifications.md +++ b/docs/roadmap/phase-08a-assessment-notifications.md @@ -132,6 +132,13 @@ and an unread template store is a schema nobody validates. ### Notifications +This phase owns the full engine and template-driven channel orchestration. +[Phase 03 G8](phase-03-identity-admin.md#the-decision-register) owns the earlier +usable bounded invitation delivery/handoff and its privacy/idempotency/recovery +contract. That first consumer must name any required minimum email slice there; +it cannot assume this engine is already running. This phase integrates that +accepted boundary instead of introducing a competing sender or retry policy. + - Notification dispatch orchestration in the Notifications module. - Channels: email wired through the `IEmailProvider` adapter ([06-extension-model.md](../architecture/06-extension-model.md)); SMS, WhatsApp, and diff --git a/docs/roadmap/phase-10-english-learning-mvp.md b/docs/roadmap/phase-10-english-learning-mvp.md index 3ab7decd8..755d56088 100644 --- a/docs/roadmap/phase-10-english-learning-mvp.md +++ b/docs/roadmap/phase-10-english-learning-mvp.md @@ -42,7 +42,7 @@ eight, and where a gap in any of them stops being theoretical. |---|---|---| | `TenantContentType` | [Phase 02a Packet 8](phase-02a-kernel-tenancy.md) | `vocabulary-card` (word + part of speech + definition + examples + audio reference), `grammar-topic` (title + summary + examples + level reference), `speaking-prompt` (prompt + difficulty + sample answers), `lesson-package` (composite referencing courses + supplementary content) | | `TenantLevelTaxonomy` | [Phase 02a Packet 8](phase-02a-kernel-tenancy.md) | CEFR levels A1 … C2. The taxonomy declares the vocabulary; the `Level` table holds items keyed by `(tenant_id, taxonomy_key, key)` | -| `TenantCustomFieldDef` | [Phase 03](phase-03-identity-admin.md) | `User.preferredAccent` (BrE / AmE / AusE / other), `InstructorProfile.dialectsTaught`, `Enrollment.preferredPace` | +| `TenantCustomFieldDef` | [Phase 03](phase-03-identity-admin.md) | `Membership.preferredAccent` (BrE / AmE / AusE / other), `InstructorProfile.dialectsTaught`, `Enrollment.preferredPace` | | `TenantPageBlock` | [Phase 04](phase-04-cms-media-pages.md) | `vocabulary-list`, `level-card`, `placement-test-entry`, `instructor-grid` — each pointing at a built-in `content-list` / `card-grid` / `default-card` composite renderer | | `TenantLessonItemType` | [Phase 05](phase-05-education-learning-content.md) | `SpeakingPracticeItem` (prompts + live-session reference), `VocabularyDrillItem` (deck reference + drill mode), `GrammarExerciseItem` (exercise reference + scoring config) | | `TenantScoringRule` | [Phase 05](phase-05-education-learning-content.md) | Placement test → CEFR level recommendation. Takes an attempt's answer map, returns a level key from the tenant's own taxonomy | diff --git a/docs/standards/01-architecture-standards.md b/docs/standards/01-architecture-standards.md index a5a5f1341..087ff7be2 100644 --- a/docs/standards/01-architecture-standards.md +++ b/docs/standards/01-architecture-standards.md @@ -15,7 +15,10 @@ (supersedes ADR-0011 Vertical Extension Points). Background-job authority additionally derives from [ADR-0047](../decisions/0047-transactional-background-job-runtime.md) -(Accepted; P02b-4 implementation in progress). +(Accepted; implemented runtime and enforcement). +Identity foundation boundaries additionally derive from Accepted +[ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md) and +[ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md). These rules turn the architecture docs into enforceable code conventions. They are checked by architecture tests where possible. @@ -86,6 +89,15 @@ exceptions below) — so the seam has nowhere else to live. The edge is one-way: Infrastructure for a **capability of its own** rather than for a shared seam is the misuse this sentence exists to name. +**Bounded migration installer.** ADR-0072 admits only the Identity migration's +enumerated `IdentityCreationWitnessInstaller` call on its migration connection +after Audit exists. The [Database contract](05-database.md#lock-snapshot-and-adoption-conditions) +owns its exact central Audit SQL/guard installation boundary. Identity copies no +audit SQL, gains no direct audit writer or general cross-module join, and core +Infrastructure gains no module assembly/entity reference. Step 3 implements the +exact installer/body/caller census and the Identity-only common Application +coordinator dependency. Other module/core edges remain forbidden. + Forbidden edges: - Domain → Application - Domain → Infrastructure @@ -204,6 +216,11 @@ Rules: [ADR-0003 Amendment 3](../decisions/0003-tenant-isolation-defense-in-depth.md). The presence of a `TenantId` property is **not** the test: `PlatformHostMapping` has one and takes no marker. +- Global self-identity `users` takes no `[TenantOwned]` marker or tenant column. + Its adopted subject-confined EF/RLS/owner contract is specified once in + [Database Standards](05-database.md#identity-storage-contract), implemented in Step 3. + Its common transaction/capture admission is an exact authority mode, not a + table-name exemption or a fifth cross-module communication mechanism. - `[TenantOwned]` entities must have a configured EF global query filter and a PostgreSQL RLS policy (see [Database Standards](05-database.md)). - Application services must never expose `IgnoreQueryFilters()` directly to callers. - Background jobs restore tenant/org from the authoritative LearnStack job envelope diff --git a/docs/standards/04-api-design.md b/docs/standards/04-api-design.md index 841ebb443..703d40e47 100644 --- a/docs/standards/04-api-design.md +++ b/docs/standards/04-api-design.md @@ -14,6 +14,8 @@ derive from [ADR-0066](../decisions/0066-bounded-tenant-subject-admission.md), Accepted — 2026-10-20. Implementation has local runtime/exported proofs; the [implementation record](../roadmap/phase-02b-delivery-log.md#adr-0066-acceptance-and-implementation-2026-10-20) owns independent reviews and final-source CI qualification. +Existing-binding admission additionally derives from Accepted +[ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md). REST conventions for LearnStack public and admin APIs. @@ -144,6 +146,15 @@ before JWT validation; credential-free public reads retain anonymous behavior. Production authentication and authorization services/middleware activate together with the complete Step 4 boundary. +**Existing-binding handoff.** The [Security contract](11-security.md#identity-admission-contract) +separates verified provider subject from normalized application identity. An +optional wire actor is consistency evidence; quota precedes the uncached existing- +binding read, which alone supplies a stored actor. Unknown/conflicting/Closed or +unavailable bindings return uniform 401 without allocation. Ordinary resolution +remains route-independent. Credential-free public reads and AccountSite's existing +absent-bearer 404/admitted-wrong-method 405 remain. No POST, OpenAPI operation or +SDK census change is admitted; P03-3/G1/G6 owns new-user transport decisions. + ## Tenant Context **[ADR-0036](../decisions/0036-tenant-resolution-trusted-inputs.md) is the single diff --git a/docs/standards/05-database.md b/docs/standards/05-database.md index f38414801..bfb68aadc 100644 --- a/docs/standards/05-database.md +++ b/docs/standards/05-database.md @@ -39,6 +39,10 @@ Vendor-maintenance configuration and source deadlines derive from Actual runtime/source ownership additionally derives from [ADR-0059](../decisions/0059-owned-hangfire-server-generations.md), qualified by [ADR-0060](../decisions/0060-fatal-hangfire-startup-and-unsafe-unwind.md). +Identity storage and global audit authority additionally derive from Accepted +[ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md), +[ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md) and +[ADR-0074](../decisions/0074-membership-admission-under-ordered-locks.md). PostgreSQL schema, EF Core, and migration conventions. @@ -49,11 +53,13 @@ PostgreSQL schema, EF Core, and migration conventions. - One `DbContext` per module (not one global). - Schema migrations live with the owning module. -Five migration chains exist: Tenancy, Platform, Customization, Audit and -Education. The complete applied-table census, including job and pinned vendor -storage, is checked independently from `pg_catalog` by +Six migration chains currently exist: Tenancy, Platform, Audit, Identity, +Customization and Education. The complete applied-table census, including job +and pinned vendor storage, is checked independently from `pg_catalog` by [`SchemaTableClasses`](../../backend/tests/LearnStack.Tests.Integration/Database/SchemaTableClasses.cs). -Its reviewed classes cover every data table and the five migration-history tables. +Its reviewed classes cover every data and migration-history table. +The [Identity contract](#identity-storage-contract) owns the implemented sixth +chain and its bounded database authority. ## Naming @@ -275,7 +281,15 @@ with row security bypassed and a single-column child FK could point at another tenant's row. Here the referencing column *is* `tenant_id`, so pointing elsewhere would be pointing at a different tenant by definition, which the child's own `WITH CHECK` already refuses. The exception is exactly one table -wide; a second one is a decision, not a convenience. +wide among tenant-owned parents. + +**Tenant-owned to global self-identity is the third relationship shape.** Under +ADR-0072/0073, same-module `memberships.user_id` references global `users.id`, +indexed with `ON DELETE RESTRICT`, without a tenant composite: User has no tenant +key. The [Identity storage contract](#identity-storage-contract) owns its exact +admission guard, which refuses unknown/nonadmitting targets before FK diagnostics. +Audit actor columns gain no User FK. This shape is implemented; +every other tenant-owned parent retains the composite or self-keyed shape above. **`ON DELETE RESTRICT` on every foreign key whose parent is an aggregate root, until a phase owns deprovisioning.** A cascade from `tenants` or `organizations` @@ -356,8 +370,9 @@ Rules: correction to the existing `tenant_settings` and `audit_log` policies by forward migrations; Step 2 applies it to all four Education tables. Applied migrations are not rewritten. -- The session variable names `app.tenant_id`, `app.organization_id`, `app.scope` and - `app.resolving_host` are canonical and the set is closed; do not invent alternatives +- The session variable names `app.tenant_id`, `app.organization_id`, `app.scope`, + `app.resolving_host`, `app.identity_authority_id` and `app.identity_subject_key` + are canonical and the six-name set is closed; do not invent alternatives (`app.current_tenant_id`, `learnstack.tenant_id`, …). `app.tenant_id` and `app.organization_id` are set inside the ambient transaction — by `TransactionBehavior` in the general case, and by each of the out-of-band setters on @@ -374,6 +389,10 @@ Rules: the second argument `true` (missing-OK), and always wrap the result in `NULLIF(…, '')`, so an unset context yields `NULL` and the predicate filters the row out rather than raising inside a pooled connection. + Only the [enumerated global owners](#global-owners-and-privileges) set the last + two, transaction-locally from verified facts. Missing/reset/malformed identity + values fail closed; identity announcements add no tenant-context setter. Their + implementation follows the global owner contract below. - The application sets `app.tenant_id` and `app.organization_id` with `SET LOCAL` **inside the ambient transaction**, after it opens. These settings are transaction-local: set before the transaction begins — in a MediatR behavior that @@ -466,6 +485,9 @@ P02d-1 Step 2 implements this control on `lessons`, `course_translations` and exercises insertion through separately authenticated `learnstack_app` connections; [EducationParentScopeTests](../../backend/tests/LearnStack.Tests.Integration/Database/EducationParentScopeTests.cs) exercises reparenting and the parent lock before the FK executes. +Identity's Membership profile/assignment children participate in the same +model/applied-schema census under the +[Identity storage contract](#identity-storage-contract). The lookup carries **both** tenant and parent identity, runs under the caller's RLS, and uses `IS DISTINCT FROM` so tenant-wide `NULL` is compared as a value. A missing, @@ -552,17 +574,25 @@ hole the composite key exists to close. ### Table classes Not every table in the tenancy schema is tenant-owned, and applying the template above -to all of them produces a deadlock rather than isolation. Six classes exist, and every -migration states which one its table is. +to all of them produces a deadlock rather than isolation. Seven classes are +adopted, and every migration states which one its table is. The applied schema +contains all seven after P03-1 Step 3. Step 4 adds contextual Identity tables +under the existing tenant-wide and organization-scoped classes. | Class | Rule | Tables | |---|---|---| -| **Tenant-owned, org-scoped** | The full template above: `ENABLE` + `FORCE`, one permissive policy `AND`-ing the tenant term with the organization term, explicit `WITH CHECK`, **and** the two `AS RESTRICTIVE` `UPDATE` / `DELETE` guards | any domain table carrying `organization_id`, plus `tenant_settings` — the only org-scoped table in the Packet 6 set — `event_deliveries` (P02b-3 Step 1), `background_jobs`, `background_job_attempts`, `background_job_recipients` (P02b-4 Step 2), and `audit_log`, which Packet 9 added ([ADR-0044 § 9](../decisions/0044-audit-write-path.md)); P02d-1 Step 2 adds `courses`, `lessons` and both translation tables | -| **Tenant-owned, tenant-wide** | The same shape with the organization half of the predicate omitted, and therefore **no** restrictive guards — there is no organization to guard | `organizations`, `tenant_domains`, `tenant_locales`, `tenant_feature_flags`, `platform_entitlement_cache`, `idempotency_keys`, `outbox_messages`, `inbox_messages` (P02b-3 Step 1), `background_job_capacity`, `background_job_reservations` (P02b-4 Step 2), `tenant_content_types`, `tenant_level_taxonomies`, `tenant_level_taxonomy_items`, `customization_generations`, and `audit_config`, which Packet 9 adds ([ADR-0044 Amendment 1](../decisions/0044-audit-write-path.md)) | +| **Tenant-owned, org-scoped** | The full template above: `ENABLE` + `FORCE`, one permissive policy `AND`-ing the tenant term with the organization term, explicit `WITH CHECK`, **and** the two `AS RESTRICTIVE` `UPDATE` / `DELETE` guards | any domain table carrying `organization_id`, plus `tenant_settings` — the only org-scoped table in the Packet 6 set — `event_deliveries` (P02b-3 Step 1), `background_jobs`, `background_job_attempts`, `background_job_recipients` (P02b-4 Step 2), and `audit_log`, which Packet 9 added ([ADR-0044 § 9](../decisions/0044-audit-write-path.md)); P02d-1 Step 2 adds `courses`, `lessons` and both translation tables; P03-1 Step 4 adds `memberships`, `membership_profiles` and `membership_role_assignments` | +| **Tenant-owned, tenant-wide** | The same shape with the organization half of the predicate omitted, and therefore **no** restrictive guards — there is no organization to guard | `organizations`, `tenant_domains`, `tenant_locales`, `tenant_feature_flags`, `platform_entitlement_cache`, `idempotency_keys`, `outbox_messages`, `inbox_messages` (P02b-3 Step 1), `background_job_capacity`, `background_job_reservations` (P02b-4 Step 2), `tenant_content_types`, `tenant_level_taxonomies`, `tenant_level_taxonomy_items`, `customization_generations`, and `audit_config`, which Packet 9 adds ([ADR-0044 Amendment 1](../decisions/0044-audit-write-path.md)); P03-1 Step 4 adds `roles` and `role_permission_grants` | | **Tenant-owned, self-keyed** | Identical, except the tenant term is `id = …` because the row's primary key *is* the tenant id | `tenants` | -| **Platform-scoped** | `ENABLE` + `FORCE`, and role-qualified per-command policies: the read is widened by an explicitly declared non-tenant predicate, and writes are either tenant-keyed or reserved to `learnstack_platform` | `platform_host_to_tenant`, `platform_killswitches` | +| **Platform-scoped** | `ENABLE` + `FORCE`, and role-qualified per-command policies: the read is widened by an explicitly declared non-tenant predicate, and writes have exact declared owners | `platform_host_to_tenant`, `platform_killswitches`, `identity_authority` (P03-1 Step 3) | | **Infrastructure control** | `ENABLE` + `FORCE`, no app policy or privilege; enumerated confined bypass control access under ADR-0047 | `background_job_recurrences`, `background_job_occurrences` | | **Vendor control** | Pinned stock schema with exact confined role grants and metadata guards under ADR-0047; no tenant payload or app access | The twelve Hangfire schema-23 tables; canonical vendor contract below | +| **Global self-identity** | `ENABLE` + `FORCE`, DbContext-parameterized self filter and exact role-qualified policies/guards in the [Identity storage contract](#identity-storage-contract) | `users` (P03-1 Step 3) | + +The adopted contextual population adds `memberships`, `membership_profiles` and +`membership_role_assignments` to tenant-owned org-scoped, and `roles` and +`role_permission_grants` to tenant-owned tenant-wide in Step 4. `audit_log` retains +its tenant/org semantics with the [named global branch](#global-central-audit-branch). **The EF query filter follows the class.** It is the second layer, not a restatement of the policy: the filter is what a handler's `IQueryable` meets, the policy is what still @@ -581,15 +611,21 @@ drops the other tenants' rows when the filter is missing. `TenantId` property and still takes no filter — the property is not the test, the class is. `platform_killswitches` takes none either, and could not: it carries no tenant column for a filter to key on. +- **Global self-identity** — the immutable verified authority/subject-key filter + specified in the [Identity contract](#global-class-and-authority-anchor), never + a tenant predicate or UserId-only filter. -**A table is platform-scoped only when no tenant predicate can isolate it.** Two tables -qualify, in two shapes. `platform_host_to_tenant` is read **before the tenant is known**, +**A table is platform-scoped only when no tenant predicate can isolate it.** Three +implemented tables qualify. `platform_host_to_tenant` is read **before the tenant is known**, so a tenant-keyed policy returns nothing on the path that decides the tenant. `platform_killswitches` is read inside a tenant request and still has no tenant of its own — [ADR-0045 § 5](../decisions/0045-entitlement-and-feature-flag-socket.md) is the decision this rule asked for, and the class fits for the stated reason rather than by analogy: the rows belong to no tenant, so there is nothing for a tenant predicate to -isolate. A third platform-scoped table is still a decision, not a convenience. ADR-0047 +isolate. Accepted ADR-0072 adds the third, `identity_authority`, as a singleton +deployment authority anchor with no tenant/person content. Its migration and +explicit deployment installer are implemented in P03-1 Step 3. +Another platform-scoped table requires a decision. ADR-0047 separately accepts the infrastructure-control and vendor-control classes above; these carry neither tenant content nor general Platform-role access. @@ -639,7 +675,7 @@ security bypassed, so a duplicate-slug insert reveals that *some* tenant already the slug. That is accepted here because slugs appear in hostnames and are public by construction. -**Exactly two columns carry that cost.** The second is `tenant_domains.host`, and for +**Two public hostname columns carry that cost.** The second is `tenant_domains.host`, and for the same reason stated the other way round: a host resolving to two tenants is unresolvable no matter who owns it, so global uniqueness is not a convenience but the constraint the resolver depends on. Its index is **partial** — @@ -648,15 +684,20 @@ soft-deleted claim hold a hostname forever, and [ADR-0036](../decisions/0036-tenant-resolution-trusted-inputs.md) contemplates a released-then-re-registered domain. -Adding a third is a decision, not a convenience. Every other tenant-owned natural key -is `UNIQUE (tenant_id, …)`. +ADR-0072 adds only the authority anchor's permanent `authority_id` and global +User's permanent `(authority_id, subject_key)` binding as identity uniqueness +exceptions. Their [canonical contract](#global-class-and-authority-anchor) is +implemented in Step 3 and never releases a binding through a partial index. Every other +tenant-owned natural key is `UNIQUE (tenant_id, …)`; another exception needs a decision. #### `audit_log` and `audit_config` — one chain, two classes -`audit_log` is **tenant-owned, org-scoped** and takes the template above -**unmodified** — `ENABLE` + `FORCE`, one permissive policy `AND`-ing the tenant term -with the organization term, an explicit `WITH CHECK`, and both `AS RESTRICTIVE` guards. -It carries `organization_id`, and the class follows the column. +`audit_log` is **tenant-owned, org-scoped**. Its ordinary tenant/org predicate +semantics, ENABLE/FORCE, explicit WITH CHECK and restrictive guards remain. +Accepted ADR-0072 adds only the [global identity policy/insertion/evidence +branch](#global-central-audit-branch); it no longer takes the template unmodified. +The reusable tenant template above is unchanged. P03-1 Step 3 installs and +qualifies the exact applied global branch and reciprocal evidence guards. `audit_config` is **tenant-owned, tenant-wide**. It has no `organization_id` column — its overrides are keyed `(tenant_id, module, operation)`, and nothing asks a tenant to @@ -666,10 +707,10 @@ class gives, no restrictive write guards. [ADR-0044 § 9](../decisions/0044-audit-write-path.md) put both tables in the org-scoped class; its Amendment 1 corrects that, and this is the corrected reading. -Both take their policy from the class, so none is restated here: a template copied for -one more table is how the corpus last shipped a broken policy into four files at once. +The reusable class policy and the named Identity exception each have one canonical +owner in this document; neither is copied here. -`audit_log` takes the class's **policy** unmodified and deliberately not the template's +`audit_log` deliberately omits the template's `ix_
_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 high-volume append-only table is a write cost paid on every row for a predicate arm @@ -915,6 +956,13 @@ closed; a fifth role requires an ADR. | `learnstack_platform` | `ConnectionStrings:PlatformAdmin` | API host, worker host | `EnterPlatformAdminScope(reason)` and nothing else | `BYPASSRLS` | | `learnstack_outbox_admin` | `ConnectionStrings:OutboxDispatcher` | API host only; never Seeder or web | confined dispatcher infrastructure only | `BYPASSRLS` | +Migration **credentials** remain deploy-only. The five [enumerated Identity +SECURITY DEFINER contracts](#confined-owner-functions) deliberately add runtime +execution as the migration owner on an app transaction under FORCE RLS. Exact +owner-policy, guard, body, privilege and caller confinement replaces any claim +that owner execution is absent. The applied Identity chain installs these +functions; its actual body/privilege/caller controls qualify their confinement. + **Passwords arrive from the environment, through `\getenv`.** The four `:'name'` placeholders below are **psql client variables**, and the `docker-entrypoint-initdb.d` runner binds none of them: measured, the script as @@ -1005,10 +1053,19 @@ that bound. #### GRANT matrix `—` means no privilege. `learnstack_migration` owns every table, which carries all -privileges implicitly. +privileges implicitly. The matrix records current applied grants. Global +[Identity grants/functions](#global-owners-and-privileges) are implemented in +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 | — | — | +| `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 | — | — | | `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` | — | @@ -1366,13 +1423,17 @@ changes `xmin` while leaving `row_version` intact. `WHERE deleted_at IS NULL`.** A table-wide one lets a deleted row hold its key forever, and where soft delete is the only way to change a row — `audit_config` has no setter, so an override changes by deleting it and declaring a fresh one — the second write fails - `23505` for good. Two shapes are exempt, and the rule - [`Unique_Indexes_On_Soft_Deletable_Tables_Exclude_Deleted_Rows`](21-architecture-tests-catalogue.md#unique_indexes_on_soft_deletable_tables_exclude_deleted_rows) - names both: an index containing the whole primary key, which is a foreign-key target + `23505` for good. The recorded exceptions are named by + [`Unique_Indexes_On_Soft_Deletable_Tables_Exclude_Deleted_Rows`](21-architecture-tests-catalogue.md#unique_indexes_on_soft_deletable_tables_exclude_deleted_rows): + an index containing the whole primary key, which is a foreign-key target rather than a natural key and can never collide with a successor; and `ux_tenants_slug`, held table-wide **by decision** — a tenant slug is a hostname, and whether a terminated tenant's slug may ever be reissued is [Phase 02c](../roadmap/phase-02c-hub-foundation.md)'s call. + ADR-0072 additionally holds the global User binding permanently under its + [Identity contract](#global-class-and-authority-anchor): closure leaves the + inherited deletion fields NULL, and the binding index has no partial predicate. + Its model convention and applied-schema controls are implemented in Step 3. - Scheduled purge job removes rows past retention. ## Migrations @@ -1410,6 +1471,10 @@ changes `xmin` while leaving `row_version` intact. still uses it is not a valid rollback order. Fresh application, reversed application and reapplication belong to the migration-chain integration proof. +- Accepted ADR-0072's sixth migration chain (Identity) additionally requires Audit before + invoking the [central creation-witness installer](#lock-snapshot-and-adoption-conditions). + Step 3 implements recipe/fixture ordering and applied-schema proof. Disposable + reversal removes Identity before Audit; live recovery stays forward-only. ## Data Migrations @@ -4161,6 +4226,463 @@ simultaneously busy connections or a tight empirical minimum. Later SQL lanes require a new census and requalification; Phase 11 owns measured production capacity and PgBouncer. + + +## Identity storage contract + +**Status: Global/contextual storage and common audit implemented.** Derived from +[ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md), +[ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md) and +[ADR-0074](../decisions/0074-membership-admission-under-ordered-locks.md). +The active clauses above adopt the bounded exceptions below. Current applied +global tables, grants, three global owner functions, two contextual functions and +five contextual tables are implemented. The four login roles are unchanged. +The [Identity specification](../modules/identity/README.md) owns the adopted +Membership, profile, Role and assignment shapes; this annex owns their database +authority boundary and the global exceptions. +P03-1 delivers the internal creation core, seed adoption and ordinary +existing-binding lookup. New-user HTTP/native-BFF activation belongs to P03-3; +this annex adds no P03-1 HTTP endpoint. + + + +### Global class and authority anchor + +`users` belongs to a seventh, **global self-identity**, class. It has no tenant or +organization column. ENABLE/FORCE RLS and a DbContext-parameterized EF filter +independently restrict ordinary reads to the immutable verified authority/subject +key. Missing, reset or malformed authority cannot select a row. The filter uses +the current scoped values, never a model-cache literal, raw caller input or only +UserId. The global class is not an exemption from transaction/capture guards. + +| Relation / field | Implemented global storage contract | +|---|---| +| `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.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. | + +The authority anchor is installed once using the deploy/installer's migration +credential, before bootstrap is enabled. It is not derived anew from a changed +issuer URL, realm import or application restart. Application configuration must +match its exact current issuer; mismatch refuses admission without allocating a +new authority or binding. `learnstack_app` has SELECT only on the anchor, with an +explicit platform read predicate; it has no INSERT, UPDATE or DELETE privilege. +The owner has an explicit installation policy under FORCE RLS. The installer +refuses an existing conflicting anchor instead of repairing it automatically. +Qualify the anchor/configuration pair before enabling identity admission; the +request path uses that immutable admitted configuration and performs no anchor +lookup before the subject quota. A changed pair requires requalification, not +live replacement of a request's verified authority. +P03-9/G13 owns a future controlled issuer rebind with verified continuity and a +freeze boundary; no runtime rebind owner is admitted here. + +**Canonical subject-key encoding.** Compute SHA-256 over three concatenated +length-prefixed byte strings: UTF-8 `learnstack.identity.subject.v1`, the stable +AuthorityId's 16 UUID bytes in RFC/network byte order, and the exact opaque +subject's UTF-8 bytes. Each length is an unsigned 32-bit big-endian byte count. +Do not use the issuer URL, .NET's mixed-endian UUID array representation, trimming +or case folding. The verified-subject owner computes the key; a request supplies +neither it nor AuthorityId. An Active match with a different retained raw subject +refuses as a collision, without aliasing, repair or a new actor. A Closed key +always refuses even though its raw subject is gone. The digest remains linkable +personal data; it is neither anonymisation nor authentication authority. + + + +### Global owners and privileges + +The four login roles remain unchanged. Global runtime owners connect as +`learnstack_app`, NOBYPASSRLS. Each transaction announces only its verified +`app.identity_authority_id` and `app.identity_subject_key` (canonical lowercase +hex of the 32-byte key), using parameterized transaction-local setters. Neither +the platform sentinel nor any other tenant is announced. The owner binds those +values immutably to its actual connection/transaction; pool reuse, cancellation, +rollback and nested calls cannot retain or retarget them. Global and tenant +owners cannot join each other's transaction mode. + +Internal lookup, seed adoption and reconciliation are implemented. New-user +bootstrap activation remains P03-3. + +| Owner contract | Granted operation and lifetime | +|---|---| +| Global self lookup | Short physically READ ONLY app transaction; exact authority/key query, retained-subject collision check and status check; closes before tenant resolution. No allocation or mutation intent. | +| Global bootstrap | One READ COMMITTED app transaction; subject-key advisory lock, fresh lookup, allocation only when absent, first User INSERT and central MUST audit, then commit. A unique constraint is the final concurrent-write backstop. | +| Trusted seed adoption | Separately enumerated development owner with credential-free verified provider facts and fixed seed actor; same global insertion/audit guards, never ordinary HTTP adoption. | +| Global audit reconciliation | New central owner for one captured failed/indeterminate creation intent, with the captured subject announcement and its own bounded app transaction; no general sentinel writer. | + +**Prepared owner and creation reference.** The common coordinators extend +the existing `PreparedDeliveryOwner` lifetime pattern. The implemented +`PreparedGlobalIdentityOwner` has a distinct global authority kind; +ReadOnly/ReadWrite alone cannot distinguish tenant/global owners. + +1. The exact internal descriptor prepares a fresh physical READ COMMITTED owner, + with no inherited tenant, audit frame or transaction. Its single-use handle + binds the actual unit, connection, transaction, generation, verified subject + and fixed source. The new identity setter clears unrelated tenant authority, + announces the verified identity scope and never calls a tenant setter. +2. Await the exclusive subject-key advisory lock, then freshly read the exact + binding. An eligible existing binding returns its actor without allocation, + creation intent or creation-handler construction. Collision/nonadmission also + declares no mutation intent. The prepared handle owns cleanup on every exit. +3. Only serialized absence enters the common audit coordinator's typed global + entry. It checks the central MUST catalogue, opens the capture frame and + allocates the target actor and creation intent. An immutable, narrow + `GlobalIdentityCreationReference` exposes the exact audit `(id, timestamp)` to + this invocation's deferred handler; subject, target, source and owner binding cannot be replaced + by a handler, request or a second intent lookup. +4. The common transaction coordinator consumes the original prepared owner once, + constructs/invokes the handler and flushes its tracked User with that reference. + The central pending seam composes/writes the success row on this same physical + transaction. The ordinary common frame still owns completion, outcome reporting + and cleanup; the outer audit frame still owns reconciliation and clearing. + +Unconsumed, foreign, stale, disposed or reused handles refuse and clean up their +own frame. No private Identity audit writer, replacement transaction, synthetic +tenant context or handler-owned capture manipulation is admitted. + +`users` grants app SELECT and column-level INSERT only for the declared initial +identity, status, creation-reference and inherited creation fields. It grants no +app UPDATE, DELETE or TRUNCATE, no profile refresh and no directory read. Its one +permissive isolation policy has role-qualified app self and `learnstack_migration` +owner arms in USING. These are row-visibility predicates, **not SELECT-only +policies**: USING also selects UPDATE/DELETE targets. Explicit WITH CHECK admits +only app self-qualified initial values; grants and command-specific creation/ +immutability guards confine those values to the first INSERT. Unconditional +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. + + + +### Global central-audit branch + +`TenantId.PlatformSentinel` gains a second explicitly named attribution class: +global identity creation, including its failed/indeterminate attempts. It remains +storage attribution, never tenant authority. The discriminator is the conjunction +of sentinel tenant, NULL organization, module `identity`, operation +`identity.user.create`, MUST/SecurityEvent, and closed `metadata.identity_source` +`identity-bootstrap` or `identity-seed-adoption`. Source is fixed by the admitted +owner, never by the body. The existing platform-admin class and its writer remain +distinct. Audit metadata carries the verified `identity_authority_id` and +`identity_subject_key`; it contains neither raw issuer/subject nor credentials. +Extend `AuditIntent`, captured attribution and the shared `AuditDraftComposer` +with a closed typed global-creation value carrying this scope, source, target and +creation reference. Central composition generates the metadata for both success +and reconciliation; no arbitrary metadata/draft port is exposed. Bootstrap's +authenticated audit actor is NULL; seed adoption uses its fixed SystemActor. + +This is the adopted bounded departure from `audit_log` taking the tenant +template **unmodified**, not a change to the reusable tenant template: + +- Keep one permissive isolation policy. Its USING retains the ordinary tenant/org + branch with exactly the existing semantics, and adds only an explicitly + `current_user = 'learnstack_migration'` global-identity evidence-read arm with + the complete discriminator above. App tenant readers and direct self reads + receive no global SELECT arm. There is no general owner/platform sentinel arm. +- Its explicit WITH CHECK retains the ordinary tenant/org branch exactly, and + adds the app-role global-identity branch bound to the verified authority/key, + admitted global owner, exact discriminator and target. The new branch is + INSERT-only through the command-specific global insertion guard; WITH CHECK + alone does not distinguish INSERT from UPDATE. Absent app UPDATE/DELETE grants, + existing restrictive org guards and append-only enforcement remain in place. +- The global guard requires the row's captured subject/key, source, operation and + target to agree with the enrolled physical owner. A missing owner, foreign + subject, caller-supplied metadata or another sentinel operation refuses. A + transaction-local string alone is not the owner's provenance proof. +- Central methods `WriteGlobalIdentityPendingAsync` and + `ReconcileGlobalIdentityAsync` are the only new writer paths. The former accepts + only the enrolled live business transaction; the latter only its captured + typed non-success intent. Ordinary `WritePendingAsync` explicitly refuses + sentinel/global intents and global owners before batch SQL. + Standalone/best-effort sentinel refusals stay. + Ordinary audit entry, transaction entry and tenant/provisioning setters reject + global enrollment before declaration, joining or announcement. EF command and + capture admission accept only the exact Identity owner/transaction, never a + blanket unresolved-context or table-name exemption. Global entry rejects tenant, + provisioning, delivery, job and platform nesting. `WritePlatformScopeAsync` + rejects the global discriminator; its platform class and the exact terminal + event/job seams remain separate. No global owner receives producer/outbox + tenant-announcement authority. +- A success row and its first User mutually validate the complete audit key, + authority/key, target actor, source, operation and successful outcome through + deferred insertion guards on the same transaction. A failed/indeterminate row + requires no User witness and cannot satisfy that reciprocal success guard; + neither its presence nor successful validation proves User absence. + Reconciliation preserves the intent ID and takes a fresh standalone timestamp. + Exact-key duplicates require the bounded evidence read below; a 23505 by itself + never proves a matching audit row or a business COMMIT. + +After the final business/audit writes, await `SET CONSTRAINTS ALL IMMEDIATE` on +the enrolled owner **before** the common coordinator's committing flag/commit +admission. No later mutation, intent declaration, callback or reset to DEFERRED +is permitted. A guard refusal follows the existing precommit rollback path and +failed reconciliation. The deferred guards remain a database backstop for an +omitted preflight. Physical COMMIT faults retain the existing uncertain-outcome +contract; successful preflight, cancellation and cleanup are not COMMIT evidence. +No blanket SQLSTATE-to-rollback inference is introduced. + +Global classification reads the central baseline catalogue directly; no tenant +AuditConfig lookup or suppression allowance applies. Ordinary binding reads make +no mutation intent. P03-9/G13 owns privileged global audit consumption; this +contract adds no user or tenant endpoint for those rows. Existing retention and +permitted redaction remain separate from insertion-time witness validation. + + + +### Confined owner functions + +The first three functions are installed in Step 3; the two Membership functions +are installed in Step 4. All execute as +`learnstack_migration`, NOBYPASSRLS, under FORCE RLS, on the caller's existing +physical transaction. No migration credential enters runtime configuration. +SECURITY DEFINER adds the explicitly accepted runtime owner-execution exception; +it is not ordinary app isolation. Acceptance alone installed no function; the +Step 3 migration installs only its qualified global subset; Step 4's forward +migration installs the contextual pair. + +| Function contract | Bound input / permitted result | +|---|---| +| `fn_identity_user_creation_audit_guard()` | Deferred User INSERT trigger; reads only the exact creation audit key and verifies the complete global discriminator/subject/target/outcome. Returns no audit row. | +| `fn_identity_audit_creation_guard()` | Deferred global audit INSERT trigger; verifies the exact User creation reference for success, or the captured subject/target and non-success class for reconciliation. Returns no User/profile row. | +| `fn_identity_audit_evidence(id, timestamp, authority_id, subject_key, target_id, source, outcome)` | Central duplicate checker only; all inputs come from its captured intent and must agree with the transaction's announced authority/key. Returns a Boolean exact match of the complete audit key, discriminator, subject, target, source and outcome, never metadata/profile/list data. | +| `fn_identity_membership_admission_guard()` | Membership INSERT, Suspended-to-Active and every assignment-addition trigger; target comes from the actual Membership or its tenant-composite parent. Verifies its already-held exclusive User fence and freshly checks eligibility before mutation, including after the complete ordered plan holds tenant fences. Acquires no User key; returns no User fields. | +| `fn_identity_admin_admission_state(user_id, tenant_id)` | Last-admin guard only; target must be a candidate Membership in the already admitted tenant invariant check. Returns one admission Boolean; takes no second User lock while holding the tenant lock. | + +These functions have fixed `search_path = pg_catalog`, schema-qualified relations, +no dynamic SQL, no identity/tenant setters and no provider/person-field projection. +Revoke PUBLIC execution in the same migration transaction that creates them; +grant app execution only for the enumerated callable contracts. Trigger functions +are entered only by their declared table/command; no generic UserId probe or SQL +executor is exposed. Exact function-body, ownership, privilege, trigger and +call-site census controls reject widening or an additional definer function. + +After a unique error, evidence runs on a clean bounded reconciliation transaction, +not the aborted INSERT transaction. Only a matching exact key can be swallowed; +missing, mismatched or unavailable evidence follows the central failure/health +contract. Original-success evidence uses the intent's original declaration key +and reciprocal User creation reference. A fresh failed/indeterminate duplicate +proves only that exact audit row is durable; it cannot establish business success. +An original success and fresh indeterminate row may coexist after a lost COMMIT +acknowledgement. The function never substitutes another timestamp or outcome. + +The owner-read arms are role-qualified inside each relation's single isolation +policy. The audit arm admits only the global identity discriminator, not tenant +or platform-admin evidence. Every function also uses its own exact key predicate; +an existing tenant GUC cannot widen its query through the ordinary policy branch. +User reads project only admission status or the identity/creation-reference fields +required by the named guards. Table ownership inherently carries column +privileges: this is confinement of function projections and call sites, not a +claim that column grants restrict the owner to those columns. + +The historical host-lookup definer rejection above remains its historical +decision: that table's policies grant the owner no read. This contract instead +explicitly admits narrow owner reads for a new class and the global audit branch. +It adds neither BYPASSRLS nor a fifth login role, and changes no existing host +lookup. The alternatives and their trade-offs belong to ADR-0072. + + + +### Lock, snapshot and adoption conditions + +The in-memory enrollment marker is checked by the common transaction/capture +coordinator and central writer against the actual connection/generation. SQL +policies cannot inspect that CLR marker or validate JWT signatures: they enforce +the announced values, role and exact row constraints. As with tenant GUCs, a +compromised application SQL credential is not made safe by a context string. +No hidden enrollment table or purported database JWT verifier is introduced. + +Global audit policy/guard SQL belongs to central Audit infrastructure. The first +Identity migration invokes its enumerated installer on the migration connection, +after the existing Audit schema prerequisite. The bounded, implemented +`IdentityCreationWitnessInstaller` exception admits only installation of the two +reciprocal creation guards and exact evidence function over the declared User creation +reference and Audit discriminator fields. Identity migration/handler source +contains no copied audit SQL; core infrastructure gains no module assembly/entity +reference. The exception permits no general cross-module joins or additional +Audit writer. Exact installer, function-body, table-reference and call-site +censuses extend the existing module/audit SQL guards; the sixth migration chain +and prerequisite order receive independent applied-schema proof. + +Contextual lifecycle, scope-compatibility and final-admin guards are SECURITY +INVOKER, with fixed search path and canonical tenant context. They use the named +state-only owner function only for global eligibility. Every Membership mutation +must leave an eligible tenant-wide Tenant Admin, including first creation; +protected Role/kernel changes cannot remove that minimum. Role initialization +may precede any Membership. Completion is derived from actual approved templates +and that admin, never an ordinarily writable flag. Trial, Active and Suspended +tenants preserve administration; Archived supplies no implicit exception. This +closes only Membership/Role mutations, not the future Tenancy archive workflow. + +**Canonical advisory key.** SHA-256 hashes a sequence of unsigned-32-bit +big-endian-length-prefixed byte strings: UTF-8 `learnstack.identity.lock.v1`, +UTF-8 lock kind (`subject`, `user`, or `tenant`), then either AuthorityId's 16 +RFC/network-order UUID bytes and the 32-byte subject digest (`subject`), or the +corresponding UserId/TenantId's 16 network-order UUID bytes. Interpret the first +eight digest bytes as a signed two's-complement big-endian 64-bit PostgreSQL +advisory key. Application and SQL implementations use identical fixed test +vectors; neither runtime hash functions nor .NET mixed-endian UUID bytes qualify. +Collisions serialize unrelated work only; exact row predicates remain mandatory. + +Bootstrap takes its exclusive subject key before reading absence. Membership +creation/reactivation and **all** assignment additions take the target User's +exclusive admission key before any tenant key. Tenant keys use SHARED mode for +profile, nonadministrator and organization-scoped mutations; first-admin +creation, administrator eligibility/assignment changes and protected Role/kernel +changes use EXCLUSIVE mode. Derive the strongest required mode from actual +OLD/NEW transitions and protected capabilities before locking, not a caller's +label. Acquire all required User keys, then tenant keys, in stable order within +each family; never upgrade a held shared tenant lock or acquire another User +key beneath it. Ambiguous or post-wait changed classification refuses, rather +than upgrading. A multi-write owner acquires its strongest complete lock set +before mutation. Last-admin checks acquire no further User key. + +Closed seed authority and scope lifecycle are checked before lock acquisition; +P03-2 owns live permission checks. Revalidate actual scope/Role/parent facts in +a separate fresh post-wait read before mutation. For the admission operations +above, the real BEFORE trigger freshly checks global eligibility while the +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. +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 +admitted by this read-timing change under ADR-0074. + +Both modes freshly verify the total eligible tenant-wide-admin invariant for +every Membership/child mutation and protected post-initialization Role change. +The finite first Role-creation acts have their separate SHARED-lock exception: +freshly require that no Membership has existed in the tenant and that the exact +admitted initial manifest/source is being created. Existing Role edits, grant +upgrades and repairs cannot use that exception. First-admin creation takes +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 +the final administrator ineligible without a +separately accepted recovery/termination contract; closure and Archived status +are not implicit exceptions. + +All these writer/guard transactions use READ COMMITTED and reject incompatible +isolation. Functions are VOLATILE. Await the advisory-lock statement, then issue +a separate fresh read; no STABLE function, pre-wait snapshot or cached state can +decide admission. Use a transaction-local two-second `lock_timeout` default and a +command/cancellation deadline within the existing ten-second native API budget. +Timeout/cancellation refuses without partial grants or allocation retry. Lost +commit responses remain uncertain; cleanup and central reconciliation retain +their independent bounded ownership after caller cancellation. + +The closed `ContextualIdentityStorageControl` saves one complete Role or Membership +graph on that owner. During only that tracked save it suspends EF's automatic +savepoints, restoring the previous flag in `finally`; every save failure poisons +the whole unit. No partial repair or save retry is admitted. This lets the finite +initial-Role guard verify its tuple's `xmin` against the current top transaction +both during mutation and after `SaveChanges`, without a released-subtransaction +lock or snapshot heuristic. Ordinary module contexts and global binding saves +retain automatic savepoints. The exact adapter/caller census and real success, +constraint-failure and cancellation controls prove restoration, full rollback +and the unchanged sibling-context default. The common coordinator still owns +physical commit and central MUST durability. + +#### Membership fence checks + +The trigger observes `pg_catalog.pg_locks` using all of these predicates: + +| Predicate | Required value | +|---|---| +| `pid` | `pg_catalog.pg_backend_pid()` | +| `database` | OID from `pg_catalog.pg_database` for `pg_catalog.current_database()` | +| `locktype`, `granted`, `mode` | `advisory`, true, `ExclusiveLock` | +| `objsubid` | 1: the single-bigint namespace, not the two-integer overload | +| `(classid::bigint << 32) \| objid::bigint` | Exact signed canonical User key derived from the actual target | + +Missing, wrong-key, shared-only, foreign-backend/database or wrong-namespace +observations refuse. The trigger makes no acquisition call, including no +`pg_try_advisory_xact_lock`: a try-lock can acquire a missing key and is not an +ownership observation. Any tenant-fence mode observation uses the corresponding +actual canonical tenant key and strongest required mode. + +This proves current backend heldness and mode only. `pg_locks` cannot distinguish +session-level from transaction-level advisory ownership, reconstruct historical +order, prove future lifetime or authenticate a CLR caller. Session-only ownership +can satisfy the SQL predicate; it is not an admitted writer substitute. Closed +production helper/caller censuses require transaction-level APIs, an actual +owning unit/connection/transaction/generation and a lock plan completed before +data-mutating statements. Session acquisition/unlock APIs and out-of-order +production calls fail those controls. Actual commit/rollback/savepoint and pool- +reuse controls qualify continuous lifetime. SQL cannot retroactively validate +arbitrary lock calls made through a compromised application SQL credential. + +The view is not a frozen cluster snapshot. Qualification verifies own-backend +observations under contention and the wrong-key/backend/database/namespace cases; +it does not infer ownership from another process's row. Per-admission-row view +collection can affect lock-manager contention and is included in actual +trigger-path/query/pool measurements under the existing write-p95 budget. + +Missing or insufficient fencing is a fixed internal **plan fault**, distinct +from an expected **target refusal** for unknown/Closing/Closed User. Adapters +translate both to the same fixed outward refusal without constraint/target +details; unknown and nonadmitting targets remain indistinguishable. Plan faults +emit the existing closed lock-refusal `fault` signal once per operation; target +refusals do not pretend lock acquisition failed. Fixed internal descriptors, +not provider exception text or identity labels, retain diagnostic distinction. + +Step 4's closure competitors are explicit fixture accommodations in disposable +databases: preserve original guard/policy definitions, narrowly disable only +`tg_users_no_update` and add an owner-only fixture WITH CHECK arm for the fixed +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. + + + +### Applied census and qualification + +The Step 3 census was **seven table classes, 44 data tables plus six +history tables, six migration chains, eight central audit write seams and three +Identity SECURITY DEFINER functions**: 50 tables total. The applied Step 4 +census is **seven classes, 49 data tables plus six history tables, six +chains, eight central audit write seams and exactly five Identity SECURITY DEFINER +functions**: 55 tables total. Step 4 adds the five contextual tables and two +contextual owner functions to the existing Identity chain. +The global pair and sixth history table/chain are applied in Step 3. The two +global seams extend the earlier six without a new INSERT owner. + +Steps 3/4 must qualify actual app-role positive/negative paths, owner DELETE/ +TRUNCATE refusal, exact definer bodies/ownership/grants/projections/call sites, +ordinary/global seam refusals, matching/mismatched creation and duplicate evidence, +precommit guard refusal versus lost-COMMIT uncertainty, stale/foreign/reused owner +handles and pooled cleanup. Lock proof requires a held lock and a **real competing +commit**, followed by the waiting transaction's fresh read; mocks or two reads +without contention do not qualify. Include shared/exclusive blocking, forbidden +upgrade and final-admin/closure races. Step 5 qualifies ordinary existing-binding +lookup before/after latency, pool occupancy and cancellation/cleanup under load; +P03-3 separately qualifies the new-user HTTP/BFF transport. The +[catalogue](21-architecture-tests-catalogue.md#pending-identity-extensions-to-implemented-rules) +owns the implemented foundation obligations; the +[phase Status block](../roadmap/phase-03-identity-admin.md) owns current +qualification state. Documentation checks establish none of these runtime proofs. + +Step 4 includes exact backend/database/bigint-key and mode observations, both +signed User/Tenant C#/SQL vectors, wrong/shared/foreign/missing ownership and +transaction-end/pool-reuse controls. A session-only fixture demonstrates the +observation limit; actual writer/caller controls reject session APIs. The actual +first-seed-admin command succeeds under its complete plan; second-admin subjects +remain fixture-local. Profile/removal controls prove no automatic User lock. +Representative trigger-path p95/query/pool measurements include repeated view +collection and contention. Complete-graph constraint preflight and forced central +MUST failure prove rollback without reclassifying unknown physical COMMITs. + ## Backups - Daily logical backups (`pg_dump`) for dev-grade restore. diff --git a/docs/standards/06-testing.md b/docs/standards/06-testing.md index 5cc40c053..03f852b00 100644 --- a/docs/standards/06-testing.md +++ b/docs/standards/06-testing.md @@ -11,6 +11,8 @@ The seeded browser/audit proof derives from [ADR-0056](../decisions/0056-public-demo-browser-and-lighthouse-enforcement.md). Native admission, stock-browser fallback and HMR proof controls derive from [ADR-0055](../decisions/0055-public-renderer-bootstrap-failures.md). +The ordinary CI window derives from +[ADR-0075](../decisions/0075-ordinary-ci-job-window.md). UI localization controls derive from [ADR-0027](../decisions/0027-frontend-i18n.md) and the [Accepted P02d-6 package](../roadmap/phase-02d-delivery-log.md#p02d-6-decision-package-2026-10-09). @@ -214,9 +216,17 @@ Matching worker digests alone cannot replace API or result evidence. Base/Architecture use only the approved non-root child and owned systemd/cgroup boundary on exclusive Ubuntu 24.04 VMs: no Docker census/disposal, collector access or crash inventory. Ordinary retains Docker ownership; native alone -retains collector provisioning and independent crash assertions. Every execution -keeps twenty minutes, both aggregates five minutes, and meta five minutes. The -new offline plan/result controls share one thirty-second allocation in meta. +retains collector provisioning and independent crash assertions. +[ADR-0075](../decisions/0075-ordinary-ci-job-window.md) gives only verified ordinary +producers a twenty-five-minute whole-job ceiling. Base/Architecture/native keep +twenty minutes, both aggregates five minutes, and meta five minutes. The +203-second cleanup/export/upload reserve and test-specific deadlines stay fixed. +Expected verified producer identity selects API, receipt and enclosing +measurement bounds; a receipt partition or global observation-limit increase +cannot grant ordinary authority. The four disjoint receipt intervals sum below +that producer's ceiling; nested workload/project observations are not additional +disjoint time. The offline plan/result controls share one thirty-second +allocation in meta. Actual SDK/console/loaded-adapter hashes, disjoint phase intervals, first-result gaps and scoped resource observations accompany every successful execution. Uninstrumented fixture/container measurements remain unknown. @@ -435,9 +445,10 @@ Use the shipped examples: Fixtures apply every chain through [MigrationChains](../../backend/tests/LearnStack.Tests.Integration/Database/MigrationChains.cs), -which owns current chain/history discovery. The current schema has five chains, -21 data tables and five history tables; tests must not copy a fixed partial chain -list. Follow [add-integration-test](../../.claude/skills/add-integration-test/SKILL.md) +which owns current chain/history discovery. +[`SchemaTableClasses`](../../backend/tests/LearnStack.Tests.Integration/Database/SchemaTableClasses.cs) +independently checks the complete applied-table census; tests must not copy a +fixed partial chain list. Follow [add-integration-test](../../.claude/skills/add-integration-test/SKILL.md) for fixture selection and transaction-scoped context. Rules: diff --git a/docs/standards/07-frontend-architecture.md b/docs/standards/07-frontend-architecture.md index 8375ec8bb..735451d99 100644 --- a/docs/standards/07-frontend-architecture.md +++ b/docs/standards/07-frontend-architecture.md @@ -17,6 +17,8 @@ single-bootstrap ownership derives from [ADR-0055](../decisions/0055-public-renderer-bootstrap-failures.md); page composition follows the [Accepted P02d-6 package](../roadmap/phase-02d-delivery-log.md#p02d-6-decision-package-2026-10-09). +The existing-session Identity foundation boundary derives from Accepted +[ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md). Next.js App Router layout, tenant resolution, SDK shape, and runtime concerns for the tenant-facing `apps/web` application in *this* repository. See @@ -257,6 +259,12 @@ owns the source, pin, diff policy, bootstrap exception and required-check rollou - Server Components use the app-local read-only `auth()` projection. Response owners perform refresh/idle/cookie updates before streaming. Never expose credentials to Client Components; no Server Action is admitted by P02b-7. +- Accepted ADR-0072 preserves complete native actor/tenant identity, independent + ID-token verification and the matching positive AccountSite witness. P03-1 only + aligns native opaque subject validation to the API's 255-character bound; it + adds no SDK operation or `LoginCompletion` variant. P03-3/G1/G6 owns new-user + HTTP/bootstrap association and typed session/no-session completion decisions + under the [Security activation gate](11-security.md#p03-3-new-user-http-and-native-activation-gate). ## Routing diff --git a/docs/standards/10-observability.md b/docs/standards/10-observability.md index 3d259f972..dc2dc0a45 100644 --- a/docs/standards/10-observability.md +++ b/docs/standards/10-observability.md @@ -25,6 +25,10 @@ Subject-admission refusal and cleanup-fault signals derive from 2026-10-20. Their implementation and local exported proofs are delivered; the [implementation record](../roadmap/phase-02b-delivery-log.md#adr-0066-acceptance-and-implementation-2026-10-20) owns independent reviews and final-source CI qualification. +Identity lock/admission observation derives from Accepted +[ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md), +[ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md) and +[ADR-0074](../decisions/0074-membership-admission-under-ordered-locks.md). Three signals — logs, traces, metrics — bound by a single correlation id. Everything we ship is observable from day one. @@ -439,9 +443,36 @@ backend treat business rejections as system failures. | `learnstack_cache_factory_duration_seconds` | histogram | `cache.name`, `outcome` | | `learnstack_audit_standalone_write_failures_total` | counter | `operation` | | `learnstack_audit_standalone_duplicates_total` | counter | `operation` | +| `learnstack_identity_lock_wait_seconds` | histogram | `lock_kind`, `outcome` | +| `learnstack_identity_lock_refusals_total` | counter | `lock_kind`, `reason` | | `learnstack_entitlement_source_total` | counter | `source` | | `learnstack_entitlement_unresolved_total` | counter | — | +### Identity lock signals + +Accepted ADR-0072/0073/0074 require `lock_kind` closed to `subject`, `user`, `tenant`; +wait `outcome` closed to `acquired`, `timeout`, `cancelled`, `fault`; and refusal +`reason` closed to `timeout`, `cancelled`, `fault`. No tenant, actor, subject, +digest, raw issuer, SQL, correlation or exception text is a label. Typed closed +binding diagnostic reasons remain separate from public Problem Details and are +not trusted identity-refusal witnesses. A contextual lock-plan fault increments +the existing refusal counter exactly once with `reason=fault`. An expected +unknown/nonadmitting target refusal is a separate closed internal classification, +not a lock fault. Both preserve the same outward fixed refusal; no new metric +label or reason is introduced. The +[database contract](05-database.md#lock-snapshot-and-adoption-conditions) owns +their classification and heldness limits. + +Steps 3/4 implement lock signals. Step 4 qualifies `pg_locks` observation on the +actual Membership trigger path: representative before/after local write p95 +against [Standard 15's budgets](15-performance.md#initial-budgets), query cost, +pool occupancy and cancellation/cleanup under ordinary load and contention. +Step 5 separately qualifies ordinary binding lookup plans, local latency and +pool/cancellation behavior. No measured production p95 or extension of ADR-0047 +capacity follows; Phase 11 owns production alert thresholds and sizing. + +### Delivered metric populations + Outbox metrics above are implemented in P02b-2 Step 3 under ADR-0046; both independent review rounds are complete. The subscriber/inbox inventory is accepted by the [P02b-3 package](../roadmap/phase-02b-delivery-log.md#p02b-3-decision-package-2026-10-13); diff --git a/docs/standards/11-security.md b/docs/standards/11-security.md index ca7fd7fe0..690993e08 100644 --- a/docs/standards/11-security.md +++ b/docs/standards/11-security.md @@ -45,6 +45,12 @@ ownership and closed refusal/fault signals derive from [implementation record](../roadmap/phase-02b-delivery-log.md#adr-0066-acceptance-and-implementation-2026-10-20) owns independent reviews and final-source CI qualification. The bound grants no throughput entitlement. +Identity admission/owner contracts additionally derive from Accepted +[ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md), +[ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md) and +[ADR-0074](../decisions/0074-membership-admission-under-ordered-locks.md). +The [phase Status block](../roadmap/phase-03-identity-admin.md) owns current +implementation and qualification state; live membership execution remains P03-2. Bounded authenticated assertion recording derives from [ADR-0065](../decisions/0065-bounded-tenant-assertion-diagnostics.md); its implementation and local proofs are delivered in the @@ -360,7 +366,7 @@ tenant-facing endpoints. Per [ADR-0019](../decisions/0019-learnstack-hub.md) and ## Authorization -Every write use case checks, in order: +Every ordinary tenant write use case checks, in order: 1. **Authentication** (valid token). 2. **Tenant membership** (user has a Membership in the resolved tenant). @@ -368,6 +374,9 @@ Every write use case checks, in order: 4. **Resource scope** (e.g. instructor can only edit their own courses). A failure at any step returns a Problem Details response with the right code (`unauthorized`, `tenant_mismatch`, `forbidden`, `resource_scope_violation`). +The exact internal global-identity creation class instead uses the +[adopted subject-confined owner](#identity-admission-contract), with no tenant +selection or membership authority. It is not a routed HTTP write in P03-1. ## Tenant + Organization Isolation @@ -536,8 +545,9 @@ context writer, factory privilege or tenant retargeting authority. ### The out-of-band setters `TransactionBehavior` delegates the general announcement path to -`TransactionExecutionCoordinator`. Eight logical setter paths exist in -total and the set is closed +`TransactionExecutionCoordinator`. Eight logical setter paths currently exist. +The adopted [candidate-reader extension](#owner-and-setter-census) registers a +ninth for P03-2 implementation; no ninth setter is shipped. The current set is closed ([ADR-0040 § Who sets `app.tenant_id`, completely](../decisions/0040-ambient-unit-of-work.md), with its Amendments 3 and 7, is the authority; it is reproduced here because this section is the placement authority). Two set it on the **ambient** transaction; six own a **short @@ -1010,9 +1020,12 @@ Security-relevant durability rules: tenant-owned and tenant-wide** — it has no `organization_id`, so it carries the tenant term only and no restrictive write guards ([ADR-0044 Amendment 1](../decisions/0044-audit-write-path.md)). Both take the - canonical RLS template for their class from - [05-database.md § Table classes](05-database.md) unmodified — it is not repeated - here, or anywhere else. A tenant admin's read is bounded by the policy, not by the + canonical RLS template for their class in the current applied schema. + [ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md) accepts the + exact global-identity departure for `audit_log`, implemented in Step 3; `audit_config` + remains unmodified. [Database Standards](05-database.md#global-central-audit-branch) + owns that policy, without a second template here. A tenant admin's read is + bounded by the policy, not by the query. `audit_log` carries no foreign key to `tenants`: the record of what happened to a tenant has to outlive the tenant. - **Append-only holds in three layers, and each stops a different actor.** @@ -1036,6 +1049,206 @@ Security-relevant durability rules: cannot be retrofitted, audit scale can. Phase 02a ships `audit_log` as a single plain table ([ADR-0028 Amendment, 2026-09-07](../decisions/0028-audit-log-partition-management.md)). + + +## Identity admission contract + +**Status: Global/contextual storage, common audit, seed and existing-binding API +admission are implemented; live membership execution remains P03-2.** Derived from +[ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md), +[ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md) and +[ADR-0074](../decisions/0074-membership-admission-under-ordered-locks.md). +The bounded global owner below is implemented; this does not activate HTTP +creation or live membership. The current authentication surface, eight tenant +setters and deny-all membership reader remain until their owning steps. The +[adopted database contract](05-database.md#identity-storage-contract) +owns the global class, authority anchor, subject-key encoding, exact policies, +owner functions and lock/snapshot rules; they are not duplicated here. + + + +### Credential, quota and binding order + +Stock cryptographic/provider validation creates an immutable +`VerifiedProviderSubject` projection. It carries the exact validated subject and +issuer, matched to the installed stable authority anchor, plus validated optional +actor/scope evidence. It is distinct from the normalized application identity; +only a successful existing binding lookup creates that identity on P03-1's HTTP +path. Neither raw claims nor a supplied UserId substitutes for either proof. +Present malformed/reserved/duplicate actor or scope claims still refuse; absence +of the compatibility actor claim permits only resolution of an existing Active +binding. Ordinary HTTP never allocates or adopts a User. + +Qualify the authority anchor and configuration before enabling identity admission; +requests use that immutable admitted pair, with no anchor lookup before the quota. +A mismatch refuses without deriving a new authority, repairing the anchor or +using an email. The classified HTTP pipeline remains route-independent: + +| Stage | P03-1 handoff | +|---|---| +| Existing admission and host classification | Preserve visitor/peer/body bounds and precedence; unknown host remains masked 404 before token/provider work. | +| Provider validation and credential-result gate | Produce `VerifiedProviderSubject`; the gate recognizes that verified stage without requiring the later normalized actor. Present invalid/undecidable credentials remain fixed 401 with bare Bearer challenge. | +| Subject admission | Debit the existing validated issuer/sub quota before any binding SQL. Preserve its refusal/fault result and request-local ownership. | +| Existing-binding lookup | Use Standard 05's short physically READ ONLY self owner; resolve the stored actor only for an Active matching subject and absent/equal actor evidence, then close before tenant resolution. | +| Ordinary tenant pipeline | Feed normalized `ValidatedTenantIdentity` into the existing resolver, assertions, authorization and surface admission. No endpoint selects a different resolution outcome or bypasses those stages. | + +The subject quota consumes `VerifiedProviderSubject` before any binding database +access, including ordinary authenticated requests. Its current consumer of an +actor-bearing `ValidatedTenantIdentity` must be replaced explicitly; merely +omitting `user_id` from a token cannot reach that consumer. Preserve the existing +validated issuer/subject key, 600-per-window quota, 4096-partition registry, +retirement/fault protocol, early quotas and refusal precedence. Re-entry consumes +no second permit. A changed actor, tenant, host or bearer never resets the quota; +no application actor is required to debit it. + + + +### Ordinary outcomes and source handoffs + +| Observation | Adopted response / database work | +|---|---| +| Credential-free public GET/HEAD | Existing anonymous behavior; no binding lookup or allocation. | +| AccountSite, absent bearer | Existing masked 404; no binding lookup. This is not the rule for anonymous public reads. | +| AccountSite, admitted valid identity and host-backed authority, wrong method | Existing routing 405 with `Allow: GET`; absent credentials remain masked 404. | +| Subject admission refuses | Existing 429 or registry-fault 503; no binding access. | +| Unknown binding, conflicting actor, collision or Closing/Closed binding | Fixed 401; no allocation, adoption, alias, recreation or replacement actor. | +| Binding lookup unavailable | Fixed 401 under ADR-0064/0071; no anonymous fallback or automatic retry. | +| Active matching binding | Continue ordinary reconciliation with its stored actor; authentication supplies no new membership or scope authority. | + +Error bodies and challenges disclose no claim values or internal refusal detail. +`binding_store_unavailable` is a closed internal diagnostic reason, not a new +public Problem Details code or a trusted identity-refusal witness. Translate +expected binding-store availability failures at the new boundary while preserving +uniform 401; arbitrary exceptions do not establish an identity outcome. ADR-0065's +host-tenant assertion allowance remains independent and supplies no global +creation-audit budget. + +The ordinary API's uniform 401 and ADR-0071's uncertain AccountSite policy remain: +withhold authenticated content, retain the ordinary live owner without idle +renewal, and add no automatic retry/refresh. Initial and refreshed publication +still require the independently verified ID-token identity and matching positive +AccountSite actor/scope witness, with existing late-publication fences. A failed +post-refresh check revokes. The native provider identity still requires complete +actor/tenant claims, and `LoginCompletion` still represents a published session. +Align native opaque subject validation to the API's 255-character bound; no +pre-session optional-actor/tenant projection is introduced here. + +P03-1 adds no POST, SDK operation or endpoint-census entry. Its source changes +must cover the actual handoffs rather than only relaxing a claim parser: + +| Source seam | Required change / preserved boundary | +|---|---| +| `TenantTokenProfile`, `TenantCredentialFeature`, `TenantAuthenticationEvents` | Separate the verified provider subject from normalized application identity; only stock-validated facts enter either stage. | +| `TenantCredentialAdmissionMiddleware` | Recognize verified-subject success before binding normalization; keep invalid-present refusal and absent-credential behavior. | +| `TenantSubjectAdmissionMiddleware`, `TenantSubjectRateLimiter` | Consume the verified stage, retaining issuer/sub key, once-per-request debit and closed quota/capacity/fault outcomes. | +| New binding-admission stage and `TenantResolverMiddleware` | Resolve only existing bindings after quota and before the existing route-independent resolver; no allocation or endpoint-dependent bypass. | +| `TenantAuthenticationPipelineProof` and current HTTP/OpenAPI/SDK controls | Qualify the new stage's order and real owner; retain the exact existing public/AccountSite operation union and native publication contract. | + +### P03-3 new-user HTTP and native activation gate + +P03-3/G1/G6 owns the following decisions before adding a bootstrap HTTP caller. +They are prerequisites, not policies selected or activated by this annex: + +- Provider signup/admission policy and the durable User/creation-audit budget. + The retained subject registry and per-subject quota do not bound lifetime + new-subject cardinality. +- Exact route/method, absent-token and masking behavior, and an explicit bounded + supersession of ADR-0064's prohibition on endpoint-dependent resolution. +- A separate bootstrap caller and exact SDK/OpenAPI ownership, cache/input/body + bounds, verified host/source/hop contract and complete operation census. +- An independently verified pre-session provider projection and exact bootstrap + issuer/subject/actor association before ordinary session publication. +- Typed session/no-session completion with an explicit response, cookie, cleanup + and expiry table, including tenantless success and preservation of an existing + session during a failed replacement. +- Exact native handling of bootstrap 400/401/404/429/503, cancellation and unknown + results, with no automatic mutation retry or inference of rollback from a + missing response. Do not inherit AccountSite's read classification by accident. +- Real actorless and tenantless provider/native controls, wrong association, + response loss, capacity, cancellation and late-publication qualification. + +The necessary ADR-0053/0064/0070 changes and G1/G6 authority acceptance precede +that activation. Standard 05 remains the canonical prepared global owner/audit +contract; its existence admits no HTTP endpoint or native caller. + + + +### Owner and setter census + +Standard 05's global self lookup, prepared creation, trusted seed adoption and +central reconciliation owners announce verified subject authority only. Their +immutable connection/transaction marker is a separate mode of the common guard, +not a table-name exemption or a tenant context. Only their enumerated setters may +announce identity variables derived from verified/captured facts, never payload +or headers. +Missing markers, foreign subject reuse, nested tenant/global ownership and pooled +authority leakage refuse. Ordinary tenant setters, factories and audit writers +must hard-refuse `TenantId.PlatformSentinel` and global owner mode. Ordinary +pending gains its missing explicit refusal before admitting the global branch; +the source-bound requirements are in Standard 05. + +The adopted global audit methods and confined definer functions are enumerated +in Standard 05. Their bounded target/operation/subject evidence is the only new +authority. Sentinel attribution conveys neither PlatformAdminScope nor operator +permission. Runtime never receives a migration credential; the new functions do +execute with migration-owner rights and need their own exact privilege/body/caller +controls before admission. No general SQL executor, global User directory or +direct self audit read follows from them. + +`PreContextIdentityAuthorizationReader` is the planned ninth logical tenant +setter, owned by P03-2 execution under G2. It uses `learnstack_app`, NOBYPASSRLS, +and a short physically READ ONLY transaction. It binds the verified application +actor and exact candidate tenant/organization to a minimal coverage/grant read, +announces only that candidate scope, and closes before the request owner opens. +It installs no `ITenantContext` and returns no profile or member directory. +Candidate scope remains a question; validated identity and the confined reader +contract supply input authority. P03-1 specifies the port/storage contract only. +Accepted ADR-0040's disclosure and this census admit only that ninth logical path; +P03-2 must implement/register/qualify its actual adapter before activation. The +eight current tenant setters remain the implemented set. The global subject +owners do not add tenant setters or ITenantContext writers. + + + +### Bounded contention and pending proof + +Use Standard 05's canonical owner, lock, snapshot, deadline and cleanup contracts; +no second allocation/reconciliation algorithm is defined here. The canonical +[lock signal contract](10-observability.md#identity-lock-signals) owns names and +closed labels. Phase 11 owns production alert thresholds and capacity tuning; +bounded acquisition and cancellation are P03-1 prerequisites. + +ADR-0074's contextual admission contract requires the actual mutation trigger's +fresh target check even when the complete ordered lock plan is preheld. Its +heldness observation does not establish session-versus-transaction ownership, +acquisition history or the CLR caller. Standard 05's closed caller/source and +transaction-lifetime controls supply those separate obligations. Internal +lock-plan faults and expected unknown/nonadmitting target refusals have distinct +closed classifications and the same outward fixed refusal, without a User-state +oracle. Standard 05 owns the exact checks; no general User probe is admitted. + +P03-1 qualification covers actorless API credentials for an existing adopted +binding, unknown/conflicting/closed bindings without allocation, quota before +every binding read, unchanged anonymous/AccountSite method behavior and uniform +401 during store failure. Existing seed provider/native sessions retain their +complete identity and independent AccountSite witness. Standard 05 owns the +creation/audit, RLS, race, reconciliation and owner-cleanup proof obligations; +P03-3 owns new-user HTTP/native qualification above. + +Uncached binding admission adds a database dependency to every authenticated +request, including credential-bearing public reads. Qualify actual app-role lookup +plans, representative before/after local latency, bounded pool checkout and +cancellation/connection cleanup under contention and outage. A lock timeout alone +does not establish pool capacity or a complete request deadline. No measured +production p95 or extension of ADR-0047's qualified capacity follows; Phase 11 +retains production sizing. Step 4 qualifies the actual Membership +trigger's `pg_locks` observation under +[Standard 15's p95 budgets](15-performance.md#initial-budgets), as specified by +the lock signal contract. Its real mutation/race/cleanup and local command-path +measurement controls qualify their recorded contextual scope. Existing-binding +load observations retain their distinct control and scope; live-admission +qualification remains P03-2. None establishes production capacity. + ## Incident Response - A security incident playbook lives in `docs/runbooks/security-incident.md` (Phase 11 deliverable). diff --git a/docs/standards/18-audit-coverage.md b/docs/standards/18-audit-coverage.md index 04ce2362c..c9adc78b1 100644 --- a/docs/standards/18-audit-coverage.md +++ b/docs/standards/18-audit-coverage.md @@ -21,6 +21,9 @@ Job additions derive from [ADR-0047](../decisions/0047-transactional-background-job-runtime.md) (accepted 2026-10-15; P02b-4 runtime and enforcement implemented; the [phase status](../roadmap/phase-02b-events-auth.md) owns hosted qualification). +Global identity creation and contextual foundation authority derive from Accepted +[ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md) and +[ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md). This standard defines **which operations must be audited**, **what an audit entry contains**, **how long entries are retained**, and how each module signs up for its @@ -35,7 +38,9 @@ document is the rule that prevents the audit story from drifting. resource, when, from where, with what outcome**" for every meaningful state change. - If omitting an audit entry would embarrass a compliance officer, it **MUST** be audited. -- Audit entries are append-only, immutable and tenant-scoped. `audit_log` is org-scoped, +- Audit entries are append-only and immutable. Ordinary entries are tenant-scoped; + the [global identity creation class](#global-identity-creation) is the separately + admitted sentinel population beside platform-scope rows. `audit_log` is org-scoped, and the row's organization is the one the ambient context announced: `AuditIntent` carries `TenantId` and `OrganizationId?`, both resolved by `AuditLogBehavior` at step 3 ([ADR-0044 Amendment 3 § 2](../decisions/0044-audit-write-path.md)) — which is before @@ -348,11 +353,12 @@ Rules: new table either way, and partitioning on day one would force every partition-key column into the primary key before the schema that shape has to serve exists. The policy shape is the same in both. -- **Table class and chain.** `audit_log` is **tenant-owned, org-scoped** and takes the - canonical policy template from +- **Table class and chain.** `audit_log` is **tenant-owned, org-scoped**. Its ordinary + tenant/org policy semantics come from [Database Standards § Tenant-Owned and Organization-Scoped Tables](05-database.md) - unmodified — one `AND`-ed policy, `ENABLE` **and** `FORCE`, explicit `WITH CHECK`, both - `AS RESTRICTIVE` write guards. `audit_config` is **tenant-owned, tenant-wide**: it has + with the accepted [global identity branch](05-database.md#global-central-audit-branch), + implemented in Step 3. The reusable template stays unchanged; the applied audit + policy includes only the qualified global extension. `audit_config` is **tenant-owned, tenant-wide**: it has no `organization_id`, so it takes the same shape with the organization half omitted and no restrictive guards — there is no organization to guard ([ADR-0044 Amendment 1](../decisions/0044-audit-write-path.md)). No document @@ -557,7 +563,7 @@ table above is the policy those deliverables implement, not a description of tod the [canonical job obligations](21-architecture-tests-catalogue.md#p02b-4-background-job-obligations) name their owners and proofs. Ordinary business mutations and privileged maintenance remain audited under their existing contracts. -- Accepted ADR-0047's sixth `WriteJobTerminalAsync` method accepts only the actual +- Accepted ADR-0047's sixth currently shipped `WriteJobTerminalAsync` method accepts only the actual fenced job-transition witness and matching caller connection/transaction. It validates stored tenant/organization/job/definition/attempt/acquisition values, MUST/SecurityEvent classification and the exact `platform.job.dead_letter` draft. @@ -593,14 +599,16 @@ table above is the policy those deliverables implement, not a description of tod the request payload: `ITenantContext.TenantId` under a resolved context, `IProvisionsTenant.ProvisioningTenantId` for provisioning under an unresolved one, and `TenantId.PlatformSentinel` — the reserved `00000000-0000-7000-8000-000000000002`, not - the nil UUID — for a platform-scope operation with no resolvable tenant. An unresolved, - non-provisioning context writes **no row**: there is no tenant whose admin could read it, + the nil UUID — for a platform-scope operation with no resolvable tenant. An ordinary + unresolved, non-provisioning context writes **no row**: there is no tenant whose admin could read it, and [ADR-0036](../decisions/0036-tenant-resolution-trusted-inputs.md) forbids inventing one ([ADR-0044 § 1, § 2](../decisions/0044-audit-write-path.md)). `AuditLogBehavior` decides it at step 3 and puts it on the `AuditIntent`, which is the only point at which all four cases are decidable; the store composes the row from the intent and resolves no tenant of its own ([ADR-0044 Amendment 3 § 2](../decisions/0044-audit-write-path.md)). + Accepted ADR-0072 adds only the exact global creation class below; an unresolved + marker, generic metadata or SystemActor does not enroll it. - **The sentinel has an enforcer, not only a constraint.** Packet 9 puts the guard where the value enters: `SetProvisioningTenantContextAsync` refuses `TenantId.PlatformSentinel` as it already refuses `Guid.Empty`, and `Tenant.Create` @@ -610,6 +618,36 @@ table above is the policy those deliverables implement, not a description of tod - The outbox dispatcher attaches the actor and the correlation id to every event it dispatches. +## Global identity creation + +**Implemented under ADR-0072 in P03-1 Step 3.** The +[Phase 03 Status block](../roadmap/phase-03-identity-admin.md) owns current +qualification and review state. +`identity.user.create` is MUST/SecurityEvent under the central baseline catalogue, +independent of tenant AuditConfig and ADR-0065's host-tenant assertion allowance. +Ordinary existing-binding reads declare no mutation intent. The exact +[Database contract](05-database.md#global-central-audit-branch) owns global +discrimination, policy/guard/evidence predicates and prepared owner sequencing. + +The common audit/transaction coordinators retain ownership. Extend `AuditIntent`, +captured attribution and shared composition with a closed typed global-creation +value; central composition derives its bounded metadata and creation reference. +No handler submits arbitrary metadata or an AuditEntryDraft. Before an actor +exists, the authenticated audit principal is NULL and the proposed target actor +is separate; seed adoption attributes its fixed SystemActor. Raw issuer/subject, +credentials and token values enter neither metadata nor snapshots. Retained +subject-key metadata remains linkable personal data under existing retention. + +`WriteGlobalIdentityPending` and `ReconcileGlobalIdentity` extend the earlier six +central write seams to **eight implemented seams**, without another SQL INSERT owner. +Success shares the first User's physical transaction; non-success reconciliation +uses captured evidence and preserves failure/unknown-COMMIT semantics. Ordinary +pending explicitly refuses sentinel/global intents and global enrollment. A +scoped read-only enrollment reader preserves the lazy application-source boundary. Platform, event and job seams keep their distinct scopes. +No global audit read endpoint or P03-1 HTTP creation route follows. Registered +Identity audit controls now exercise actual app-role, clean/dirty and physical +COMMIT-boundary paths. Later contextual writers and HTTP activation remain separate. + ## Architecture and Integration Tests Canonical names and each rule's kind live in diff --git a/docs/standards/19-permissions.md b/docs/standards/19-permissions.md index f52c64b54..4fdd89f72 100644 --- a/docs/standards/19-permissions.md +++ b/docs/standards/19-permissions.md @@ -3,11 +3,24 @@ **Status:** Adopted **Derives from:** [11-security.md](11-security.md) § Authorization, [ADR-0017 Tenant + Organization Hierarchy](../decisions/0017-tenant-organization-hierarchy.md), +[ADR-0064 Tenant API Authentication Boundary](../decisions/0064-tenant-api-authentication-boundary.md) +(realm roles and provider scope do not grant application authority), [01-architecture-standards.md](01-architecture-standards.md), [18-audit-coverage.md](18-audit-coverage.md). +Identity foundation definitions, manifests and role ownership derive from Accepted +[ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md) and +[ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md). LearnStack uses permission-based RBAC layered on top of tenant membership. This standard pins the **naming convention**, **closed action set**, **registration pattern**, **enforcement points**, and the **per-module matrix template** that every module must produce. +**Implementation boundary.** The finite Identity definitions, template grants +and confined seed commands are implemented in P03-1 Step 4. +Accepted ADR-0073 settles scoped definition identity, tenant-wide templates and +the finite initial seed manifests in the [Identity foundation contract](#identity-foundation-contract). +P03-2 owns live enforcement/delegation/adoption and +P03-9/G13 owns operator admission. Adoption of this standard grants no runtime +authority. The closed key/action/scope rules remain binding. + ## Naming Convention Permissions are dotted, lowercase, three-part keys: @@ -58,13 +71,15 @@ This rule prevents permission sprawl and keeps the matrix template stable. ## Scope: Platform / Tenant / Organization -Permissions carry a **scope** at registration time per -[ADR-0017](../decisions/0017-tenant-organization-hierarchy.md). The registries are -disjoint and validated at seed time. +Permissions are identified by **`(PermissionScope, PermissionKey)`** at +registration time under ADR-0017/0073. Tenant and Organization can register the +same key as distinct definitions. Platform definitions are never assignable to +tenant Roles. Unknown/inactive pairs authorize nothing; Step 4 implements the +nonempty foundation registry. | Scope | Examples | Granted to | |-------|----------|------------| -| **Platform** | `platform.tenant.write`, `platform.feature_flag.admin`, `platform.audit.read`, `platform.hub.operator` | Only platform admins / Hub operators; never assignable to a tenant role. | +| **Platform** | `platform.tenant.write`, `platform.feature_flag.admin`, `platform.audit.read` | 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) | Org-scoped roles; permission check requires `Membership.OrganizationId` matches the resource's `OrganizationId` (or the role is tenant-scoped). | @@ -74,38 +89,33 @@ tenant-wide variant of the same role). Platform permissions bypass tenant scope require platform-admin authentication and write a `platform-admin` audit entry (see [18-audit-coverage.md](18-audit-coverage.md)). -Architecture test -`Permission_Scope_Matches_Resource_Scope` ensures permissions registered as +Registered architecture obligation +`Permission_Scope_Matches_Resource_Scope` requires permissions registered as `Organization`-scope are only checked against `[OrganizationScoped]` resources, and that `Tenant`-scope permissions never gain `OrganizationId` filtering at runtime without an explicit `organization-scope` role binding. ## Module-Driven Registration -Permissions are declared in code, not configured in a database. Each module exposes its permissions at startup; the platform registry composes them and seeds the database. - -```csharp -public sealed class EnrollmentModule : IModule -{ - public void RegisterPermissions(IPermissionRegistry registry) - { - registry.Tenant("enrollment.enrollment.read", "View enrollments"); - registry.Tenant("enrollment.enrollment.write", "Create or update enrollments"); - registry.Tenant("enrollment.enrollment.delete", "Cancel enrollments"); - registry.Tenant("enrollment.course_access.read", "View course access"); - registry.Tenant("enrollment.course_access.write", "Grant or revoke course access"); - registry.Tenant("enrollment.cohort.read", "View cohorts"); - registry.Tenant("enrollment.cohort.write", "Create or update cohorts"); - registry.Tenant("enrollment.cohort.delete", "Delete cohorts"); - } -} -``` +Permissions are declared in code. Module definition sources compose the available +scoped capabilities; registration grants nothing to existing Roles. The accepted +[manifest composition contract](#immutable-admin-kernel-and-one-manifest-source) +supplies finite initial grants and the admin kernel from one versioned source. +Its finite manifest and scoped definition types are implemented in P03-1 +Step 4; no `IModule` interface is introduced. Rules: - Renaming a permission key is a breaking change. Add the new key, dual-write during migration, drop the old key in a separate release. Renaming under the radar breaks every role assignment. - Removing a permission requires an ADR + grace period (one minor release with a deprecation log). -- Adding a permission is non-breaking; it ships disabled-by-default in seeded roles until a tenant admin enables it. +- Adding a permission grants nothing to existing Roles. New-tenant initialization + selects an explicit finite initial manifest version; later grant adoption is a + separately admitted audited act under P03-2. + +Seed/registry reruns preserve adopted grants and never perform upgrades. A +legitimate later manifest adoption takes precedence over fixed-v1 seed state; +that seed refuses a differing adopted version instead of repairing it. Changes +to the closed role/delegation contract require their owning decision. ## Enforcement Points @@ -136,7 +146,11 @@ Combining: an `instructor` role has `education.course.write`, but a policy class ### Frontend -Permission-aware UI hides actions the user cannot perform — but the API is authoritative. The frontend never decides authorization on its own. UI checks call a generated permission catalogue (`usePermissions().can("education.course.write")`) that fetches the actor's permissions once per session and caches them. +Permission-aware UI hides actions the user cannot perform; the API is +authoritative. The target generated catalogue facade +(`usePermissions().can("education.course.write")`) is not shipped. G5 specifies +API revocation and UI invalidation/freshness; fetching grants once per session +alone proves neither. A stale enabled control still cannot authorize a mutation. ## Permission Matrix Template @@ -151,26 +165,41 @@ Every module ships this matrix as part of its module spec under Legend: ✓ = permission exists; – = does not apply (the closed action set means some cells are intentionally empty). -The "Default role grants" column declares which built-in roles receive which permissions on tenant provisioning. +The "Default role grants" column documents the owning operation's approved finite +initial manifest. Illustrative example bundles do not register or grant keys; +P03-1's exact manifest below takes precedence for the foundation population. ## Built-in Roles -| Role | Scope | Auto-provisioned | Notes | -|------|-------|------------------|-------| -| `Platform Admin` | Platform | At platform install | Superset of platform permissions; never a tenant role. | -| `Tenant Admin` | Tenant | On tenant creation | Superset of tenant permissions for that tenant. Receives newly registered tenant permissions on next provisioning cycle. | -| `Instructor` | Tenant | Module-defined seeds | Read/write on courses, lessons, sessions, attendances where they are the owner/host. | -| `Learner` | Tenant | Module-defined seeds | Read on published catalog; write on own attempts, bookings, profile. | -| `Guardian` | Tenant | Off by default | Read on linked learner's progress and recordings (per consent). | -| `Editor` | Tenant | Module-defined seeds | Read/write on content, pages, media; no enrollment / billing access. | -| `Portal Public` | Tenant | Anonymous | Read on published public surfaces only. | -| `Org Admin` | Organization | Off by default | Tenant-admin permissions limited to the actor's organization. Typical for branch managers / campus heads. | -| `Org Instructor` | Organization | Off by default | Instructor permissions limited to the actor's organization. | -| `Hub Operator` | Platform | Off by default — provisioned by Hub | Has the `platform.hub.operator` permission and a Hub-realm token. Each Hub operator action against a tenant resource writes an audit entry with `actor.hubOperator = true`. | +| Role | Capability scope | Template / assignment contract | +|---|---|---| +| `Platform Admin` | Platform | No tenant template; production admission remains P03-9/G13. | +| `Tenant Admin` | Tenant | Tenant-wide template; finite v1 initial grants and immutable kernel below. | +| `Instructor` | Tenant | Tenant-wide template; v1 grants empty. | +| `Learner` | Tenant and Organization | Two tenant-wide templates with separate scoped grants and compatible Membership assignments. | +| `Guardian` | Tenant | Tenant-wide template; v1 grants empty and no initial assignment. | +| `Editor` | Tenant | Tenant-wide template; v1 grants empty. | +| `Portal Public` | Tenant | Virtual anonymous capability; no stored Membership or template. | +| `Org Admin` | Organization | Tenant-wide template; compatible branch Membership supplies organization authority, with no initial assignment. | +| `Org Instructor` | Organization | Tenant-wide template; v1 grants empty and no initial assignment. | +| `Hub Operator` | Platform | No tenant template; authenticated chain/exact permissions remain P03-9/G13. A Hub token grants no tenant-route authority. | + +P03-1 stores all eight tenant templates in Step 4. Template existence supplies no +authority: only eligible Membership assignments and active registered scoped +grants contribute. Off-by-default means no initial assignment, not an omitted +template. Capability scope never selects storage/authoring scope; Role has no +OrganizationId. The exact [v1 manifest](#version-1-built-in-grant-manifest) replaces +the earlier broad built-in examples and never expands automatically. Tenant-driven customization **does not add roles**. Tenants extend behavior through customization data; they configure role grants by composing the closed set above. +The historical proposed operator key used `operator` as its action, outside the +closed set. It is not a registration exception; G5/G13 choose a conforming key. +`Portal Public` is the anonymous capability model, not a stored membership: its +eventual registry integration preserves the `HostOnly`/PublicSurface ceiling under +ADR-0036 and grants no protected authority. + ## Testing Requirements Every endpoint and every job has, at minimum: @@ -192,7 +221,9 @@ Permission grants and revocations are MUST-audit security-events ([18-audit-cove - The role mutated. - The permission added or removed. -- Whether the change affects active sessions (forces JWT refresh). +- The decided effect on active requests/sessions and the applicable revocation + boundary under G5. Forcing provider JWT refresh alone does not enforce a + LearnStack role/permission change; realm roles remain nonauthoritative. ## Forbidden @@ -209,3 +240,136 @@ Permission grants and revocations are MUST-audit security-events ([18-audit-cove - [18-audit-coverage.md](18-audit-coverage.md) — audit entries for permission changes. - [13-identity-and-auth.md](../architecture/13-identity-and-auth.md) — Keycloak vs LearnStack identity split (Keycloak does authentication, LearnStack does authorization). - [01-architecture-standards.md](01-architecture-standards.md) — module layout for `IPermissionRegistry`. + + + +## Identity foundation contract + +**Status: Foundation registry, models and seed commands implemented.** Derived from +[ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md) and +[ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md). +API composition denies the seed capability. No route, operator admission or live +HTTP permission is activated by the foundation. + + + +### Adopted scope and grant boundary + +The active Scope, Module-Driven Registration and Built-in Roles sections above +adopt this implemented foundation contract. Live enforcement remains P03-2. + +P03-1's five pairs and version-1 grants below are the complete foundation set. +P03-2 owns the separately admitted finite live-authorization/grant-adoption +contract; P03-3 owns protected operations and UI/scope transitions. Neither a +later operation nor an older built-in-role example silently expands v1 grants. + +### Capability scope and template ownership + +`PermissionDefinition(PermissionScope, PermissionKey)` identifies a definition. +The same key at Tenant/Organization scope is two definitions; unknown/inactive +entries never authorize. Existing key grammar and closed action set remain. + +Role templates are tenant-owned, **tenant-wide** roots. Capability scope does +not dictate storage scope or authoring: Role has TenantId, built-in key and +PermissionScope, with no OrganizationId. Only an eligible tenant-wide Tenant +Admin with Tenant `identity.role.admin` edits templates, including Organization +variants. No independent branch copy exists; needing that product capability +reopens ADR-0073. Organization creation consequently writes no Identity rows. + +Assignments belong to Membership. Tenant templates require NULL-org Membership; +Organization templates require non-NULL-org Membership and apply to that exact +organization alone. Grants mirror Role capability scope. Storage as a tenant-wide +template never promotes an Organization grant to Tenant capability or widens writes. + +A branch session may consume eligible Tenant grants for operations on that +branch. Tenant-wide Membership/Profile/template writes require P03-3's explicit +validated orgless reissue, preserving the canonical write guards. The +`app.scope = 'tenant'` hatch remains read-only; a permission or Tenant assignment +cannot clear an authenticated branch scope implicitly. + +### Exact foundation registry and operation owners + +Version 1 contains **exactly five pairs**: + +| Scope | Key | Production foundation consumer | +|---|---|---| +| Tenant | `identity.membership.admin` | `CreateFirstSeedAdminMembership`; Tenant variant of `CreateSeedMembership` | +| Organization | `identity.membership.admin` | Organization variant of `CreateSeedMembership` | +| Tenant | `identity.role.admin` | `InitializeSeedRole`, including Organization-capability templates | +| Tenant | `identity.membership_profile.write` | Tenant variant of `SetSeedMembershipProfile` | +| Organization | `identity.membership_profile.write` | Organization variant of `SetSeedMembershipProfile` | + +These are actual compiled production commands, distinct from test fixtures. +Finite scope metadata derives from immutable target/validated declarations. +The seed profile declaration binds its expected User and single Role assignment; +the handler verifies both before and after its tenant-lock wait. +Closed seed authority is checked independently before dispatch, default-denied +in API composition. P03-2 qualifies live permission admission before protected +activation; registration/attributes/seed success grant no HTTP route. + +### Version-1 built-in grant manifest + +Keep seven stored built-in keys; Learner has two capability variants, yielding +eight templates per tenant. Platform Admin/Hub Operator have no tenant rows; +Portal Public remains virtual anonymous capability. Empty means empty, without +future automatic expansion. + +| Built-in key | Capability scope | Exact version-1 grant set | +|---|---|---| +| Tenant Admin | Tenant | Tenant `identity.membership.admin`; Tenant `identity.role.admin`; Tenant `identity.membership_profile.write` | +| Instructor | Tenant | Empty | +| Learner | Tenant | Tenant `identity.membership_profile.write` | +| Guardian | Tenant | Empty | +| Editor | Tenant | Empty | +| Org Admin | Organization | Organization `identity.membership.admin`; Organization `identity.membership_profile.write` | +| Org Instructor | Organization | Empty | +| Learner | Organization | Organization `identity.membership_profile.write` | + +Organization Learner explicitly extends the earlier Tenant-only example, without +Tenant/other-branch grants. Instructor/Org Instructor/Guardian/Editor remain empty +until real owning operations register keys and separately admitted grants adopt +them. Later broader P03-2 manifests are finite; reruns cannot fill existing Roles. + +### Immutable admin kernel and one manifest source + +The minimum is **exactly two pairs**: Tenant `identity.membership.admin` and +Tenant `identity.role.admin`. Profile writing belongs to the initial bundle, +outside that minimum, and P03-2 may remove it through an explicitly admitted +audited grant change. Role-admin is reserved to Tenant Admin template/eligible +actors; an arbitrary grant or renamed Role cannot delegate template authorship. + +One versioned compiled `IdentityFoundationManifest` supplies the adopted +`PermissionDefinitionSource`, `BuiltInRoleGrantManifest` and +`TenantAdminKernelManifest` composition. These are not current interfaces or an +`IModule` API. It generates the immutable SQL guard artifact; an equivalence +control compares complete scoped values/version/fingerprint with the compiled +manifest. No app-editable kernel table, wildcard/prefix or independently +maintained SQL list defines the minimum. Changes need the decision and guard +migration before dependent grants. + +New tenants receive the explicitly selected current finite initial version. +Existing Roles retain adopted grants; registry/seed reruns add no new-key grants. +P03-2 owns separately admitted audited grant additions/removals outside the kernel. +Keep historical manifest versions/fingerprints for completed-act verification. +Matching completed seed acts do no writes; revoked/suspended/operator-edited +authority conflicts without repair/reset. A legitimate later manifest adoption +that differs from the fixed v1 seed also makes that seed refuse, preserving the +adopted state. Seed is not an upgrade reconciler. Realm roles/SystemActor cannot +supply manifests or authority. +[Identity's seed sequence](../modules/identity/README.md#first-admin-and-seed-sequence) +owns ordering and interrupted-run disposition. + +### Enforcement and proof boundary + +P03-1 Step 4 supplies nonempty actual-command registry, templates, reference/ +scope guards and kernel artifact. P03-2 owns default deny/delegation, per-act +revocation/freshness, grant adoption and denied controls. P03-3 owns HTTP/new-user +BFF activation, protected UI and explicit scope transitions; +P03-9/G13 owns production first-admin/recovery before its production provisioner. +The development seed capability is not that future authority. + +The [catalogue](21-architecture-tests-catalogue.md) records the implemented +semantic property census and foundation/manifests/scope controls with actual +clean/dirty subjects. Empty censuses, stored Roles and diagrams alone are not +implementation proof. Current qualification state lives in the +[phase Status block](../roadmap/phase-03-identity-admin.md). diff --git a/docs/standards/20-infrastructure-stack.md b/docs/standards/20-infrastructure-stack.md index 126ebaea3..b40553eda 100644 --- a/docs/standards/20-infrastructure-stack.md +++ b/docs/standards/20-infrastructure-stack.md @@ -30,6 +30,8 @@ Accepted server lifecycle and its bounded availability qualification derive from [ADR-0059](../decisions/0059-owned-hangfire-server-generations.md). The exceptional startup/unsafe-unwind process boundary derives from [ADR-0060](../decisions/0060-fatal-hangfire-startup-and-unsafe-unwind.md). +The ordinary CI window derives from +[ADR-0075](../decisions/0075-ordinary-ci-job-window.md). Three audit decisions are referenced here but **not owned** here, and the split matters because they are easy to conflate: @@ -789,8 +791,11 @@ job-scoped `actions: read`; executors retain `contents: read`. Base/Architecture add only an owned transient systemd/cgroup seam on exclusive hosted Ubuntu 24.04 VMs, without Docker or collector authority. Native's ADR-0062 authority remains exclusive. No application runtime, production infrastructure or local/shared -host authority follows. Each execution remains bounded to twenty minutes and -each aggregate to five; actual final-source fit is recorded in the phase. +host authority follows. The ordinary-only whole-job window is twenty-five +minutes under [ADR-0075](../decisions/0075-ordinary-ci-job-window.md); +base/Architecture/native retain twenty minutes and each aggregate five. The +testing standard owns the expected-producer bounds and unchanged reserves; +actual final-source fit is recorded in the phase. - Step 4's API composition registers one `BackgroundJobHostedService` over [`BackgroundJobRuntime`](../glossary.md#background-jobs), with singleton hosted diff --git a/docs/standards/21-architecture-tests-catalogue.md b/docs/standards/21-architecture-tests-catalogue.md index 8f5841061..6c6808fb7 100644 --- a/docs/standards/21-architecture-tests-catalogue.md +++ b/docs/standards/21-architecture-tests-catalogue.md @@ -39,6 +39,9 @@ owns review, packet and exact PR-head CI/job-budget status), [ADR-0063 Complete Bounded CI Test Shards](../decisions/0063-complete-bounded-ci-test-shards.md) (Accepted 2026-10-18; general CI obligation implemented; the phase record owns final-source hosted qualification), +[ADR-0075 Ordinary CI Job Window](../decisions/0075-ordinary-ci-job-window.md) +(Accepted 2026-10-27; the ordinary-budget extension below is implemented with +offline controls and source-bound hosted A/B; the phase owns evidence review), [ADR-0064 Tenant API Authentication Boundary](../decisions/0064-tenant-api-authentication-boundary.md) (Accepted 2026-10-19; P02b-5 obligations implemented and merged through PR #33; the [merge closeout](../roadmap/phase-02b-delivery-log.md#p02b-5-merge-and-closeout-2026-10-20) @@ -55,6 +58,13 @@ owns source-bound validation, reviews and hosted qualification), [ADR-0067 Development Tenant Access-Token Issuance](../decisions/0067-development-tenant-access-token-issuance.md) (Accepted 2026-10-21; formalizes the existing issuance obligation's authority without adding a rule or changing its implementation status). +Identity foundation registration additionally derives from Accepted +[ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md), +[ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md) and +[ADR-0074](../decisions/0074-membership-admission-under-ordered-locks.md). +The implemented Identity obligations and extensions name their actual proof +owners below; the [phase Status block](../roadmap/phase-03-identity-admin.md) owns +current qualification and review state. The catalogue grows as subsequent ADRs and phases land their tests; per-test ownership stays with the originating ADR / standard. @@ -147,7 +157,7 @@ not implemented is the failure mode this column exists to prevent. ### Implemented today -**282 test methods run in +**303 test methods run in [`backend/tests/LearnStack.Tests.Architecture`](../../backend/tests/LearnStack.Tests.Architecture),** shipped by [Phase 01](../roadmap/phase-01-repository-tooling.md), [Phase 02a Packets 2–3](../roadmap/phase-02a-kernel-tenancy.md), Packet 4, Packet 6, Packet 7, @@ -188,8 +198,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. -**237 rules in this catalogue are Implemented, and 134 of them are in that assembly.** -The other 103 are no less binding, and most could not live there. The table says where +**244 rules in this catalogue are Implemented, and 140 of them are in that assembly.** +The other 104 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. @@ -1416,7 +1426,7 @@ otherwise). **Kind:** structural. - **Status:** **Implemented** (Packet 6 step 4, `LearnStack.Tests.Architecture`, `TenancyConventionTests`), and whole: it reads every - module `Domain` assembly, including the three — Content, Identity, Media — + module `Domain` assembly, including the two — Content and Media — that declare no domain type yet, only an `AssemblyMarker`, so the first `Organization` or `OrganizationBranding` to land in one of them fails it. `OrganizationBranding` itself arrives with [Phase 06](../roadmap/phase-06-renderer-admin-studio.md)'s branding; until then "exactly @@ -1564,9 +1574,11 @@ catalogue as the carrier of their status — so all three are Packet 10's. #### `Migrate_Target_Applies_The_Tenancy_Chain_First` -- **Asserts:** the `migrate` recipe visits Tenancy before Audit and Education. - Education's four organization-immutability triggers call Tenancy's shared function - (P02d-1). The two dependent-first companions exercise and repair the same detector. +- **Asserts:** the `migrate` recipe visits Tenancy before Audit and Education, + and Audit before Identity. Education's four organization-immutability triggers + call Tenancy's shared function (P02d-1); ADR-0072's Identity chain invokes the + [central creation-witness installer](05-database.md#lock-snapshot-and-adoption-conditions) + after Audit. The three dependent-first companions exercise and repair the same detector. From Phase 02a Packet 9 the chains are no longer independent — `audit_config` carries the schema's only foreign key crossing two chains, to `tenants` — and the recipe's project list is a glob that expands alphabetically, with `Modules/Audit` @@ -1587,11 +1599,12 @@ catalogue as the carrier of their status — so all three are Packet 10's. named rule the only thing that catches it. - **Source:** [05-database.md § Migrations](05-database.md); the `migrate` target. - **Type:** xUnit + Makefile and directory inspection. **Kind:** structural. -- **Status:** **Implemented** (Packet 9 step 3; expanded in P02d-1 Step 2, - `LearnStack.Tests.Architecture`, `PersistenceConventionTests`). - Mutation-checked: deleting the Tenancy prefix fails this case; the Audit-first and - Education-first companions each exercise and repair the same order detector. -- **Phase:** 02a (Packet 9); expanded in 02d (P02d-1). +- **Status:** **Implemented** (Packet 9 step 3; expanded in P02d-1 Step 2 and + P03-1 Step 3, `LearnStack.Tests.Architecture`, `PersistenceConventionTests`). + Mutation-checked: deleting the Tenancy prefix fails this case; the Audit-first, + Education-first and Identity-before-Audit companions each exercise and repair + the same order detector. +- **Phase:** 02a (Packet 9); expanded in 02d (P02d-1) and 03 (P03-1). #### `Migrate_Target_Refuses_An_Aliased_Runtime_Credential` @@ -1802,21 +1815,29 @@ catalogue as the carrier of their status — so all three are Packet 10's. - **Asserts:** two halves. The composition root's persistence registration is run, and every `DbContext` service in it is one `AddModuleDbContext` registered — scoped, from an implementation factory, never a type registration EF could give - its own connection. And under `backend/src`, exactly **eight** files may reach for a - connection at all: the five design-time factories — one per migration chain, where a - connection string is the point; the shared helper, which passes a *connection*; and the - API's separately guarded platform-role builder; and the shared application-role - builder used by both the API and the one-shot seeder. A ninth is a new decision. + its own connection. Under `backend/src`, the configuration/construction scan + admits exactly **eleven** files: six design-time factories, one per migration + chain; `ModuleDbContextRegistration`, which passes a *connection*; + `PersistenceCompositionExtensions`, with the guarded platform-role builder; + `ApplicationDataSource`, shared by the API and one-shot Seeder; + ADR-0046's confined `OutboxDispatcherDataSource`; and ADR-0072's deployment-only + `LearnStack.Tools.IdentityAuthorityInstaller/Program.cs`. Another construction + site requires its owning decision and an explicit allow-list change. A context on its own connection never saw the announcement, so every read through it returns zero rows under the corrected policy — silently. The set is keyed on `directory/filename`, not the bare filename: two files with - the same name cannot silently share a sanctioned construction site. -- **Source:** ADR-0040; [05-database.md § Forbidden](05-database.md). + the same name cannot silently share a sanctioned construction site. The lexical + scan covers `UseNpgsql`, `AddDbContext`, data-source builders/factories and raw + connection constructors. Connection acquisition from an already configured + source remains governed by its named owner contract. +- **Source:** ADR-0040; ADR-0046's confined dispatcher; ADR-0072's deployment + authority installer; [05-database.md § Forbidden](05-database.md). - **Type:** xUnit + DI registration inspection and a source scan. **Kind:** structural. - **Status:** **Implemented** (Packet 6 step 6; the allow-list widened to five and keyed by directory in Packet 7 step 10, to six in Packet 8 step 3 and to seven in - Packet 9 step 3 and eight in P02d-1 step 2, `LearnStack.Tests.Architecture`, `PersistenceConventionTests`). + Packet 9 step 3, eight in P02d-1 step 2 and eleven with the ADR-0046/0072 + construction sites, `LearnStack.Tests.Architecture`, `PersistenceConventionTests`). - **Phase:** 02a (Packet 6). #### `The_registration_marker_does_not_vouch_across_containers` @@ -1970,7 +1991,7 @@ diagnostic above row security, not the boundary, as its own note says. real PostgreSQL role/grant/startup refusal proofs. Exact unique literal source-reader signatures, visibility and staticness reject named-method overloads; those focused controls and both fresh fix reviews passed at `606362b`. - [OutboxDispatchConventionTests.Credential_census_rejects_compiled_connection_string_indexers_and_composed_keys](../../backend/tests/LearnStack.Tests.Architecture/OutboxDispatchBoundaryTests.cs) + [OutboxDispatchConventionTests.CredentialBindingMutationTests.Credential_census_rejects_compiled_connection_string_indexers_and_composed_keys](../../backend/tests/LearnStack.Tests.Architecture/OutboxDispatchBoundaryTests.cs) plants actual compiled concatenation, interpolation, formatting and configuration indexer calls, with clean configuration/dictionary/diagnostic controls. [OutboxDispatcherRoleGuardTests.App_membership_in_the_dispatcher_is_refused_directly_and_transitively_then_restoration_connects](../../backend/tests/LearnStack.Tests.Integration/Database/OutboxDispatcherRoleGuardTests.cs) @@ -2140,9 +2161,12 @@ diagnostic above row security, not the boundary, as its own note says. schema-qualified parent lookup, both tenant and parent-id predicates, and `FOR KEY SHARE`. Its nullable organization comparison and uniform `23514` refusal cover missing, hidden and mismatched parents. Initial subjects are Lesson → Course, - CourseTranslation → Course and LessonTranslation → Lesson; subject discovery and - declaration coverage must make an omitted relation fail. + CourseTranslation → Course and LessonTranslation → Lesson. Identity adds + MembershipProfile → Membership and MembershipRoleAssignment → Membership; + its combined invoker trigger retains the same parent-scope contract. + Subject discovery and declaration coverage must make an omitted relation fail. - **Source:** [ADR-0003 Amendment 6](../decisions/0003-tenant-isolation-defense-in-depth.md#amendment-6--insert-scope-and-parent-mirrors-2026-09-14); + [ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md); [05-database.md § Parent organization mirrors](05-database.md#parent-organization-mirrors); [Education data model](../modules/education/README.md#data-model-and-invariants). - **Type:** xUnit + EF model and applied PostgreSQL schema inspection. **Kind:** structural. @@ -2152,7 +2176,7 @@ diagnostic above row security, not the boundary, as its own note says. Separate `learnstack_app` proofs exercise insertion, reparenting, the lock before the FK runs and temporary-table shadowing. A well-shaped trigger alone is not an isolation proof. -- **Phase:** 02d (P02d-1). +- **Phase:** 02d (P02d-1); P03-1 contextual foundation. #### `Pattern_A_Content_Uses_Translation_Satellites` @@ -2526,10 +2550,156 @@ because the filters hold, and removing both turns all five red. `TenantCustomFieldDef`, never as a column on the global aggregate. The reviewer's version of the same question is "which tenant authored this value?". - **Source:** [Phase 03 § Attribute ownership](../roadmap/phase-03-identity-admin.md); - [ADR-0017](../decisions/0017-tenant-organization-hierarchy.md). + [ADR-0017](../decisions/0017-tenant-organization-hierarchy.md); + [ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md). - **Type:** xUnit + EF model inspection. **Kind:** structural. -- **Status:** **Registered.** -- **Phase:** 03. +- **Test owner:** `GlobalIdentityModelTests`. +- **Status:** **Implemented** (`GlobalIdentityModelTests`) — actual global User model, exact scalar population and independent self filter. +- **Phase:** P03-1 Step 3; contextual ownership extends in Step 4. + +### Accepted Identity foundation obligations + +These obligations derive from ADR-0072/0073. Each Status states actual delivery; +Registered owners remain planned classes, not passing controls. Promotion to +Implemented requires nonempty production subjects and dirty/clean controls. + +#### `Mapped_Properties_Have_Explicit_Personal_Data_Classification` + +- **Asserts:** the coordinator compares every real mapped EF property with its + module's explicit personal-data declaration, including inherited keys, raw + subjects and stable linkage. Missing/conflicting declarations and a planted + neutral-name omission fail the same complete census. Diagnostics reveal no + values; snapshot/redaction and sink canaries remain independent controls. +- **Source:** [ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md); + [Data Protection](../architecture/23-data-protection.md). +- **Type:** complete EF model/declaration comparison and planted omissions. + **Kind:** structural. +- **Test owner:** `DataProtectionConventionTests`. +- **Status:** **Implemented** (`DataProtectionConventionTests`) — P03-1 Step 2; + current nonempty production models, + the deliberately empty migration-only Platform context, real neutral-property + negative/positive controls and annotation/schema neutrality. Global and + contextual Identity models participate in the complete census. +- **Phase:** P03-1 Step 2, before the first Identity personal-data writer. + +#### `Global_Identity_Storage_Is_Subject_Confined` + +- **Asserts:** actual app-role reads expose only the announced verified subject; + missing/reset/malformed/foreign authority refuses. EF filters, applied + policies/grants/functions, owner DELETE/TRUNCATE refusal and pooled cleanup + match the sole [Database contract](05-database.md#identity-storage-contract), + with positive and planted-widening controls. The current applied schema has + 55 tables, six chains and five Identity definer functions. +- **Source:** [ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md); + [Database Standards](05-database.md#identity-storage-contract). +- **Type:** PostgreSQL catalogue, app-role isolation and owner controls. + **Kind:** behavioural, with structural companions. +- **Test owner:** `GlobalIdentitySchemaTests`. +- **Status:** **Implemented** (`GlobalIdentitySchemaTests`, integration assembly) — actual self reads/writes, compiled/applied body/ACL/caller census, committed widening/removal controls and owner mutation refusal. +- **Phase:** P03-1 Step 3. + +#### `Global_Identity_Creation_Uses_The_Common_Audit_Owner` + +- **Asserts:** exact prepared global authority uses the common coordinators, + typed creation reference and sole central SQL writer. Success/User reciprocity, + failure/unknown-COMMIT reconciliation, exact duplicate evidence and precommit + refusal preserve distinct outcomes. Missing/foreign/stale/reused owners, + ordinary/global crossover, metadata substitution and copied audit SQL fail. + The exact migration installer adds no runtime module/entity dependency or writer. +- **Source:** [ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md); + [Database Standards](05-database.md#global-central-audit-branch); + [Audit Coverage](18-audit-coverage.md#global-identity-creation). +- **Type:** production owner/installer census and actual app-role creation, + reconciliation and fault controls. **Kind:** behavioural and structural. +- **Test owners:** `IdentityAuditConventionTests`, `GlobalIdentityBootstrapTests`. +- **Status:** **Implemented** (`IdentityAuditConventionTests`; `GlobalIdentityBootstrapTests`, integration assembly) — closed actual owner/call sites, real PostgreSQL/provider/COMMIT fault twins and exact evidence controls; all eight central seams ship. +- **Phase:** P03-1 Step 3; no HTTP creation route is admitted. + +#### `Identity_Membership_Invariants_Use_Fresh_Ordered_Locks` + +- **Asserts:** actual Membership/child and protected Role mutations preserve the + total eligible-admin invariant under canonical ordered locks. Held-lock races + observe a real competing commit through fresh post-wait reads; wrong isolation, + forbidden upgrades, incomplete first-admin state and closure/final-admin races + refuse. Scope/reference/lifecycle controls cover tenant and branch variants. + Creation, Suspended-to-Active and every assignment addition require the actual + target User fence and a fresh actual-trigger eligibility check even when the + complete plan is preheld. Missing/wrong/shared-only/foreign-backend fences + refuse as fixed internal plan faults, distinct from uniform unknown/nonadmitting + target refusals. Exact current-backend heldness is observed without an + acquisition probe; `pg_locks` does not prove transaction ownership or history. + Closed caller/source/receipt controls reject session-lock APIs and actual + transaction-end tests prove lifetime; a session-only fixture exposes the + observation limit. Profile edits and assignment removals take no User fence + solely for admission. Fixed C#/SQL User/Tenant key vectors agree. Disposable + fixture-only closure competitors temporarily accommodate only the User update + guard and owner CHECK policy, restore both in `finally`, and prove the policy/guard/ + body/ACL census afterward, with independent dirty and clean controls; they + introduce no production closure writer. +- **Source:** [ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md); + [ADR-0074](../decisions/0074-membership-admission-under-ordered-locks.md); + [Database lock contract](05-database.md#lock-snapshot-and-adoption-conditions). +- **Type:** real app-role PostgreSQL mutation/concurrency controls and closed + transaction-only acquisition/caller census. **Kind:** structural and behavioural. +- **Test owners:** `IdentityMembershipTests`, `IdentityMutationLockTests`, `IdentityFoundationConventionTests`. +- **Status:** **Implemented** (`IdentityFoundationConventionTests`; `IdentityMembershipTests`, integration assembly) — real app-role races, immediate/deferred guards, + transaction-only caller/receipt controls, fixture restoration and local + command-path measurement. Current qualification/review state lives in the + [phase Status block](../roadmap/phase-03-identity-admin.md). +- **Phase:** P03-1 Step 4. + +#### `Identity_Seed_Uses_Finite_Adopted_Manifests` + +- **Asserts:** one versioned compiled source and generated SQL kernel agree on + complete scope/key/version/fingerprint. Finite templates/grants, ordered seed + acts and interrupted/no-write/conflict reruns preserve actors/credentials and + later adopted state. Registry additions grant nothing to existing Roles; seed + authority is default-denied in API composition. +- **Source:** [ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md); + [Permissions foundation](19-permissions.md#identity-foundation-contract); + [Identity seed sequence](../modules/identity/README.md#first-admin-and-seed-sequence). +- **Type:** actual manifest/command census, generated-artifact equality and seed/rerun + controls. **Kind:** structural and behavioural. +- **Test owners:** `IdentityFoundationConventionTests`, `IdentitySeederTests`. +- **Status:** **Implemented** (`IdentityFoundationConventionTests`; `IdentitySeederTests`, integration assembly) — actual owned private-witness handoff, finite + production commands, no-write/interrupted/conflict reruns and central MUST + rollback/contained capture controls. +- **Phase:** P03-1 Step 4. + +#### `Permission_Definitions_DeclareScope` + +- **Asserts:** each definition declares Platform, Tenant or Organization scope; + identity is `(PermissionScope, PermissionKey)`. The actual nonempty foundation + registry equals the accepted finite five-pair manifest; missing/duplicate/wrong- + scope definitions and inconsistent consumers fail. +- **Source:** [ADR-0017](../decisions/0017-tenant-organization-hierarchy.md); + [ADR-0073](../decisions/0073-scoped-membership-and-identity-data-foundation.md); + [Permissions Standards](19-permissions.md#identity-foundation-contract). +- **Type:** compiled definitions/consumers with planted controls. **Kind:** structural. +- **Test owner:** `IdentityFoundationConventionTests`. +- **Status:** **Implemented** (`IdentityFoundationConventionTests`) — the actual five-pair registry, command metadata, + generated artifacts and planted definition controls are exercised. +- **Phase:** P03-1 Step 4. + + + +### Identity extensions to Implemented rules + +The following rules retain **Implemented** for their shipped populations. +P03-1 extends their named owners without creating duplicate catalogue rules or +promoting later live-admission controls. The phase Status block and delivery log +own current qualification and review state. + +| Existing canonical rule(s) | Accepted extension and implemented owner scope | +|---|---| +| [`ModuleInfrastructure_References_Only_Its_Own_Layers_And_Core_Infrastructure`](#moduleinfrastructure_references_only_its_own_layers_and_core_infrastructure), [`CoreInfrastructure_DoesNotDependOn_AnyModule`](#coreinfrastructure_doesnotdependon_anymodule), [`Modules_Do_Not_Write_AuditLog_Directly`](#modules_do_not_write_auditlog_directly) | Step 3: exact migration-only installer/body/caller exception; no copied audit SQL, core module/entity reference or new SQL writer. | +| [`Migrate_Target_Covers_Every_Migration_Chain`](#migrate_target_covers_every_migration_chain), [`Every_Module_With_A_Schema_Is_Swept`](#every_module_with_a_schema_is_swept), [`Every_TenantOwned_Entity_HasFilterAndRlsPolicy`](#every_tenantowned_entity_hasfilterandrlspolicy) | Steps 3/4: sixth Identity chain/Audit prerequisite and complete seven-class population, retaining tenant predicates. | +| [`Every_TenantOwned_Foreign_Key_Includes_TenantId`](#every_tenantowned_foreign_key_includes_tenantid), [`Unique_Indexes_On_Soft_Deletable_Tables_Exclude_Deleted_Rows`](#unique_indexes_on_soft_deletable_tables_exclude_deleted_rows) | Steps 3/4: exact Membership-to-global-User FK and permanent binding index. Other tenant references retain composite/self-keyed shape. | +| [`Every_Organization_Mirroring_Child_Has_A_Parent_Scope_Guard`](#every_organization_mirroring_child_has_a_parent_scope_guard) | Contextual Identity: both contained Membership children join the independent EF/applied relation census and real guard/FK mutation controls; the invoker guard preserves canonical parent-scope refusal and the same fixed adapter descriptor. | +| [`AllowsUnresolvedTenantContext_Only_On_Provisioning_Commands`](#allowsunresolvedtenantcontext_only_on_provisioning_commands), [`Tenant_Context_Guard_Fires_Only_On_An_Unmarked_Transaction`](#tenant_context_guard_fires_only_on_an_unmarked_transaction) | Step 3: closed global authority mode and crossover refusal; provisioning marker/current four context writers do not grow. P03-2 separately implements the accepted ninth candidate setter. | +| [`AuditEntry_Is_AppendOnly`](#auditentry_is_appendonly), [`MustClass_Audit_Writes_Share_The_Business_Transaction`](#mustclass_audit_writes_share_the_business_transaction) | Step 3: ordinary pending sentinel/global-owner refusal, typed global composition and two new central seams with independent failure/uncertainty/duplicate proof. Six ordinary seams and two confined global seams are implemented. | +| [`Tenant_Authentication_Profile_Is_Closed`](#tenant_authentication_profile_is_closed), [`Keycloak_Roles_Are_Not_Application_Authority`](#keycloak_roles_are_not_application_authority), [`Authenticated_Rate_Limits_Use_Validated_Subject`](#authenticated_rate_limits_use_validated_subject), [`Authentication_Middleware_Order_Is_Enforced`](#authentication_middleware_order_is_enforced) | Step 5: verified subject before quota/binding SQL, optional actor evidence, normalized existing binding, uniform 401 and immutable feature/caller census. Numeric quota/fault/once-per-request semantics remain. | +| [`Authenticated_Http_Surface_Is_Enumerated_And_ReadOnly`](#authenticated_http_surface_is_enumerated_and_readonly) | Step 5: existing-binding read, unchanged endpoint/SDK union, AccountSite404/405 and native publication. No POST or tenantless completion; P03-3 owns transport activation. | #### `Every_TenantCustomFieldDef_Declares_PiiCategory` @@ -3094,8 +3264,9 @@ which decides identity, multiplicity, capture and classification; `The_AppendOnly_Sweep_Can_Actually_Fail`, that checks the pattern against the shapes it must catch and the shapes it must not, because with no offending statement anywhere the sweep passes whether it works or matches nothing; and a reflection check, - `IAuditStore_Exposes_No_Update_Method`, that `IAuditStore` exposes exactly five write - methods and no update (the additive fifth terminal seam ships in P02b-2 Step 2). None + `IAuditStore_Exposes_No_Update_Method`, that `IAuditStore` exposes exactly eight + write methods and no update: the event/job seams ship in Phase 02b, and + ADR-0072's two global seams ship in P03-1 Step 3. None 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 @@ -3114,10 +3285,14 @@ which decides identity, multiplicity, capture and classification; 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.** `IUserReferenceLocator` and - `UserGdprDeletedIntegrationEventHandler` land with the `users` table they need - ([ADR-0044 § What we explicitly punted on](../decisions/0044-audit-write-path.md)), so - until then there is no locator to count and no module obliged to have one. Reserving the +- **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 @@ -3930,7 +4105,6 @@ implements it. | `Cert_PrivateKey_NeverLeavesVault_To_Logs` | The log redaction filter strips a PEM private-key block before a line is emitted, in every deployment mode | behavioural | [Phase 02c](../roadmap/phase-02c-hub-foundation.md) on the Hub side, per ADR-0022, which applies it in every mode; on the LearnStack side [Phase 11](../roadmap/phase-11-production-hardening.md), with the TLS automation — the first LearnStack code that handles certificate material, and a Self-Hosted air-gapped deployment has no Hub | ADR-0022; [Custom Domain TLS](../architecture/27-custom-domain-tls.md) | | `Frontend_Has_Only_The_OperatorPortal_App` | The Hub repository ships exactly one frontend application, the operator portal | structural | [Phase 02c](../roadmap/phase-02c-hub-foundation.md), owned and run by the `learnstack-hub` repository | [ADR-0019](../decisions/0019-learnstack-hub.md) | | `Customization_Reference_Resolution_Is_Batched` | Resolving an entry's references costs a small constant number of queries, not one per reference | behavioural | [Phase 05](../roadmap/phase-05-education-learning-content.md), with the batched reference walk — Phase 02d's lesson body carries its fields inline and resolves no reference | [Tenant Customization Model](../architecture/32-tenant-customization-model.md); [Phase 05](../roadmap/phase-05-education-learning-content.md) | -| `Permission_Definitions_DeclareScope` | Every registered permission declares its `PermissionScope` — Platform, Tenant or Organization | structural | [Phase 03](../roadmap/phase-03-identity-admin.md), with the permission registry | [ADR-0017](../decisions/0017-tenant-organization-hierarchy.md) | | `Permission_Scope_Matches_Resource_Scope` | An `Organization`-scope permission is checked only against an `[OrganizationScoped]` resource, and a `Tenant`-scope permission never gains organization filtering | structural | [Phase 03](../roadmap/phase-03-identity-admin.md) | [Permissions](19-permissions.md); `add-permission` | | `Permission_Keys_Match_Convention` | Every registered key parses as `{module}.{resource}.{action}` with an action from the closed set | structural | [Phase 03](../roadmap/phase-03-identity-admin.md) | [Permissions](19-permissions.md); `add-permission` | | `Permission_Registry_Has_DeniedTest` | Every registered key has at least one test that is denied it | structural | [Phase 03](../roadmap/phase-03-identity-admin.md) | [Permissions](19-permissions.md); `add-permission` | @@ -4744,7 +4918,10 @@ structural test proves — and what it does not. #### `Tenant_Authentication_Profile_Is_Closed` - **Asserts:** the real stock handler enforces ADR-0064's signed RS256, issuer, - audience, purpose/client, bounded lifetime, stable actor and scalar UUID profile; + audience, purpose/client, bounded lifetime and scalar UUID profile; + ADR-0072 makes the wire actor optional compatibility evidence. Only a matching + Active existing binding normalizes the application actor, after subject quota; + unknown/conflicting/nonadmitting/unavailable bindings refuse uniformly. duplicate JSON/security properties and duplicate or unsupported JOSE parameters fail. Credential shape/size and configured-key-only discovery are bounded. Controlled metadata proves added-key refresh and rejection after observed key @@ -4764,7 +4941,8 @@ structural test proves — and what it does not. - **Source:** [ADR-0064](../decisions/0064-tenant-api-authentication-boundary.md) § Access-token profile and § Vendor diagnostic boundary; [ADR-0065](../decisions/0065-bounded-tenant-assertion-diagnostics.md) - § Outbound telemetry scope. + § Outbound telemetry scope; + [ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md). - **Type:** real JwtBearer/OIDC handler with controlled signed-token issuer, discovery/JWKS server and actual logging/export/error-capture controls. **Kind:** behavioural. @@ -4772,6 +4950,10 @@ structural test proves — and what it does not. `backend/tests/LearnStack.Tests.Integration/TenantAuthenticationProfileTests.cs`; actual sink/export controls in `TenantAuthenticationDiagnosticsTests.cs` and `TenantAuthenticationDiagnosticsTests.Metrics.cs` in the same project. + `Database/TenantExistingBindingAdmissionTests*.cs` adds actual app-role binding, + startup, outage, no-allocation, lookup/pool and cancellation controls; + `TenancyIdentity/TenantRealmApiTests.ExistingBinding.cs` supplies the real + provider actorless-existing-binding positive. - **Status:** **Implemented** (`TenantAuthenticationProfileTests` and the diagnostic owners above). ADR-0065's ordinary HTTP hostname/IP/numeric-port/ path/query negatives retain real unprojected positives and ordinary traces. @@ -4788,7 +4970,8 @@ structural test proves — and what it does not. #### `Authentication_Middleware_Order_Is_Enforced` - **Asserts:** the actual chain preserves early admission/body limits, host - classification, authentication, credential enforcement, subject quota, tenant + classification, authentication, credential enforcement, subject quota, + existing-binding normalization, tenant resolution/assertions, authorization, closed-surface admission and dispatch in ADR-0064 order. Unknown-host/early-quota precedence survives; subject refusal prevents durable mismatch recording. A planted reorder fails. Production scheme @@ -4803,13 +4986,14 @@ structural test proves — and what it does not. the existing health endpoint-convention builder remains clean. This is not a general C# semantic analysis of arbitrary reflection or dynamic code. - **Source:** [ADR-0064](../decisions/0064-tenant-api-authentication-boundary.md) - § Pipeline and error precedence. + § Pipeline and error precedence; + [ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md). - **Type:** whole-chain actual-host HTTP controls plus a planted reorder control. **Kind:** behavioural. - **Test owner:** `backend/tests/LearnStack.Tests.Integration/TenantAuthenticationHttpTests.cs`. - **Status:** **Implemented** (`TenantAuthenticationHttpTests`, - `AuthenticatedRateLimitTests`). + `AuthenticatedRateLimitTests`, `TenantExistingBindingAdmissionTests`). - **Phase:** P02b-5 Step 3 component harness; Step 4 actual activation; Step 5 complete production enforcement. @@ -4874,12 +5058,14 @@ structural test proves — and what it does not. controls; missing subjects or a weakened predicate fail. Phase 03 retains membership and permission authority. - **Source:** [ADR-0064](../decisions/0064-tenant-api-authentication-boundary.md) - § Access-token profile and § Resolution and attribution; ADR-0004. + § Access-token profile and § Resolution and attribution; ADR-0004; + [ADR-0072](../decisions/0072-application-owned-identity-bootstrap.md). - **Type:** complete production source/IL call-site census with planted compiled violations and predicate-mutation controls. **Kind:** structural. - **Test owner:** `backend/tests/LearnStack.Tests.Architecture/AuthenticationAuthorityTests.cs`. - Its real production graph closes typed projection creation, feature writes, + Its real production graph separately closes verified-subject and normalized + identity creation, feature writes, immutable shape and direct actor/scope/subject accessors. Signature, local, field, method and generic-argument uses close projection acquisition and forwarding, including object/generic formatting. Raw IdentityModel accessors @@ -4899,6 +5085,9 @@ structural test proves — and what it does not. and opaque subject, with no queue. Token rotation or tenant/organization changes cannot reset quota; distinct subjects have independent state. Invalid tokens gain no quota identity or early bypass. Existing visitor/peer limits remain. + ADR-0072's verified-subject stage requires no wire actor and precedes every + binding read. Reentry retains the original immutable subject provenance; + changed or missing evidence cannot borrow an earlier decision or identity. Whole-chain reduced-budget controls isolate subject accounting beneath those floors; a separate proof covers the actual 600 boundary. Concurrent accounting, first-refusal Retry-After/429, a finite partition registry with refusal before @@ -6084,7 +6273,12 @@ and fixture definitions make the implemented controls non-vacuous. Pending-only API acquisition validates each fresh complete snapshot under one finite deadline; it never combines responses or retries terminal, malformed, missing, duplicate or identity-invalid evidence. -- **Source:** [ADR-0063](../decisions/0063-complete-bounded-ci-test-shards.md). + The ADR-0075 extension binds the ordinary-only twenty-five-minute whole-job + and enclosing observation bounds to verified expected producer identity; + other producers retain twenty minutes, operation caps and the 203-second + reserve stay fixed. Forged modes/partitions cannot select a longer window. +- **Source:** [ADR-0063](../decisions/0063-complete-bounded-ci-test-shards.md), + [ADR-0075](../decisions/0075-ordinary-ci-job-window.md). - **Type:** actual Python plan/owner subprocess controls and workflow/API/hosted result proofs. **Kind:** structural + behavioural. - **Status:** **Implemented** — `scripts/ci-test-shards.py`, @@ -6097,6 +6291,13 @@ and fixture definitions make the implemented controls non-vacuous. gates/toolchain/resource fields, partial-rerun refusals and canonical-name collisions. The phase's Step 3 record separately owns actual final-source two-assignment hosted qualification; source enforcement is not a fit claim. + **ADR-0075 extension implemented** by the same owners and offline suites: + exact mode/job/index policy, ordinary-only workflow/API/receipt/measurement + windows, fixture-preparation identity, unchanged operation caps and forged + identity/nonfinite/threshold counterexamples. The + [Phase 03 closeout](../roadmap/phase-03-delivery-log.md#adr-0075-three-step-closeout-2026-10-27) + owns implementation reviews and observed complete hosted A/B; local controls + alone do not establish fit and later documentation identities remain distinct. - **Phase:** 02b (P02b-4 CI follow-up). ## References diff --git a/docs/standards/README.md b/docs/standards/README.md index 9622d668c..0f6c8be17 100644 --- a/docs/standards/README.md +++ b/docs/standards/README.md @@ -105,10 +105,10 @@ included. |---|---|---|---| | 00 | [Principles](00-principles.md) | **Active** | Governs every PR and every ADR; principles 1, 16 and 17 are already deciding live scope questions. | | 01 | [Architecture Standards](01-architecture-standards.md) | **Active** | Module layout shipped; `ModuleDomain_DoesNotDependOn_*` and the planted-violation meta-test are green. | -| 02 | [Backend Coding](02-backend-coding.md) | **Active** | MediatR pipeline, `Result`, `IClock`, the `LS0001` analyzer and the pipeline-order test all ship. Packet 6 brought the first `DbContext`, the first aggregates and the ambient unit of work, so its EF Core and domain-modelling clauses became live. Tenancy, Customization, Audit and Education now implement domain and persistence code. | +| 02 | [Backend Coding](02-backend-coding.md) | **Active** | MediatR pipeline, `Result`, `IClock`, the `LS0001` analyzer and the pipeline-order test all ship. Packet 6 brought the first `DbContext`, the first aggregates and the ambient unit of work, so its EF Core and domain-modelling clauses became live. Tenancy, Customization, Audit, Education and Identity implement domain and persistence code. | | 03 | [Frontend Coding](03-frontend-coding.md) | **Active** | ESLint and TypeScript strict mode are configured, the Vitest harness runs, and Packet 10 added the two rules this document's § Forbidden names — the direct-`fetch` ban and `dangerouslySetInnerHTML` outside the sanitised-HTML primitive — with a test that lints fixtures through the app's own configuration, because a configured rule and a missing one look identical from a green `pnpm lint`. P02d-5 delivers trusted entry/caller controls; P02d-6 Step 1 implements complete UI catalogues, ICU/callsite controls and synchronous chrome/state views; Step 2 adds catalog/course views and metadata; Step 3 adds ordered lesson presentation and blocking JSX accessibility controls. | | 04 | [API Design](04-api-design.md) | **Active** | Packet 4 shipped the versioned route convention and its startup guards, one Problem Details shape on every error including the framework-minted ones, cursor pagination, the sort grammar, idempotency keys, ETag concurrency, correlation ids, the request-body limit and the tenancy edge — each with tests in the required `backend` check. P02d-4 adds four institution public GET/HEAD pairs, served/snapshot contract controls and compatibility CI; application writers remain unrouted. | -| 05 | [Database](05-database.md) | **Active** | Five compiled migration chains are reconciled against the independent live PostgreSQL census and canonical table classes; the [database standard](05-database.md#table-classes) owns the current classification. The four-role model and canonical RLS template (`ENABLE` **and** `FORCE`, one `AND`-ed policy per table) are tested as `learnstack_app`. Concurrency, indexes and exact grants each have planted controls. Partitioning and retention jobs belong to Phase 11. | +| 05 | [Database](05-database.md) | **Active** | Six compiled migration chains are reconciled against the independent live PostgreSQL census and canonical table classes; the [database standard](05-database.md#table-classes) owns the current classification. The four-role model and canonical RLS template (`ENABLE` **and** `FORCE`, one `AND`-ed policy per table) are tested as `learnstack_app`. Concurrency, indexes and exact grants each have planted controls. Partitioning and retention jobs belong to Phase 11. | | 06 | [Testing](06-testing.md) | **Active** | Unit, architecture, contract and Docker-free HTTP populations feed the required backend aggregate; complementary ordinary/native Docker populations feed `backend integration (Testcontainers)`. The [CI contract](../../.github/CONTRIBUTING.md#branch-protection-settings-on-main) names all seven required contexts. ADR-0063's complete current-attempt case and cleanup receipts, rather than a two-job filter sketch, enforce the partition. | | 07 | [Frontend Architecture](07-frontend-architecture.md) | **Active** | The one-app rule is mechanical — `Frontend_Has_Only_The_Web_App` fails a second application in this repository — and the route groups it prescribes exist as layouts. The rest, the server/client split and the tenant context an SDK call carries, is exercised first in [Phase 02d](../roadmap/phase-02d-walking-skeleton.md): Active for what ships, and the phase that adds components is the one that tests them. | | 08 | [Localization](08-localization.md) | **Active** | Packet 6 shipped `tenant_locales` and the slug schema. The partial unique default index enforces at most one default, not existence of a default for every enabled set; P02d-2 ships supported-write validation and the default-enabled CHECK constraint; raw deletes can still leave an enabled locale set without a default. `LocalizedText` and `LocalizedMessage` ship with their own cases, and API errors are keyed. P02d-1 shipped Education Pattern A satellites, canonical locales and flat localized-slug uniqueness; P02d-4 Step 3 delivers exact enabled public locale admission and response labels. P02d-5 Step 3 delivers membership-first redirect G36. P02d-6 Step 1 implements Accepted ADR-0027/G39's next-intl 4.14.9 plugin/request runtime, app-local `src/i18n/messages/{en,tr}/public.json` and catalogue controls. Phase 04 inherits the foundation for CMS/Studio. | @@ -122,7 +122,7 @@ included. | 16 | [Accessibility](16-accessibility.md) | **Active** | P6 delivers catalog/course/lesson and controlled-state semantics, all 31 active recommended jsx-a11y rules at error severity with per-rule actual-config dirty/clean controls, and real product HTML/Flight proofs. The [packet closeout](../roadmap/phase-02d-delivery-log.md#p02d-6-packet-closeout-2026-10-10) records keyboard/focus/reflow/contrast observations and the maintainer's passing VoiceOver smoke. This is enforcement for delivered public-page scope, not a full WCAG audit. P02d-7 adds hard Lighthouse automated accessibility and a narrow library browser walkthrough; full Playwright Test/axe remains [Phase 06](../roadmap/phase-06-renderer-admin-studio.md). | | 17 | [Code Review](17-code-review.md) | **Active** | Applied to every pull request merged so far; the zero-tolerance blocker list is in live use. | | 18 | [Audit Coverage](18-audit-coverage.md) | **Active** | Packet 9 lit the write path under [ADR-0033](../decisions/0033-audit-durability-model.md) and [ADR-0044](../decisions/0044-audit-write-path.md): classification at step 3, MUST rows on the business transaction before `COMMIT`, `audit_log` / `audit_config` with their append-only layers, and the catalogue ↔ matrix join enforced in both directions and per request/concrete integration-handler identity by `AuditCoverageTests`; actual API/Seeder catalogue parity includes Off coordinators. Retention and partitioning are [Phase 11](../roadmap/phase-11-production-hardening.md)'s. | -| 19 | [Permissions](19-permissions.md) | **Adopted** | No application permission key or application role exists. P02b-5's AccountSite admission policy grants neither; the permission registry and enforcement land in [Phase 03](../roadmap/phase-03-identity-admin.md). | +| 19 | [Permissions](19-permissions.md) | **Adopted** | The finite scoped registry, Role templates and seed command declarations are implemented under the [Identity foundation contract](19-permissions.md#identity-foundation-contract). API composition denies seed authority; live permission enforcement remains P03-2, with current qualification owned by [Phase 03](../roadmap/phase-03-identity-admin.md). | | 20 | [Infrastructure Stack](20-infrastructure-stack.md) | **Active** | `ISecretProvider` shipped in Packet 3, the foundation ports and their defaults in Packet 5, and the entitlement socket in Packet 9; `DeploymentMode` branching happens once, at the composition root. P02b-2 delivers producer dispatch; P02b-3 Steps 1–5 add durable acceptance, shared inbox and independently scheduled default consumers. 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. Packet 10 made the bans this document states mechanical: no module reaches a cache client, a Hub namespace, `audit_log` or `platform_entitlement_cache`, and every entitlement key a call site names is a registry member. The adapters themselves — Dapr, Kafka, Valkey, Vault, APISIX — arrive on [ADR-0035](../decisions/0035-demand-gated-infrastructure.md)'s triggers, which is the model rather than a gap in it. | | 21 | [Architecture Tests Catalogue](21-architecture-tests-catalogue.md) | **Active** | The catalogue's own § Implemented today carries the counts, and `The_Catalogue_Counts_Its_Own_Rules` recomputes them, so this row does not keep a third copy. Rules run in the architecture assembly and beside it in the unit, integration and frontend suites — each where it can actually fail, against an applied schema, a real host or a real ESLint configuration. `Every_Implemented_Rule_Names_A_Test_That_Exists` holds each Implemented entry to a method of that name. `No_Architecture_Test_Is_Skippable` governs backend suites; P02d-5 delivers G38(d)'s guarded frontend runner and planted skip/todo, empty-report and omitted-workspace controls. | diff --git a/frontend/apps/web/scripts/verify-bff-browser.mjs b/frontend/apps/web/scripts/verify-bff-browser.mjs index c3546e6a2..3fedd520d 100644 --- a/frontend/apps/web/scripts/verify-bff-browser.mjs +++ b/frontend/apps/web/scripts/verify-bff-browser.mjs @@ -226,6 +226,8 @@ try { '--disable-component-update', '--disable-sync', '--disable-breakpad', + '--password-store=basic', + '--use-mock-keychain', '--no-proxy-server', '--host-resolver-rules=' + input.sites.map((site) => 'MAP ' + site.host.split(':')[0] + ' 127.0.0.1').join(','), diff --git a/frontend/apps/web/src/server/auth/provider-core.ts b/frontend/apps/web/src/server/auth/provider-core.ts index ef775762e..5511db26e 100644 --- a/frontend/apps/web/src/server/auth/provider-core.ts +++ b/frontend/apps/web/src/server/auth/provider-core.ts @@ -43,8 +43,11 @@ function identity(claims: oidc.IDToken | undefined, issuer: string): ProviderIde claims.iss !== issuer || typeof claims.sub !== 'string' || !claims.sub || - claims.sub.length > 1024 || - /[\r\n]/.test(claims.sub) || + claims.sub.length > 255 || + /^[\t\n\v\f\r \u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+$/u.test( + claims.sub, + ) || + /[\0\r\n\ud800-\udfff]/u.test(claims.sub) || typeof claims.user_id !== 'string' || !uuid.test(claims.user_id) || claims.user_id === allZero || diff --git a/frontend/apps/web/src/server/auth/provider.test.ts b/frontend/apps/web/src/server/auth/provider.test.ts index 5994e555d..60a1fdbc4 100644 --- a/frontend/apps/web/src/server/auth/provider.test.ts +++ b/frontend/apps/web/src/server/auth/provider.test.ts @@ -315,6 +315,21 @@ describe('inactive tenant RP boundary', () => { }); } + it.each([255, 256])( + 'enforces the shared opaque subject bound at %i characters', + async (length) => { + const f = await fixture(); + const subject = 's'.repeat(length); + f.setClaims({ sub: subject }); + if (length === 255) { + const { result } = await f.login(); + expect(result.identity.subject).toBe(subject); + } else { + await expect(f.login()).rejects.toMatchObject({ reason: 'identity' }); + } + }, + ); + it('rejects wrong signatures at both code and refresh processing', async () => { const f = await fixture(); const { result } = await f.login(); @@ -325,6 +340,39 @@ describe('inactive tenant RP boundary', () => { await expect(f.login()).rejects.toMatchObject({ reason: 'response' }); }); + it.each([ + ' ', + '\u0085\u3000', + 'private\0subject', + 'private\ud800', + 'private\udc00', + '🙂'.repeat(128), + ])( + 'refuses nonstorable, whitespace-only or over-bound subjects at code and refresh processing (%#)', + async (subject) => { + const f = await fixture(); + const { result } = await f.login(); + f.setClaims({ sub: subject }); + await expect(f.login()).rejects.toMatchObject({ reason: 'identity' }); + await expect(f.provider.refresh(result.refreshToken!, result.identity)).rejects.toMatchObject( + { reason: 'identity' }, + ); + }, + ); + + it.each([' I/ı/🙂 ', '🙂'.repeat(127) + 'a'])( + 'preserves exact non-ASCII subject text at both grants (%#)', + async (subject) => { + const f = await fixture(); + f.setClaims({ sub: subject }); + const { result } = await f.login(); + expect(result.identity.subject).toBe(subject); + expect( + (await f.provider.refresh(result.refreshToken!, result.identity)).identity.subject, + ).toBe(subject); + }, + ); + for (const patch of [ { sub: 'replacement-subject' }, { user_id: '019a154b-0000-7000-8000-000000000012' }, diff --git a/frontend/apps/web/src/server/ingress.test.ts b/frontend/apps/web/src/server/ingress.test.ts index cd2b5ac4e..a0d9ea4e3 100644 --- a/frontend/apps/web/src/server/ingress.test.ts +++ b/frontend/apps/web/src/server/ingress.test.ts @@ -265,32 +265,62 @@ describe('private local configuration', () => { ).toBe('explicit'); }); - it('resolves API issuer across source, projection and ambient inputs only for the API launcher', () => { - const key = 'Authentication__Tenant__Issuer'; - const issuer = 'https://identity.example/realms/learnstack'; + const identityPair = { + Authentication__Tenant__Issuer: 'https://identity.example/realms/learnstack', + Identity__AuthorityId: '019a1929-5450-7bbb-8df1-516e8e002501', + }; + const identitySource = Object.entries(identityPair) + .map(([key, value]) => key + '=' + value) + .join('\n'); + + it('resolves complete matching identity pairs only for the API launcher', () => { const options = { apiAuthentication: true }; const projectionDirectory = join(directory, 'frontend/apps/web'); mkdirSync(projectionDirectory, { recursive: true }); const projectionPath = join(projectionDirectory, '.env.local'); - writeFileSync(join(directory, '.env'), key + '=' + issuer); - writeFileSync(projectionPath, key + '=' + issuer); - expect(loadLocalEnvironment(directory, {}, options)[key]).toBe(issuer); - expect(loadLocalEnvironment(directory, { [key]: issuer }, options)[key]).toBe(issuer); - expect(() => loadLocalEnvironment(directory, { [key]: issuer + '-hub' }, options)).toThrow( - 'Conflicting API authentication configuration', - ); - writeFileSync(projectionPath, key + '=' + issuer + '-hub'); - expect(() => loadLocalEnvironment(directory, {}, options)).toThrow( - 'Conflicting API authentication configuration', - ); - expect(loadLocalEnvironment(directory, { [key]: 'unrelated' })[key]).toBeUndefined(); + writeFileSync(join(directory, '.env'), identitySource); + writeFileSync(projectionPath, identitySource); + expect(loadLocalEnvironment(directory, identityPair, options)).toMatchObject(identityPair); + for (const key of Object.keys(identityPair)) { + expect(() => + loadLocalEnvironment(directory, { ...identityPair, [key]: 'conflict' }, options), + ).toThrow('Conflicting API authentication configuration'); + expect(loadLocalEnvironment(directory, { [key]: 'unrelated' })[key]).toBeUndefined(); + } writeFileSync(join(directory, '.env'), ''); - writeFileSync(projectionPath, key + '=' + issuer); - expect(loadLocalEnvironment(directory, {}, options)[key]).toBe(issuer); + expect(loadLocalEnvironment(directory, {}, options)).toMatchObject(identityPair); writeFileSync(projectionPath, ''); - expect(loadLocalEnvironment(directory, { [key]: issuer }, options)[key]).toBe(issuer); + expect(loadLocalEnvironment(directory, identityPair, options)).toMatchObject(identityPair); + expect(loadLocalEnvironment(directory, {}, options)).toEqual({}); }); + it.each(['root', 'projection', 'ambient'] as const)( + 'refuses a partial %s pair even when another source supplies its missing key', + (partial) => { + const projectionDirectory = join(directory, 'frontend/apps/web'); + mkdirSync(projectionDirectory, { recursive: true }); + const rootPath = join(directory, '.env'); + const projectionPath = join(projectionDirectory, '.env.local'); + writeFileSync( + rootPath, + partial === 'root' + ? 'Identity__AuthorityId=' + identityPair.Identity__AuthorityId + : identitySource, + ); + writeFileSync( + projectionPath, + partial === 'projection' + ? 'Authentication__Tenant__Issuer=' + identityPair.Authentication__Tenant__Issuer + : '', + ); + const ambient = + partial === 'ambient' ? { Identity__AuthorityId: identityPair.Identity__AuthorityId } : {}; + expect(() => loadLocalEnvironment(directory, ambient, { apiAuthentication: true })).toThrow( + 'Incomplete API authentication configuration', + ); + }, + ); + const configuration = { LEARNSTACK_PUBLIC_API_ORIGIN: 'http://127.0.0.1:5080', LEARNSTACK_PUBLIC_HOP_SECRET: secret, diff --git a/frontend/apps/web/src/server/ingress.ts b/frontend/apps/web/src/server/ingress.ts index 5336f868a..588eb38e5 100644 --- a/frontend/apps/web/src/server/ingress.ts +++ b/frontend/apps/web/src/server/ingress.ts @@ -321,16 +321,26 @@ export function loadLocalEnvironment( ]) { if (environment[key] !== undefined) result[key] = environment[key]; } - const issuerKey = 'Authentication__Tenant__Issuer'; // Web startup does not consume API authentication configuration. Only the API - // launcher opts into resolving this private value and its conflict checks. - delete result[issuerKey]; + // launcher resolves the exact issuer/authority pair and its conflict checks. + const identityKeys = ['Authentication__Tenant__Issuer', 'Identity__AuthorityId']; + for (const key of identityKeys) delete result[key]; if (options.apiAuthentication) { - const issuers = [source[issuerKey], projection[issuerKey], environment[issuerKey]].filter( - (value): value is string => value !== undefined, - ); - if (new Set(issuers).size > 1) throw new Error('Conflicting API authentication configuration'); - if (issuers[0] !== undefined) result[issuerKey] = issuers[0]; + for (const input of [source, projection, environment]) { + const present = identityKeys.filter((key) => input[key] !== undefined); + if ( + present.length !== 0 && + (present.length !== identityKeys.length || present.some((key) => !input[key])) + ) + throw new Error('Incomplete API authentication configuration'); + } + for (const key of identityKeys) { + 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 authentication configuration'); + if (values[0] !== undefined) result[key] = values[0]; + } } return result; } diff --git a/frontend/apps/web/src/test/demo-lifecycle.test.ts b/frontend/apps/web/src/test/demo-lifecycle.test.ts index f64dd7fa0..a272f3607 100644 --- a/frontend/apps/web/src/test/demo-lifecycle.test.ts +++ b/frontend/apps/web/src/test/demo-lifecycle.test.ts @@ -99,6 +99,8 @@ export async function ${method}() { appendFileSync(${JSON.stringify(join(root, ' 'ConnectionStrings__Migration=Username=learnstack_migration', 'ConnectionStrings__Default=Username=learnstack_app', 'ConnectionStrings__OutboxDispatcher=Username=learnstack_outbox_admin', + 'Identity__AuthorityId=01930000-0000-7000-8000-000000009001', + 'Authentication__Tenant__Issuer=http://localhost:8080/realms/learnstack', 'KEYCLOAK_ADMIN=fixture-admin', `KEYCLOAK_ADMIN_PASSWORD=${randomBytes(16).toString('hex')}`, `KEYCLOAK_WEB_CLIENT_SECRET=${randomBytes(16).toString('hex')}`, @@ -546,7 +548,7 @@ const { appendFileSync } = require('node:fs'); const args = process.argv.slice(2); const startup = JSON.stringify(args) === JSON.stringify(['dev']); const migration = JSON.stringify(args) === JSON.stringify(['migrate']); -const forbidden = Object.keys(process.env).filter(key => /keycloak|connectionstrings|_pw$|bff|debug/i.test(key) && !(migration && key === 'ConnectionStrings__Migration')); +const forbidden = Object.keys(process.env).filter(key => /keycloak|connectionstrings|_pw$|bff|debug|^Identity__AuthorityId$|^Authentication__Tenant__Issuer$/i.test(key) && !(migration && ['ConnectionStrings__Migration', 'Identity__AuthorityId', 'Authentication__Tenant__Issuer'].includes(key))); if ((!startup && !migration) || forbidden.length || process.env.ConnectionStrings__Migration !== (migration ? 'Username=learnstack_migration' : undefined) || process.env.LEARNSTACK_COMPOSE_PROJECT !== 'learnstack-dev' || process.env.LEARNSTACK_COMPOSE_ENV_FILE !== ${JSON.stringify(join(root, '.env'))} || process.env.LEARNSTACK_COMPOSE_MODE !== 'dev') process.exit(13); appendFileSync(${JSON.stringify(join(root, 'events'))}, (startup ? 'stack-up' : 'migrate') + '\\n'); `, @@ -607,11 +609,16 @@ appendFileSync(${JSON.stringify(join(root, 'events'))}, (build ? 'build' : 'apps join(root, 'scripts/connection-string.awk'), readFileSync(new URL('../../../../../scripts/connection-string.awk', import.meta.url)), ); + for (const name of ['migrate', 'compose', 'demo-database', 'development-realm-errors']) + writeFileSync( + join(root, `scripts/${name}.mjs`), + readFileSync(new URL(`../../../../../scripts/${name}.mjs`, import.meta.url)), + ); writePrivateFileSync( join(root, '.env'), 'ConnectionStrings__Migration=Username=learnstack_platform\n', ); - writeFileSync( + writePrivateFileSync( join(root, 'alternate.env'), 'ConnectionStrings__Migration=Username=learnstack_app\n', ); @@ -627,8 +634,8 @@ appendFileSync(${JSON.stringify(join(root, 'events'))}, (build ? 'build' : 'apps }); expect(result.error).toBeUndefined(); expect(result.status).not.toBe(0); - expect(result.stdout).toContain("Username='learnstack_app'"); - expect(result.stdout).not.toContain("Username='learnstack_platform'"); + expect(result.stdout + result.stderr).toContain("Username='learnstack_app'"); + expect(result.stdout + result.stderr).not.toContain("Username='learnstack_platform'"); }); it('accepts only the owned API address in a structured hosting lifetime event', () => { const origin = 'http://127.0.0.1:5080'; @@ -777,18 +784,19 @@ describe('demo runtime boundaries', () => { ), }); }); - it('passes the selected tenant issuer only in the constructed API environment', () => { + it.each([ + ['Authentication__Tenant__Issuer', 'https://identity.example/realms/learnstack'], + ['Identity__AuthorityId', '019a1929-5450-7bbb-8df1-516e8e002501'], + ])('passes the selected %s only in the constructed API environment', (key, value) => { const root = temporary(); - const key = 'Authentication__Tenant__Issuer'; - const issuer = 'https://identity.example/realms/learnstack'; const values = { ConnectionStrings__Default: 'application', ConnectionStrings__OutboxDispatcher: 'dispatcher', - [key]: issuer, + [key]: value, }; const configuration = { apiOrigin: 'http://127.0.0.1:5080', secret: 'private' }; - expect(publicApiEnvironment(values, configuration, {})[key]).toBe(issuer); - expect(publicWebEnvironment(values, root, { [key]: issuer })).not.toHaveProperty(key); + expect(publicApiEnvironment(values, configuration, {})[key]).toBe(value); + expect(publicWebEnvironment(values, root, { [key]: value })).not.toHaveProperty(key); expect(publicApiEnvironment({ ...values, [key]: '' }, configuration, {})).not.toHaveProperty( key, ); @@ -799,7 +807,7 @@ describe('demo runtime boundaries', () => { ConnectionStrings__OutboxDispatcher: 'dispatcher', }, configuration, - { [key]: issuer }, + { [key]: value }, ), ).not.toHaveProperty(key); }); diff --git a/frontend/apps/web/src/test/demo-realm-lifecycle.test.ts b/frontend/apps/web/src/test/demo-realm-lifecycle.test.ts index 09b4d68c4..11e55c3ad 100644 --- a/frontend/apps/web/src/test/demo-realm-lifecycle.test.ts +++ b/frontend/apps/web/src/test/demo-realm-lifecycle.test.ts @@ -38,6 +38,7 @@ function fixture() { 'compose', 'demo-process', 'demo-database', + 'migrate', 'demo-observation', 'public-runtime', 'development-realm-owner', @@ -83,8 +84,9 @@ export async function waitCompose(selected, processes, signal, postgresOnly = fa writeFileSync( join(root, 'scripts/reconcile-development-realm.mjs'), `import { RealmError } from './development-realm-errors.mjs'; -export async function reconcileDevelopmentRealm({ selected, signal }) { +export async function reconcileDevelopmentRealm({ selected, signal, seedIdentityFoundation }) { const f = globalThis.lifecycle; + f.identityFoundationRequested = seedIdentityFoundation === true; f.events.push('realm-start'); f.selectionIdentity &&= selected === f.selected; f.signalIdentity &&= signal === f.signal && signal instanceof AbortSignal; @@ -126,6 +128,8 @@ export function publicServerConfiguration(values) { KEYCLOAK_ADMIN: 'fixture-admin', KEYCLOAK_ADMIN_PASSWORD: canaries[0]!, KEYCLOAK_WEB_CLIENT_SECRET: canaries[1]!, + Identity__AuthorityId: '01930000-0000-7000-8000-000000009001', + Authentication__Tenant__Issuer: 'http://localhost:8080/realms/learnstack', LEARNSTACK_PUBLIC_API_ORIGIN: 'http://127.0.0.1:5080', LEARNSTACK_PUBLIC_HOP_SECRET: 'fixture-hop', }; @@ -185,6 +189,7 @@ type Result = { timeout?: number; }>; migrationSelection: boolean; + identityFoundationRequested: boolean; }; function execute( @@ -254,7 +259,7 @@ DemoProcesses.prototype.run = async function(command, args, options = {}) { 'NPM_CONFIG_CACHE', 'npm_config_cache', 'NPM_CONFIG_STORE_DIR', 'npm_config_store_dir', ...(startup || migration || command === 'docker' ? ['USERPROFILE', 'XDG_CONFIG_HOME', 'XDG_RUNTIME_DIR', 'DOCKER_CONFIG', 'DOCKER_CONTEXT', 'DOCKER_HOST', 'DOCKER_TLS_VERIFY', 'DOCKER_CERT_PATH', 'DOCKER_DEFAULT_PLATFORM', 'DOCKER_API_VERSION'] : []), ...(startup || migration ? ['LEARNSTACK_COMPOSE_PROJECT', 'LEARNSTACK_COMPOSE_ENV_FILE', 'LEARNSTACK_COMPOSE_MODE'] : []), - ...(migration ? ['ConnectionStrings__Migration'] : []), + ...(migration ? ['ConnectionStrings__Migration', 'Identity__AuthorityId', 'Authentication__Tenant__Issuer'] : []), ...(options.label === 'Contextual seed convergence' || options.label === 'Application seed convergence' ? ['ConnectionStrings__Default'] : [])]); // The app seed is recognised by its real, argument-free Release DLL call too. if (command === 'dotnet' && args.length === 1 && args[0].endsWith('/LearnStack.Tools.Seeder.dll')) allowed.add('ConnectionStrings__Default'); @@ -295,7 +300,8 @@ DemoProcesses.prototype.run = async function(command, args, options = {}) { let failure = '', notice = '', preparationDispatched = false; const report = () => ({ events: f.events, commands: f.commands, failure, notice, preparationDispatched, selectionIdentity: f.selectionIdentity, signalIdentity: f.signalIdentity, - selectedDescription: f.selectedDescription, migrationSelection: f.migrationSelection }); + selectedDescription: f.selectedDescription, migrationSelection: f.migrationSelection, + identityFoundationRequested: f.identityFoundationRequested }); if (${JSON.stringify(entryCli)}) { process.on('exit', () => writeFileSync(${JSON.stringify(join(f.root, 'entry-report'))}, JSON.stringify(report()))); } else { @@ -403,7 +409,7 @@ export function record(stage, connection, selected = true) { const confined = Object.keys(process.env).every(key => !/keycloak|connectionstrings|_pw$|password|bff|debug|private/i.test(key) || key === permitted); const connectionMatches = permitted === undefined || process.env[permitted] === values[permitted]; - const metadataMatches = connection !== 'Migration' || ( + const metadataMatches = connection !== 'Migration' || stage === 'authority-install' || ( process.env.LEARNSTACK_COMPOSE_PROJECT === ${JSON.stringify(project)} && process.env.LEARNSTACK_COMPOSE_ENV_FILE === ${JSON.stringify(selectedFile)} && process.env.LEARNSTACK_COMPOSE_MODE === 'e2e'); @@ -470,9 +476,15 @@ if (JSON.stringify(args) === JSON.stringify(['compose', 'version'])) { `#!${process.execPath} import { record, values } from '../scripts/boundary-observer.mjs'; const args = process.argv.slice(2); +if (args.length === 1 && args[0].endsWith('/LearnStack.Tools.IdentityAuthorityInstaller.dll')) { + record('authority-install', 'Migration', process.env.Identity__AuthorityId === values.Identity__AuthorityId + && process.env.Authentication__Tenant__Issuer === values.Authentication__Tenant__Issuer); + process.exit(0); +} if (process.cwd() !== ${JSON.stringify(join(f.root, 'backend'))}) process.exit(19); if (JSON.stringify(args) === JSON.stringify(['tool', 'restore'])) record('migration-tools'); else if (JSON.stringify(args) === JSON.stringify(['build', 'src/LearnStack.Api', '--configuration', 'Release', '--nologo'])) record('migration-build'); +else if (JSON.stringify(args) === JSON.stringify(['build', 'src/LearnStack.Tools.IdentityAuthorityInstaller', '--configuration', 'Release', '--nologo'])) record('authority-build'); else if (args[0] === 'ef' && args[1] === 'database' && args[2] === 'update') record('migration-ef', 'Migration', !args.includes('--connection') && !args.some(arg => arg.includes('Password='))); else if (JSON.stringify(args) === JSON.stringify(['build', 'src/LearnStack.Tools.Seeder', '--configuration', 'Release', '--nologo'])) record('seeder-build'); else if (args.length === 1 && args[0] === ${JSON.stringify(join(f.root, 'backend/src/LearnStack.Tools.Seeder/bin/Release/net10.0/LearnStack.Tools.Seeder.dll'))}) record('appseed', 'Default'); @@ -484,11 +496,11 @@ else process.exit(19); join(f.root, 'scripts/reconcile-development-realm.mjs'), `import { appendFileSync, readFileSync } from 'node:fs'; import { realmEnvironment } from './development-realm-owner.mjs'; -export async function reconcileDevelopmentRealm({ selected, signal }) { +export async function reconcileDevelopmentRealm({ selected, signal, seedIdentityFoundation }) { const values = realmEnvironment(readFileSync(selected.file, 'utf8')); const parentPrivate = Object.entries(values).every(([key, value]) => process.env[key] === value); const selectedSource = selected.file === ${JSON.stringify(selectedFile)} && selected.project === ${JSON.stringify(project)} - && selected.mode === 'e2e' && signal instanceof AbortSignal; + && selected.mode === 'e2e' && signal instanceof AbortSignal && seedIdentityFoundation === true; appendFileSync(${JSON.stringify(events)}, JSON.stringify({ stage: 'realm', confined: true, selected: selectedSource, parentPrivate }) + '\\n'); return { mutations: 0 }; @@ -523,7 +535,7 @@ export async function reconcileDevelopmentRealm({ selected, signal }) { environment, selectedFile, sensitiveValues, - run() { + run(expectSuccess = true) { writeFileSync(events, ''); const execution = spawnSync('make', ['seed'], { cwd: f.root, @@ -537,7 +549,8 @@ export async function reconcileDevelopmentRealm({ selected, signal }) { ), ).toBe(false); expect(execution.error).toBeUndefined(); - expect(execution.status).toBe(0); + if (expectSuccess) expect(execution.status).toBe(0); + else expect(execution.status).not.toBe(0); expect(readFileSync(join(f.root, '.env'), 'utf8') === defaultSource).toBe(true); expect(readFileSync(selectedFile, 'utf8') === f.source).toBe(true); return readFileSync(events, 'utf8') @@ -954,7 +967,9 @@ DemoProcesses.prototype.dispose = async function() { 'readiness-status', 'migration-tools', 'migration-build', + 'authority-build', 'migration-ef', + 'authority-install', 'readiness-config', 'readiness-status', 'seeder-build', @@ -973,8 +988,9 @@ DemoProcesses.prototype.dispose = async function() { ); expect(planted).not.toBe(source); writeFileSync(makefile, planted); - const inherited = f.run(); + const inherited = f.run(false); expect(confined(inherited)).toBe(false); + expect(inherited.some((event) => event.stage.startsWith('migration-'))).toBe(false); expect( inherited .filter((event) => @@ -1011,6 +1027,7 @@ DemoProcesses.prototype.dispose = async function() { ]); expect(result.selectionIdentity).toBe(true); expect(result.signalIdentity).toBe(true); + expect(result.identityFoundationRequested).toBe(true); expect(result.selectedDescription).toEqual({ project: 'owned-seed', file: join(f.root, 'selected.env'), @@ -1104,6 +1121,7 @@ DemoProcesses.prototype.dispose = async function() { prerequisitesPreserved: true, }); expect(result.migrationSelection).toBe(true); + expect(result.identityFoundationRequested).toBe(true); expect(existsSync(join(f.root, '.env'))).toBe(false); }); diff --git a/frontend/apps/web/src/test/migration-build.test.ts b/frontend/apps/web/src/test/migration-build.test.ts index 2600e5b89..f4bf9f8b1 100644 --- a/frontend/apps/web/src/test/migration-build.test.ts +++ b/frontend/apps/web/src/test/migration-build.test.ts @@ -1,6 +1,7 @@ // @vitest-environment node import { spawnSync } from 'node:child_process'; import { + chmodSync, existsSync, mkdirSync, mkdtempSync, @@ -8,6 +9,7 @@ import { readFileSync, realpathSync, rmSync, + symlinkSync, writeFileSync, } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -34,9 +36,11 @@ function migrationProjects(directory = join(repository, 'backend/src')): string[ const projects = migrationProjects().sort(); const tenancy = 'backend/src/Modules/Tenancy/LearnStack.Modules.Tenancy.Infrastructure'; const platform = 'backend/src/LearnStack.Infrastructure'; +const audit = 'backend/src/Modules/Audit/LearnStack.Modules.Audit.Infrastructure'; +const identity = 'backend/src/Modules/Identity/LearnStack.Modules.Identity.Infrastructure'; const extra = 'backend/src/Modules/Zeta/LearnStack.Modules.Zeta.Infrastructure'; const ordered = (chains: string[]) => - [...new Set([tenancy, platform, ...chains.slice().sort()])].filter((path) => + [...new Set([tenancy, platform, audit, identity, ...chains.slice().sort()])].filter((path) => chains.includes(path), ); @@ -55,6 +59,11 @@ function fixture(additional = false) { join(root, 'scripts/connection-string.awk'), readFileSync(join(repository, 'scripts/connection-string.awk')), ); + for (const name of ['migrate', 'compose', 'demo-database', 'development-realm-errors']) + writeFileSync( + join(root, `scripts/${name}.mjs`), + readFileSync(join(repository, `scripts/${name}.mjs`)), + ); // A previous artifact must never substitute for this invocation's fresh build. const stale = join(root, 'backend/src/LearnStack.Api/bin/Release/net10.0'); mkdirSync(stale, { recursive: true }); @@ -63,26 +72,27 @@ function fixture(additional = false) { writeFileSync(log, ''); writeFileSync( join(root, 'bin/dotnet'), - '#!/bin/sh\nexec "$MIGRATION_TEST_NODE" "$MIGRATION_TEST_STUB" "$@"\n', + `#!${process.execPath}\nrequire(${JSON.stringify(join(root, 'dotnet-stub.cjs'))});\n`, { mode: 0o700 }, ); const stub = join(root, 'dotnet-stub.cjs'); writeFileSync( stub, - `const { appendFileSync, existsSync, writeFileSync } = require('node:fs'); + `const { appendFileSync, existsSync, readFileSync, writeFileSync } = require('node:fs'); const { join } = require('node:path'); const args = process.argv.slice(2); -const stage = args[0] === 'tool' ? 'tool' : args[0] === 'build' ? 'build' : 'ef'; -appendFileSync(process.env.MIGRATION_TEST_LOG, JSON.stringify({ - args, cwd: process.cwd(), connection: process.env.ConnectionStrings__Migration, +const stage = args[0] === 'tool' ? 'tool' : args[0] === 'build' ? 'build' : args[0] === 'ef' ? 'ef' : 'installer'; +const behavior = JSON.parse(readFileSync(${JSON.stringify(join(root, 'behavior.json'))}, 'utf8')); +appendFileSync(${JSON.stringify(log)}, JSON.stringify({ + args, cwd: process.cwd(), connection: process.env.ConnectionStrings__Migration, environment: process.env, }) + '\\n'); -if (process.cwd() !== join(process.env.MIGRATION_TEST_ROOT, 'backend')) process.exit(91); -if (process.env.MIGRATION_TEST_FAIL === stage) process.exit(17); -const built = join(process.env.MIGRATION_TEST_ROOT, 'fresh-release'); +if (process.cwd() !== (stage === 'installer' ? ${JSON.stringify(root)} : ${JSON.stringify(join(root, 'backend'))})) process.exit(91); +if (behavior.MIGRATION_TEST_FAIL === stage) process.exit(17); +const built = ${JSON.stringify(join(root, 'fresh-release'))}; if (stage === 'build') writeFileSync(built, 'fresh'); if (stage === 'ef') { if (!existsSync(built)) process.exit(92); - if (args[args.indexOf('--project') + 1] === process.env.MIGRATION_TEST_FAIL_PROJECT) + if (args[args.indexOf('--project') + 1] === behavior.MIGRATION_TEST_FAIL_PROJECT) process.exit(18); } `, @@ -91,16 +101,13 @@ if (stage === 'ef') { root, chains, run(environment: Record = {}) { + writeFileSync(join(root, 'behavior.json'), JSON.stringify(environment)); const result = spawnSync('make', ['migrate', '.SHELLFLAGS=-c'], { cwd: root, env: { PATH: `${join(root, 'bin')}:${process.env.PATH}`, NODE_ENV: 'test', ConnectionStrings__Migration: 'Host=localhost;Username=learnstack_migration', - MIGRATION_TEST_NODE: process.execPath, - MIGRATION_TEST_STUB: stub, - MIGRATION_TEST_LOG: log, - MIGRATION_TEST_ROOT: root, ...environment, }, encoding: 'utf8', @@ -110,7 +117,15 @@ if (stage === 'ef') { const calls = readFileSync(log, 'utf8') .split('\n') .filter(Boolean) - .map((line) => JSON.parse(line) as { args: string[]; cwd: string; connection?: string }); + .map( + (line) => + JSON.parse(line) as { + args: string[]; + cwd: string; + connection?: string; + environment: Record; + }, + ); return { result, calls }; }, }; @@ -168,6 +183,207 @@ it('confines a selected-file migration credential to EF after credential-free re expect(result.stderr).not.toContain(connection); }); +const authority = { + Identity__AuthorityId: '019a1929-5450-7bbb-8df1-516e8e002501', + Authentication__Tenant__Issuer: 'https://identity.example/realms/learnstack', +}; +const migrationConnection = + 'Host=deployment.example;Username=learnstack_migration;Password=private-test-credential'; // leakwatch:ignore -- synthetic input; dotnet is a local stub +const environmentText = (values: Record) => + Object.entries(values) + .map(([key, value]) => `${key}='${value}'`) + .join('\n') + '\n'; + +it.each([ + 'Username=learnstack_app', + 'UID=learnstack_app', + 'User ID=learnstack_app', + 'Username=learnstack_migration', +])('refuses an ambiguous migration role before children (%s)', (duplicate) => { + const files = fixture(); + const connection = migrationConnection + ';' + duplicate; + const { result, calls } = files.run({ ConnectionStrings__Migration: connection, ...authority }); + expect(result.status).not.toBe(0); + expect(calls).toEqual([]); + expect(result.stdout + result.stderr).not.toContain(connection); + expect(result.stdout + result.stderr).not.toContain('private-test-credential'); +}); + +it('does not confuse a quoted password segment with a second role assignment', () => { + const files = fixture(); + const connection = + 'Host=deployment.example;Username=learnstack_migration;Password="fixture;UID=learnstack_app"'; // leakwatch:ignore -- synthetic input; dotnet is a local stub + const { result, calls } = files.run({ ConnectionStrings__Migration: connection, ...authority }); + expect(result.status, result.stderr).toBe(0); + expect(calls.at(-1)!.connection).toBe(connection); + expect(result.stdout + result.stderr).not.toContain(connection); +}); + +it.each(['ambient', 'file'] as const)( + 'installs one complete %s selection with confined child environments', + (source) => { + const files = fixture(); + const complete = { ConnectionStrings__Migration: migrationConnection, ...authority }; + writeFileSync( + join(files.root, '.env'), + environmentText( + source === 'file' + ? complete + : { + ConnectionStrings__Migration: 'Host=decoy;Username=learnstack_migration', + ...authority, + Authentication__Tenant__Issuer: 'http://localhost:8080/realms/learnstack', + }, + ), + { mode: 0o600 }, + ); + const { result, calls } = files.run({ + ...(source === 'ambient' ? complete : { ConnectionStrings__Migration: '' }), + KEYCLOAK_ADMIN_PASSWORD: 'private-keycloak-canary', + ConnectionStrings__Default: 'private-app-canary', + UNRELATED_PRIVATE_VALUE: 'private-unrelated-canary', + }); + expect(result.status, result.stderr).toBe(0); + expect(calls.filter((call) => call.args[0] === 'build').map((call) => call.args[1])).toEqual([ + 'src/LearnStack.Api', + 'src/LearnStack.Tools.IdentityAuthorityInstaller', + ]); + const installed = calls.at(-1)!; + expect(installed.args).toEqual([ + 'backend/src/LearnStack.Tools.IdentityAuthorityInstaller/bin/Release/net10.0/LearnStack.Tools.IdentityAuthorityInstaller.dll', + ]); + for (const call of calls) { + expect(call.environment.KEYCLOAK_ADMIN_PASSWORD).toBeUndefined(); + expect(call.environment.ConnectionStrings__Default).toBeUndefined(); + expect(call.environment.UNRELATED_PRIVATE_VALUE).toBeUndefined(); + expect(call.connection).toBe( + call.args[0] === 'ef' || call === installed ? migrationConnection : undefined, + ); + for (const [key, value] of Object.entries(authority)) + expect(call.environment[key]).toBe(call === installed ? value : undefined); + expect(call.args.join(' ')).not.toContain(migrationConnection); + } + expect(result.stdout + result.stderr).not.toContain('private-'); + }, +); + +it.each<{ name: string; ambient: Record; file: Record }>([ + { name: 'ambient connection with file pair', ambient: {}, file: authority }, + { name: 'explicitly empty ambient authority', ambient: { Identity__AuthorityId: '' }, file: {} }, + { + name: 'explicitly empty ambient issuer', + ambient: { Authentication__Tenant__Issuer: '' }, + file: {}, + }, + { + name: 'explicitly empty ambient pair', + ambient: { Identity__AuthorityId: '', Authentication__Tenant__Issuer: '' }, + file: {}, + }, + { + name: 'empty ambient authority with complete file selection', + ambient: { ConnectionStrings__Migration: '', Identity__AuthorityId: '' }, + file: { ConnectionStrings__Migration: migrationConnection, ...authority }, + }, + { + name: 'ambient authority with file issuer', + ambient: { Identity__AuthorityId: authority.Identity__AuthorityId }, + file: { Authentication__Tenant__Issuer: authority.Authentication__Tenant__Issuer }, + }, + { + name: 'ambient issuer with file authority', + ambient: { Authentication__Tenant__Issuer: authority.Authentication__Tenant__Issuer }, + file: { Identity__AuthorityId: authority.Identity__AuthorityId }, + }, + { + name: 'ambient pair with file connection', + ambient: { ConnectionStrings__Migration: '', ...authority }, + file: { ConnectionStrings__Migration: migrationConnection }, + }, + { + name: 'file authority without issuer', + ambient: { ConnectionStrings__Migration: '' }, + file: { + ConnectionStrings__Migration: migrationConnection, + Identity__AuthorityId: authority.Identity__AuthorityId, + }, + }, + { + name: 'file issuer without authority', + ambient: { ConnectionStrings__Migration: '' }, + file: { + ConnectionStrings__Migration: migrationConnection, + Authentication__Tenant__Issuer: authority.Authentication__Tenant__Issuer, + }, + }, +])('refuses $name before every dotnet child', ({ ambient, file }) => { + const files = fixture(); + writeFileSync(join(files.root, '.env'), environmentText(file), { mode: 0o600 }); + const { result, calls } = files.run(ambient); + expect(result.status).not.toBe(0); + expect(calls).toEqual([]); + expect(result.stdout + result.stderr).toContain('one source'); + expect(result.stdout + result.stderr).not.toContain(migrationConnection); +}); + +it.each(['invalid mode', 'symlink'])( + 'preserves private-file guidance for a selected file with %s before every dotnet child', + (kind) => { + const files = fixture(); + const source = join(files.root, 'private-source.env'); + const selected = join(files.root, 'selected.env'); + writeFileSync( + source, + environmentText({ ConnectionStrings__Migration: migrationConnection, ...authority }), + { mode: 0o600 }, + ); + if (kind === 'symlink') symlinkSync(source, selected); + else chmodSync(source, 0o644); + const { result, calls } = files.run({ + ConnectionStrings__Migration: '', + LEARNSTACK_COMPOSE_ENV_FILE: kind === 'symlink' ? selected : source, + }); + expect(result.status).not.toBe(0); + expect(calls).toEqual([]); + const output = result.stdout + result.stderr; + expect(output).toContain('realm: preflight/private_file'); + expect(output).toContain('regular, single-link file owned by the current user'); + expect(output).toContain('owner-only permissions; use chmod 600 on that file'); + for (const privateValue of [source, selected, migrationConnection, ...Object.values(authority)]) + expect(output).not.toContain(privateValue); + }, +); + +it.each([ + `Identity__AuthorityId=${authority.Identity__AuthorityId}\n`, + `export Identity__AuthorityId=${authority.Identity__AuthorityId}\n`, + ` Authentication__Tenant__Issuer=${authority.Authentication__Tenant__Issuer}\n`, +])( + 'refuses duplicate or aliased authority assignments without launching dotnet (%s)', + (extraLine) => { + const files = fixture(); + writeFileSync( + join(files.root, '.env'), + environmentText({ ConnectionStrings__Migration: migrationConnection, ...authority }) + + extraLine, + { mode: 0o600 }, + ); + const { result, calls } = files.run({ ConnectionStrings__Migration: '' }); + expect(result.status).not.toBe(0); + expect(calls).toEqual([]); + }, +); + +it('does not install authority after any migration chain fails', () => { + const files = fixture(); + const { result, calls } = files.run({ + ...authority, + MIGRATION_TEST_FAIL_PROJECT: '../' + tenancy, + }); + expect(result.status).not.toBe(0); + expect(calls.some((call) => call.args[0]?.endsWith('.dll'))).toBe(false); +}); + it.each(['tool', 'build'])( 'refuses %s failure before any EF operation despite an existing Release DLL and without shell errexit', (stage) => { diff --git a/infra/keycloak/README.md b/infra/keycloak/README.md index 5cb680e1b..6bafb9a43 100644 --- a/infra/keycloak/README.md +++ b/infra/keycloak/README.md @@ -249,9 +249,26 @@ hosted assignments and their evidence limits; merge remains separate. Current identity-visibility guards remain active. Do not remove them, wipe the database or silently normalize customized scopes by name. -Direct .NET Seeder remains an application-data tool; its identity manifest is a -read-only declaration. Both combined entries build its fresh Release DLL and -keep private realm credentials out of that child. +The argument-free .NET Seeder remains an application-data tool; its identity +manifest is a read-only declaration. Both combined entries build its fresh +Release DLL and keep private realm credentials out of that child. + +The [Identity foundation](../../docs/modules/identity/README.md#first-admin-and-seed-sequence) +adds a second owned child after final authenticated realm verification, while +the realm lock remains held. A private bounded stdin envelope carries only the +exact issuer and four declared actor/provider-subject pairs. The child separately +adopts bindings and applies finite Role/Membership/profile acts through their +ordinary app-role/audit owners. It must actually finish and dispose before the +lock is released. No Admin credential enters that child; the public reconciliation +result still reports mutation counts only. A completed rerun writes nothing; +conflicting or upgraded authority refuses without repair. + +Before either combined entry, set both `Identity__AuthorityId` and +`Authentication__Tenant__Issuer` in the selected private environment. The +[environment example](../../.env.example) gives an explicit local pair. Retain +the same stable ID and exact issuer across reruns; an installed conflicting +registration is never overwritten. Direct `make migrate` can still apply schema +only when both values are absent; combined identity seeding requires them. An older private environment must add `KEYCLOAK_WEB_CLIENT_SECRET` explicitly before either combined entry starts stack or database work. Do not wipe the diff --git a/scripts/ci-native-tests.py b/scripts/ci-native-tests.py index dca52f2d5..13bfe20e0 100644 --- a/scripts/ci-native-tests.py +++ b/scripts/ci-native-tests.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Closed ADR-0062/0063 execution owner. No command/path CLI overrides. +"""Closed ADR-0062/0063/0075 execution owner. No command/path CLI overrides. The delegated work cgroup is retained by a live supervisor sibling. RemainAfterExit alone does not retain an empty cgroup: systemd prunes it on SERVICE_EXITED. Only @@ -46,6 +46,7 @@ # Sole duration owner. These are bounded path allocations, not a hosted fit # claim. Qualification must measure setup, complete execution and failure tails. JOB_SECONDS = 20 * 60 +ORDINARY_JOB_SECONDS = 25 * 60 UPLOAD_SECONDS = 60 UNIT_STOP_SECONDS = 20 JOIN_SECONDS = 15 @@ -1077,12 +1078,25 @@ def remaining(deadline, cap=None): return min(value, cap) if cap is not None else value -def deadlines(): +def job_seconds(mode, job, counts): + # Expected identity selects the policy, never a receipt or a prefix match. + require(isinstance(mode, str) and mode in SHARD_JOBS, 'mode_refused') + require(job == SHARD_JOBS[mode], 'job_identity_mismatch') + require(isinstance(counts, dict), 'shard_index_invalid') + if mode not in ('base', 'native-shard'): + scope, _, index = mode.rpartition('-') + require(type(counts.get(scope)) is int and int(index) < counts[scope], 'shard_index_invalid') + return ORDINARY_JOB_SECONDS if job == 'backend-integration-tests' else JOB_SECONDS + + +def deadlines(mode): + seconds = job_seconds(mode, os.environ.get('GITHUB_JOB'), + shard_call(shard_owner().load_plan)['counts']) value = os.environ.get('LEARNSTACK_CI_STARTED_AT', '') require(re.fullmatch(r'[1-9][0-9]*', value), 'job_clock_missing') elapsed = time.time() - int(value) - require(0 <= elapsed < JOB_SECONDS, 'job_clock_invalid') - end = time.monotonic() + JOB_SECONDS - elapsed + require(0 <= elapsed < seconds, 'job_clock_invalid') + end = time.monotonic() + seconds - elapsed return end - RESERVE_SECONDS, end - UPLOAD_SECONDS - MARGIN_SECONDS @@ -2111,7 +2125,7 @@ def observe_vm_memory(): def leaf(mode): context = identity(mode) unit, private, output = locations(mode, context) - execution, cleanup = deadlines() + execution, cleanup = deadlines(mode) lower_core() base = '/system.slice/' + unit require(cgroup_path('self') == base + '/supervisor', 'leaf_requires_owned_unit') @@ -2522,7 +2536,7 @@ def workload_failure(private): def execute(mode): global CANCELLED context = identity(mode) - execution, cleanup = deadlines() + execution, cleanup = deadlines(mode) remaining(execution) lower_core() unit, private, output = locations(mode, context) diff --git a/scripts/ci-test-shard-results.py b/scripts/ci-test-shard-results.py index 577562826..4caf1735d 100644 --- a/scripts/ci-test-shard-results.py +++ b/scripts/ci-test-shard-results.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""ADR-0063 attempt-specific API evidence, source topology and result validation. +"""ADR-0063/0075 attempt-specific API evidence, topology and result validation. Only the two aggregate jobs receive a read-only Actions token. ZIPs are fetched by API artifact ID, hash-checked before bounded extraction into separate private @@ -62,16 +62,30 @@ def module(name, filename): Refusal, require = PLAN.Refusal, PLAN.require -def prepare_fixture_images(): +def producer_seconds(owner, plan): + expected = {'native' if mode == 'native-shard' else mode for mode in OWNER.SHARD_JOBS} + require(isinstance(owner, str) and owner in expected, 'producer_identity_invalid') + mode = 'native-shard' if owner == 'native' else owner + try: + return OWNER.job_seconds(mode, JOB_IDS[owner.split('-')[0]], plan['counts']) + except OWNER.Refusal as failure: + raise Refusal(failure.reason) from None + + +def prepare_fixture_images(mode): # Pull outside fixture startup, while charging every second to the same - # twenty-minute job. Never consume the execution owner's cleanup reserve. + # verified ordinary job. Never consume the owner's cleanup reserve. require(sys.platform == 'linux' and os.environ.get('GITHUB_ACTIONS') == 'true' and os.environ.get('RUNNER_ENVIRONMENT') == 'github-hosted' - and os.environ.get('GITHUB_JOB') == 'backend-integration-tests', 'fixture_setup_context_invalid') + and os.environ.get('GITHUB_JOB') == 'backend-integration-tests' + and isinstance(mode, str) + and OWNER.job_name(mode) == 'backend-integration-tests', 'fixture_setup_context_invalid') + OWNER.identity(mode) # Verify source/workflow/job/index before any image I/O. + seconds = producer_seconds(mode, PLAN.load_plan()) started = os.environ.get('LEARNSTACK_CI_STARTED_AT', '') require(re.fullmatch(r'[1-9][0-9]*', started), 'fixture_setup_clock_missing') elapsed = time.time() - int(started) - available = OWNER.JOB_SECONDS - OWNER.RESERVE_SECONDS - elapsed + available = seconds - OWNER.RESERVE_SECONDS - elapsed require(elapsed >= 0 and available > 0, 'fixture_setup_deadline_exhausted') beginning = time.monotonic() deadline = beginning + min(110, available) @@ -172,7 +186,9 @@ def workflow_topology(documents, plan): realm_node_gates(jobs['meta']) for scope, job_id in JOB_IDS.items(): job = jobs[job_id] - require(job.get('runs-on') == 'ubuntu-24.04' and job.get('timeout-minutes') == 20 + owner = scope + '-0' if scope in ('architecture', 'ordinary') else scope + require(job.get('runs-on') == 'ubuntu-24.04' + and job.get('timeout-minutes') == producer_seconds(owner, plan) // 60 and not any(key in job for key in ('if', 'permissions', 'continue-on-error', 'container', 'services')), 'execution_topology_invalid') if scope in ('architecture', 'ordinary'): @@ -198,8 +214,11 @@ def workflow_topology(documents, plan): and names.index(compile_name) < names.index(EXECUTE_STEP), 'fixture_compile_gate_invalid') prepare_name = 'Prepare pinned provider fixture images within the whole-job budget' prepare = [step for step in steps if step.get('name') == prepare_name] - require(len(prepare) == 1 and prepare[0].get('run') == 'python3 scripts/ci-test-shards.py prepare-fixtures' + require(len(prepare) == 1 and prepare[0].get('run') == + 'python3 scripts/ci-test-shards.py prepare-fixtures ordinary-${{ matrix.index }}' and prepare[0].get('timeout-minutes') == 2 and 'if' not in prepare[0] + and isinstance(prepare[0].get('env'), dict) and prepare[0]['env'] + and prepare[0]['env'] == steps[names.index(EXECUTE_STEP)].get('env') and names.index(prepare_name) < names.index(EXECUTE_STEP), 'fixture_image_gate_invalid') build, execute, upload = (steps[names.index(name)] for name in (BUILD_STEP, EXECUTE_STEP, UPLOAD_STEP)) mode = 'native-shard' if scope == 'native' else scope @@ -374,6 +393,7 @@ def verify_jobs(jobs, context, plan, scope, *, allow_pending=False): result, pending = {}, None for owner in owners: job = by_name[producer_name(owner)] + seconds = producer_seconds(owner, plan) completed = job.get('status') == 'completed' and job.get('conclusion') == 'success' waiting = allow_pending and pending_state(job) if not completed and not waiting: @@ -388,7 +408,7 @@ def verify_jobs(jobs, context, plan, scope, *, allow_pending=False): if completed: start, end = timestamp(job.get('started_at')), timestamp(job.get('completed_at')) require(created <= start, 'api_timestamp_invalid') - require(0 < end - start <= 20 * 60, 'producer_ceiling_exceeded') + require(0 < end - start <= seconds, 'producer_ceiling_exceeded') else: require('completed_at' in job and job['completed_at'] is None and 'started_at' in job, 'api_timestamp_invalid') @@ -499,8 +519,8 @@ def unpack_archive(raw, artifact, output): raise Refusal('artifact_zip_invalid') from None -def finite_seconds(value): - return type(value) in (int, float) and math.isfinite(value) and 0 <= value <= 1200 +def finite_seconds(value, ceiling): + return type(value) in (int, float) and math.isfinite(value) and 0 <= value <= ceiling def binary_identity(value, keys): @@ -520,12 +540,13 @@ def verify_receipt(output, context, owner, plan, assignment): and result.get('partition') == mode and result.get('job') == job_id and all(result.get(key) is True for key in ('success', 'complete', 'ownershipComplete', 'cleanupOwnershipComplete')) and result.get('error') is None and result.get('forcedCleanup') is False, 'execution_receipt_incomplete') + seconds = producer_seconds(owner, plan) docker = scope in ('ordinary', 'native') require(result.get('dockerAbsent') is (True if docker else None) and result.get('authority') == {'process': 'owned_systemd_cgroup', 'docker': docker, 'collector': owner == 'native'}, 'execution_authority_mismatch') - require(all(finite_seconds(result.get(key)) for key in ('preOwnerSeconds', 'setupSeconds', 'executionSeconds', 'cleanupSeconds')) - and sum(result[key] for key in ('preOwnerSeconds', 'setupSeconds', 'executionSeconds', 'cleanupSeconds')) < 1200, + require(all(finite_seconds(result.get(key), seconds) for key in ('preOwnerSeconds', 'setupSeconds', 'executionSeconds', 'cleanupSeconds')) + and sum(result[key] for key in ('preOwnerSeconds', 'setupSeconds', 'executionSeconds', 'cleanupSeconds')) < seconds, 'execution_intervals_invalid') require(positive(result.get('observedVmMemoryPeakBytes')) and positive(result.get('vmMemorySamples')), 'vm_resource_evidence_missing') @@ -581,7 +602,7 @@ def verify_receipt(output, context, owner, plan, assignment): binary_identity(measured.get('toolchain'), ('sdk', 'console', 'consoleSha256', 'consoleDepsSha256')) for key in ('toolchainObservationSeconds', 'nonTestGateSeconds', 'discoveryAndSelectionSeconds', 'resultExportAndValidationSeconds', 'workloadSeconds'): - require(finite_seconds(measured.get(key)), 'measurement_intervals_invalid') + require(finite_seconds(measured.get(key), seconds), 'measurement_intervals_invalid') require(measured.get('fixturesStarted') is None and measured.get('fixtureStartupSeconds') is None, 'fixture_observation_invalid') projects = measured.get('projects') @@ -591,8 +612,8 @@ def verify_receipt(output, context, owner, plan, assignment): for item in projects: assembly = item.get('assembly') require(item.get('cases') == len([case for case in selected if case['assembly'] == assembly]) - and positive(item['cases']) and finite_seconds(item.get('firstResultSeconds')) - and finite_seconds(item.get('testProcessSeconds')) + and positive(item['cases']) and finite_seconds(item.get('firstResultSeconds'), seconds) + and finite_seconds(item.get('testProcessSeconds'), seconds) and item['firstResultSeconds'] <= item['testProcessSeconds'] and item.get('failureLocations') == [], 'project_measurement_invalid') binary_identity(item.get('adapter'), ('assemblyVersion', 'sha256')) diff --git a/scripts/ci-test-shards-plan.json b/scripts/ci-test-shards-plan.json index 7279d1b0c..88a155356 100644 --- a/scripts/ci-test-shards-plan.json +++ b/scripts/ci-test-shards-plan.json @@ -168,6 +168,517 @@ "sourceSha": null, "runId": null, "note": "Three passing local causal-restart variants, including the additional genuine-handler post-write conflict/retry journey. Exact case durations summed per actual selector and scaled by the existing historical ordinary ratio 2.271245 (ceil ms); advisory only, not a wall bound. Immutable source is not embedded in the local TRX." + }, + "p031-hosted-architecture-0": { + "kind": "hosted_trx", + "artifactSha256": "6c923d6eb54664b3f0d7d889e6ea9eaa29f1b582f6173fefa9318524d3be3b0f", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Attempt 1; architecture-0; artifact ID 12628761734. Complete passing owner TRX. IDs bind actual discovery selectors. Sum case ms, ceil/min1. No failed/unfinished group reduction; advisory, excludes fixture/setup and gives no wall bound." + }, + "p031-hosted-architecture-1": { + "kind": "hosted_trx", + "artifactSha256": "26837faa8779817aab5f299d42c19b0d8cae668f6bdf2143ff3c4d3b303457dc", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Attempt 1; architecture-1; artifact ID 12628722134. Complete passing owner TRX. IDs bind actual discovery selectors. Sum case ms, ceil/min1. No failed/unfinished group reduction; advisory, excludes fixture/setup and gives no wall bound." + }, + "p031-hosted-architecture-4": { + "kind": "hosted_trx", + "artifactSha256": "a1f6c92a3e543c063a47079065765ab823d05ac9e5d84c67f2ddbe7c8abbbb0d", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Attempt 1; architecture-4; artifact ID 12628133684. Complete passing owner TRX. IDs bind actual discovery selectors. Sum case ms, ceil/min1. No failed/unfinished group reduction; advisory, excludes fixture/setup and gives no wall bound." + }, + "p031-hosted-architecture-2": { + "kind": "hosted_trx", + "artifactSha256": "65d25372f760ad6db06297752a90c5ee80e8f7aea962ddd69eef02172b0ccb68", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Attempt 1; architecture-2; artifact ID 12628433534. Complete passing owner TRX. IDs bind actual discovery selectors. Sum case ms, ceil/min1. No failed/unfinished group reduction; advisory, excludes fixture/setup and gives no wall bound." + }, + "p031-hosted-architecture-5": { + "kind": "hosted_trx", + "artifactSha256": "6733ccbeb3fddcfeca2c4d4283a94a39e32b91d9cecaed18cc64a9ee77d01363", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Attempt 1; architecture-5; artifact ID 12628931958. Complete passing owner TRX. IDs bind actual discovery selectors. Sum case ms, ceil/min1. No failed/unfinished group reduction; advisory, excludes fixture/setup and gives no wall bound." + }, + "p031-hosted-architecture-3": { + "kind": "hosted_trx", + "artifactSha256": "dd1213a26dbb87999c5545f71061f76dccc124e5950f44eec6dd237a240ffc02", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Attempt 1; architecture-3; artifact ID 12629085167. Complete passing owner TRX. IDs bind actual discovery selectors. Sum case ms, ceil/min1. No failed/unfinished group reduction; advisory, excludes fixture/setup and gives no wall bound." + }, + "p031-hosted-ordinary-1": { + "kind": "hosted_trx", + "artifactSha256": "3f5b2ccc2342663a2d91fc7fdbdaa6ad71a2e7f57ecc175d1d313f3edb730b47", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Attempt 1; ordinary-1; artifact ID 12629017851. Complete passing owner TRX. IDs bind actual discovery selectors. Sum case ms, ceil/min1. No failed/unfinished group reduction; advisory, excludes fixture/setup and gives no wall bound." + }, + "p031-hosted-ordinary-8": { + "kind": "hosted_trx", + "artifactSha256": "ade39dd7df27cacff5d695a5884eab985bbf03ba2865040492f92797b875a16d", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Attempt 1; ordinary-8; artifact ID 12628007561. Complete passing owner TRX. IDs bind actual discovery selectors. Sum case ms, ceil/min1. No failed/unfinished group reduction; advisory, excludes fixture/setup and gives no wall bound." + }, + "p031-hosted-ordinary-10": { + "kind": "hosted_trx", + "artifactSha256": "d406d9eb07f741bf8e7fac412179aea37a22a6c29c836a643528f8de0626fa06", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Attempt 1; ordinary-10; artifact ID 12628957147. Complete passing owner TRX. IDs bind actual discovery selectors. Sum case ms, ceil/min1. No failed/unfinished group reduction; advisory, excludes fixture/setup and gives no wall bound." + }, + "p031-hosted-ordinary-11": { + "kind": "hosted_trx", + "artifactSha256": "e676334117064f0fca31a26bafc3df2b006eca48ef5ba72fe61426f8f1572ce0", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Attempt 1; ordinary-11; artifact ID 12628674843. Complete passing owner TRX. IDs bind actual discovery selectors. Sum case ms, ceil/min1. No failed/unfinished group reduction; advisory, excludes fixture/setup and gives no wall bound." + }, + "p031-hosted-ordinary-7": { + "kind": "hosted_trx", + "artifactSha256": "080d1cc57fd1c23f872b9bd5499c954d7c57687e7ee3a4f2407cc9ed1a082682", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Attempt 1; ordinary-7; artifact ID 12628697404. Complete passing owner TRX. IDs bind actual discovery selectors. Sum case ms, ceil/min1. No failed/unfinished group reduction; advisory, excludes fixture/setup and gives no wall bound." + }, + "p031-hosted-ordinary-3": { + "kind": "hosted_trx", + "artifactSha256": "b998043ac9bc85b53d08720e258e7f6cb0c8e13b21d57cc21bd4b2038cde1396", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Attempt 1; ordinary-3; artifact ID 12628189045. Complete passing owner TRX. IDs bind actual discovery selectors. Sum case ms, ceil/min1. No failed/unfinished group reduction; advisory, excludes fixture/setup and gives no wall bound." + }, + "p031-hosted-ordinary-6": { + "kind": "hosted_console", + "artifactSha256": "6744c7ccf7d6b5b1b5b21a57c5475a71af3b78d7cdaf10b47cd52db33deca8be", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Attempt 1; ordinary-6; artifact ID 12629027797. Interrupted owner exact JSONL prefix; complete all-Passed selector groups only. IDs bind actual discovery selectors. Sum case ms, ceil/min1. No failed/unfinished group reduction; advisory, excludes fixture/setup and gives no wall bound." + }, + "p031-hosted-ordinary-5": { + "kind": "hosted_trx", + "artifactSha256": "810f97e389e284c0d2a9c590454a13317300d0bdac741bfcb5fff9f8dd56555c", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Attempt 1; ordinary-5; artifact ID 12628422538. Complete passing owner TRX. IDs bind actual discovery selectors. Sum case ms, ceil/min1. No failed/unfinished group reduction; advisory, excludes fixture/setup and gives no wall bound." + }, + "p031-hosted-ordinary-2": { + "kind": "hosted_trx", + "artifactSha256": "4e8c0ef2a4a4b82607c39540c3692e41b4c7b4d4c0725e17fe274958aac5a83c", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Attempt 1; ordinary-2; artifact ID 12628257751. Complete passing owner TRX. IDs bind actual discovery selectors. Sum case ms, ceil/min1. No failed/unfinished group reduction; advisory, excludes fixture/setup and gives no wall bound." + }, + "p031-hosted-ordinary-0": { + "kind": "hosted_trx", + "artifactSha256": "79118f29f3dd1f8aa86dcc4c1fcc8aefea14cd330634236a4526d23880eb02c1", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Attempt 1; ordinary-0; artifact ID 12628103725. Complete passing owner TRX. IDs bind actual discovery selectors. Sum case ms, ceil/min1. No failed/unfinished group reduction; advisory, excludes fixture/setup and gives no wall bound." + }, + "p031-hosted-ordinary-4": { + "kind": "hosted_trx", + "artifactSha256": "7a805d6c4f5c0f06048fc3fc4134e60f5feef9d39a0cbb9d4c5facf73acf801a", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Attempt 1; ordinary-4; artifact ID 12628883881. Complete passing owner TRX. IDs bind actual discovery selectors. Sum case ms, ceil/min1. No failed/unfinished group reduction; advisory, excludes fixture/setup and gives no wall bound." + }, + "p031-hosted-ordinary-9": { + "kind": "hosted_console", + "artifactSha256": "c7771c4ccf4944d73bd8e83a7164a59aab07c47297721dd3c70ca525e0712bd8", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Attempt 1; ordinary-9; artifact ID 12628692608. Interrupted owner exact JSONL prefix; complete all-Passed selector groups only. IDs bind actual discovery selectors. Sum case ms, ceil/min1. No failed/unfinished group reduction; advisory, excludes fixture/setup and gives no wall bound." + }, + "pr38-a-ordinary-0": { + "kind": "hosted_trx", + "artifactSha256": "0b7776e02beaa6a740bde18ef1e2a1beac6d231d0f5b45fc7cfd5b4288afe0e6", + "sourceSha": "5e02e3cc26da696aaed43d7557127b8ca8164a9c", + "runId": "40318359878", + "note": "Complete passing A TRX, attempt 1, ordinary-0, artifact ID 12648163006, head c14ec6a78891591b52c0156b97197f9e29cfee7b, merge 5e02e3cc26da696aaed43d7557127b8ca8164a9c. Exact selector case-duration sum in ceil milliseconds, minimum 1; advisory, not a wall bound." + }, + "pr38-a-ordinary-1": { + "kind": "hosted_trx", + "artifactSha256": "dfa89757d8eeab01619c8538a8db0fe95cc70661c2d93d5b842c1c08bbbcc8c5", + "sourceSha": "5e02e3cc26da696aaed43d7557127b8ca8164a9c", + "runId": "40318359878", + "note": "Complete passing A TRX, attempt 1, ordinary-1, artifact ID 12648317031, head c14ec6a78891591b52c0156b97197f9e29cfee7b, merge 5e02e3cc26da696aaed43d7557127b8ca8164a9c. Exact selector case-duration sum in ceil milliseconds, minimum 1; advisory, not a wall bound." + }, + "pr38-a-ordinary-10": { + "kind": "hosted_trx", + "artifactSha256": "d6108a68815c7bec8f6f642998753673146fbce91cf13150725be77978cf4815", + "sourceSha": "5e02e3cc26da696aaed43d7557127b8ca8164a9c", + "runId": "40318359878", + "note": "Complete passing A TRX, attempt 1, ordinary-10, artifact ID 12648073211, head c14ec6a78891591b52c0156b97197f9e29cfee7b, merge 5e02e3cc26da696aaed43d7557127b8ca8164a9c. Exact selector case-duration sum in ceil milliseconds, minimum 1; advisory, not a wall bound." + }, + "pr38-a-ordinary-11": { + "kind": "hosted_trx", + "artifactSha256": "713976c7d837820e0812b0e1852cb22447dc62b724d297f3aafb3882a8c3c762", + "sourceSha": "5e02e3cc26da696aaed43d7557127b8ca8164a9c", + "runId": "40318359878", + "note": "Complete passing A TRX, attempt 1, ordinary-11, artifact ID 12648422552, head c14ec6a78891591b52c0156b97197f9e29cfee7b, merge 5e02e3cc26da696aaed43d7557127b8ca8164a9c. Exact selector case-duration sum in ceil milliseconds, minimum 1; advisory, not a wall bound." + }, + "pr38-a-ordinary-3": { + "kind": "hosted_trx", + "artifactSha256": "e26d9587beaab36041a1734d6a6992871c33dae8877dc4d3d2704c3be9331602", + "sourceSha": "5e02e3cc26da696aaed43d7557127b8ca8164a9c", + "runId": "40318359878", + "note": "Complete passing A TRX, attempt 1, ordinary-3, artifact ID 12648717944, head c14ec6a78891591b52c0156b97197f9e29cfee7b, merge 5e02e3cc26da696aaed43d7557127b8ca8164a9c. Exact selector case-duration sum in ceil milliseconds, minimum 1; advisory, not a wall bound." + }, + "pr38-a-ordinary-4": { + "kind": "hosted_trx", + "artifactSha256": "0f4e8bfa19e34a1a5254739365daf95f50e7efca1f5822ee6395bebd3083f32e", + "sourceSha": "5e02e3cc26da696aaed43d7557127b8ca8164a9c", + "runId": "40318359878", + "note": "Complete passing A TRX, attempt 1, ordinary-4, artifact ID 12648627438, head c14ec6a78891591b52c0156b97197f9e29cfee7b, merge 5e02e3cc26da696aaed43d7557127b8ca8164a9c. Exact selector case-duration sum in ceil milliseconds, minimum 1; advisory, not a wall bound." + }, + "pr38-a-ordinary-7": { + "kind": "hosted_trx", + "artifactSha256": "848ed3fcd2469cfa2ded4199afe0898f1c78cea68f91f1f566d63978dd35fff1", + "sourceSha": "5e02e3cc26da696aaed43d7557127b8ca8164a9c", + "runId": "40318359878", + "note": "Complete passing A TRX, attempt 1, ordinary-7, artifact ID 12648149044, head c14ec6a78891591b52c0156b97197f9e29cfee7b, merge 5e02e3cc26da696aaed43d7557127b8ca8164a9c. Exact selector case-duration sum in ceil milliseconds, minimum 1; advisory, not a wall bound." + }, + "pr38-a-ordinary-8": { + "kind": "hosted_trx", + "artifactSha256": "06360b250cc4468d4432f0435e88c7381a81126cd939faa86a95836209585769", + "sourceSha": "5e02e3cc26da696aaed43d7557127b8ca8164a9c", + "runId": "40318359878", + "note": "Complete passing A TRX, attempt 1, ordinary-8, artifact ID 12648961775, head c14ec6a78891591b52c0156b97197f9e29cfee7b, merge 5e02e3cc26da696aaed43d7557127b8ca8164a9c. Exact selector case-duration sum in ceil milliseconds, minimum 1; advisory, not a wall bound." + }, + "pr38-b-ordinary-0": { + "kind": "hosted_trx", + "artifactSha256": "23aeeab46cb657de67cac128a4287fc1279ee70896f4359bc4f8b3694804444e", + "sourceSha": "5e02e3cc26da696aaed43d7557127b8ca8164a9c", + "runId": "40318359878", + "note": "Attempt 2, ordinary-0, artifact ID 12648909903, head c14ec6a78891591b52c0156b97197f9e29cfee7b, merge 5e02e3cc26da696aaed43d7557127b8ca8164a9c. Complete passing original TRX; ceil summed case ms/minimum 1; advisory, not a wall bound." + }, + "pr38-b-ordinary-1": { + "kind": "hosted_trx", + "artifactSha256": "fec5fa78065ffdc395abeb2a36d27f8efd8023006650e380a9472a9c7694c86f", + "sourceSha": "5e02e3cc26da696aaed43d7557127b8ca8164a9c", + "runId": "40318359878", + "note": "Attempt 2, ordinary-1, artifact ID 12649710644, head c14ec6a78891591b52c0156b97197f9e29cfee7b, merge 5e02e3cc26da696aaed43d7557127b8ca8164a9c. Complete passing original TRX; ceil summed case ms/minimum 1; advisory, not a wall bound." + }, + "pr38-b-ordinary-10": { + "kind": "hosted_trx", + "artifactSha256": "150a193f0437c11be1b92e28d9d5c105283168f84ebd4ec31568d042066bcfc2", + "sourceSha": "5e02e3cc26da696aaed43d7557127b8ca8164a9c", + "runId": "40318359878", + "note": "Attempt 2, ordinary-10, artifact ID 12649402118, head c14ec6a78891591b52c0156b97197f9e29cfee7b, merge 5e02e3cc26da696aaed43d7557127b8ca8164a9c. Complete passing original TRX; ceil summed case ms/minimum 1; advisory, not a wall bound." + }, + "pr38-b-ordinary-2": { + "kind": "hosted_trx", + "artifactSha256": "17e9c12e832faab0bdd55dcf84dd4ef76759c7756353db93c642500d18fd615f", + "sourceSha": "5e02e3cc26da696aaed43d7557127b8ca8164a9c", + "runId": "40318359878", + "note": "Attempt 2, ordinary-2, artifact ID 12650566478, head c14ec6a78891591b52c0156b97197f9e29cfee7b, merge 5e02e3cc26da696aaed43d7557127b8ca8164a9c. Complete passing original TRX; ceil summed case ms/minimum 1; advisory, not a wall bound." + }, + "pr38-b-ordinary-5": { + "kind": "hosted_trx", + "artifactSha256": "6342d74f1ffaa5c5e1c5a88e6f36ababa3133d288c4fe2f8c1f142954274d52c", + "sourceSha": "5e02e3cc26da696aaed43d7557127b8ca8164a9c", + "runId": "40318359878", + "note": "Attempt 2, ordinary-5, artifact ID 12649254130, head c14ec6a78891591b52c0156b97197f9e29cfee7b, merge 5e02e3cc26da696aaed43d7557127b8ca8164a9c. Complete passing original TRX; ceil summed case ms/minimum 1; advisory, not a wall bound." + }, + "pr38-b-ordinary-7": { + "kind": "hosted_console", + "artifactSha256": "de7a7a5ca42db46ad7c1fae567c64d98cd2f6c6fc11d140560491408ac944202", + "sourceSha": "5e02e3cc26da696aaed43d7557127b8ca8164a9c", + "runId": "40318359878", + "note": "Attempt 2, ordinary-7, artifact ID 12648684971, head c14ec6a78891591b52c0156b97197f9e29cfee7b, merge 5e02e3cc26da696aaed43d7557127b8ca8164a9c. Interrupted original JSONL prefix, only complete all-Passed selector groups; ceil summed case ms/minimum 1; advisory, not a wall bound." + }, + "pr38-b-ordinary-8": { + "kind": "hosted_trx", + "artifactSha256": "ca989b6ee3f7f0c24a6e7067ecc0ae934581b70380188fe0bb3581ff5e5f4ae9", + "sourceSha": "5e02e3cc26da696aaed43d7557127b8ca8164a9c", + "runId": "40318359878", + "note": "Attempt 2, ordinary-8, artifact ID 12649532186, head c14ec6a78891591b52c0156b97197f9e29cfee7b, merge 5e02e3cc26da696aaed43d7557127b8ca8164a9c. Complete passing original TRX; ceil summed case ms/minimum 1; advisory, not a wall bound." + }, + "pr38-df-1-architecture-1": { + "kind": "hosted_trx", + "artifactSha256": "810581e38845581eb1b96afd5551b3da6a3d136af5443cfa7f6582ee50096e69", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Attempt 1, architecture-1, artifact ID 12653685003, head dfdf9cab92ab94ed7b882553c8828f1337bac9d4, merge d6a794cd41ddefbffac5fb9f9195ded465d0c358; complete passing original TRX; ceil summed case ms/minimum 1; advisory, not wall time." + }, + "pr38-df-1-architecture-2": { + "kind": "hosted_trx", + "artifactSha256": "97893f76633c41b6046d90bf2ec35c3bbc02d6249b28fd849d916f7e7f5dcdb5", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Attempt 1, architecture-2, artifact ID 12652606232, head dfdf9cab92ab94ed7b882553c8828f1337bac9d4, merge d6a794cd41ddefbffac5fb9f9195ded465d0c358; complete passing original TRX; ceil summed case ms/minimum 1; advisory, not wall time." + }, + "pr38-df-1-architecture-3": { + "kind": "hosted_trx", + "artifactSha256": "113518ba341dcd597c26a6ed8ba6c8215a58b5107981a8869f582681f15532b6", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Attempt 1, architecture-3, artifact ID 12652816720, head dfdf9cab92ab94ed7b882553c8828f1337bac9d4, merge d6a794cd41ddefbffac5fb9f9195ded465d0c358; complete passing original TRX; ceil summed case ms/minimum 1; advisory, not wall time." + }, + "pr38-df-1-architecture-4": { + "kind": "hosted_trx", + "artifactSha256": "77251e81bee71b3c63337be660df235e93de35421616b083ebf11fd35ba732b4", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Attempt 1, architecture-4, artifact ID 12653460765, head dfdf9cab92ab94ed7b882553c8828f1337bac9d4, merge d6a794cd41ddefbffac5fb9f9195ded465d0c358; complete passing original TRX; ceil summed case ms/minimum 1; advisory, not wall time." + }, + "pr38-df-1-architecture-5": { + "kind": "hosted_trx", + "artifactSha256": "d5e63d905231142da8b8e614bfb8ed285508a81235e0924d957f72840c604a1e", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Attempt 1, architecture-5, artifact ID 12653630018, head dfdf9cab92ab94ed7b882553c8828f1337bac9d4, merge d6a794cd41ddefbffac5fb9f9195ded465d0c358; complete passing original TRX; ceil summed case ms/minimum 1; advisory, not wall time." + }, + "pr38-df-1-ordinary-0": { + "kind": "hosted_trx", + "artifactSha256": "93ee7a30c7c4cdd8ff3922b1b3ea5ef6a27afc50385275078824df64ec55fcf8", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Attempt 1, ordinary-0, artifact ID 12652825643, head dfdf9cab92ab94ed7b882553c8828f1337bac9d4, merge d6a794cd41ddefbffac5fb9f9195ded465d0c358; complete passing original TRX; ceil summed case ms/minimum 1; advisory, not wall time." + }, + "pr38-df-1-ordinary-10": { + "kind": "hosted_trx", + "artifactSha256": "94008ecc6d8565a79f4ad6023e1b2de981772eddb301af2ff1a5ecab7d46dca4", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Attempt 1, ordinary-10, artifact ID 12655025643, head dfdf9cab92ab94ed7b882553c8828f1337bac9d4, merge d6a794cd41ddefbffac5fb9f9195ded465d0c358; complete passing original TRX; ceil summed case ms/minimum 1; advisory, not wall time." + }, + "pr38-df-1-ordinary-11": { + "kind": "hosted_trx", + "artifactSha256": "1afdc9d7a0e97ba5a0ca132d3100e045503994b132ed57d8ecae9bfcb5640475", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Attempt 1, ordinary-11, artifact ID 12653396243, head dfdf9cab92ab94ed7b882553c8828f1337bac9d4, merge d6a794cd41ddefbffac5fb9f9195ded465d0c358; complete passing original TRX; ceil summed case ms/minimum 1; advisory, not wall time." + }, + "pr38-df-1-ordinary-4": { + "kind": "hosted_trx", + "artifactSha256": "1a6c40876afc25eca903fade8ac1958f06884c8dda0f435bbb2712c9effa69f3", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Attempt 1, ordinary-4, artifact ID 12655210098, head dfdf9cab92ab94ed7b882553c8828f1337bac9d4, merge d6a794cd41ddefbffac5fb9f9195ded465d0c358; complete passing original TRX; ceil summed case ms/minimum 1; advisory, not wall time." + }, + "pr38-df-1-ordinary-6": { + "kind": "hosted_trx", + "artifactSha256": "a110991fc8936203d2eab59eb96933d02cba71ef5b99a433400efbb08ef7a29d", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Attempt 1, ordinary-6, artifact ID 12652851829, head dfdf9cab92ab94ed7b882553c8828f1337bac9d4, merge d6a794cd41ddefbffac5fb9f9195ded465d0c358; complete passing original TRX; ceil summed case ms/minimum 1; advisory, not wall time." + }, + "pr38-df-1-ordinary-7": { + "kind": "hosted_trx", + "artifactSha256": "8d4622f7be166644fcd1e381b9039c935eb8f4ae045dbfc8c523107ed636665c", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Attempt 1, ordinary-7, artifact ID 12653571034, head dfdf9cab92ab94ed7b882553c8828f1337bac9d4, merge d6a794cd41ddefbffac5fb9f9195ded465d0c358; complete passing original TRX; ceil summed case ms/minimum 1; advisory, not wall time." + }, + "pr38-df-1-ordinary-8": { + "kind": "hosted_trx", + "artifactSha256": "c9329ff6e95ca27b7420446545b982f4d122de22310d579cb8970ad9c8aeb2f8", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Attempt 1, ordinary-8, artifact ID 12652516461, head dfdf9cab92ab94ed7b882553c8828f1337bac9d4, merge d6a794cd41ddefbffac5fb9f9195ded465d0c358; complete passing original TRX; ceil summed case ms/minimum 1; advisory, not wall time." + }, + "pr38-df-2-architecture-1": { + "kind": "hosted_trx", + "artifactSha256": "d0f7f75b02851e9ad2375a575053925d9601ccbe11aef33d919d3996989c8457", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Attempt 2, architecture-1, artifact ID 12653084289, head dfdf9cab92ab94ed7b882553c8828f1337bac9d4, merge d6a794cd41ddefbffac5fb9f9195ded465d0c358; complete passing original TRX; ceil summed case ms/minimum 1; advisory, not wall time." + }, + "pr38-df-2-architecture-3": { + "kind": "hosted_trx", + "artifactSha256": "46d6ade56095884f79b05d6371224332c54be1c3db92825149553cc025c1cc8e", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Attempt 2, architecture-3, artifact ID 12655345633, head dfdf9cab92ab94ed7b882553c8828f1337bac9d4, merge d6a794cd41ddefbffac5fb9f9195ded465d0c358; complete passing original TRX; ceil summed case ms/minimum 1; advisory, not wall time." + }, + "pr38-df-2-architecture-5": { + "kind": "hosted_trx", + "artifactSha256": "62975572f9d8aaa8ba479063ccc7b4cbea759b547edaf6c963043c9e92fec99b", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Attempt 2, architecture-5, artifact ID 12653768947, head dfdf9cab92ab94ed7b882553c8828f1337bac9d4, merge d6a794cd41ddefbffac5fb9f9195ded465d0c358; complete passing original TRX; ceil summed case ms/minimum 1; advisory, not wall time." + }, + "pr38-df-2-ordinary-0": { + "kind": "hosted_console", + "artifactSha256": "818a8a5a8a659fb698896be2bdf03bff3413045eb433e2337cde35a266712a11", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Attempt 2, ordinary-0, artifact ID 12654553778, head dfdf9cab92ab94ed7b882553c8828f1337bac9d4, merge d6a794cd41ddefbffac5fb9f9195ded465d0c358; original interrupted JSONL prefix, full all-Passed groups only; ceil summed case ms/minimum 1; advisory, not wall time." + }, + "pr38-df-2-ordinary-1": { + "kind": "hosted_trx", + "artifactSha256": "a5ddf6ae4cdf577399e7f294db3046ef511eeebf742ab950d0a11f76ee2215ec", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Attempt 2, ordinary-1, artifact ID 12654288868, head dfdf9cab92ab94ed7b882553c8828f1337bac9d4, merge d6a794cd41ddefbffac5fb9f9195ded465d0c358; complete passing original TRX; ceil summed case ms/minimum 1; advisory, not wall time." + }, + "pr38-df-2-ordinary-10": { + "kind": "hosted_trx", + "artifactSha256": "7e8d78925b5ced3ea3446b3da9b69e11e6426fcf4ee9d778f0772d38df9c9ec8", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Attempt 2, ordinary-10, artifact ID 12654873440, head dfdf9cab92ab94ed7b882553c8828f1337bac9d4, merge d6a794cd41ddefbffac5fb9f9195ded465d0c358; complete passing original TRX; ceil summed case ms/minimum 1; advisory, not wall time." + }, + "pr38-df-2-ordinary-5": { + "kind": "hosted_trx", + "artifactSha256": "2d131fcb0125e26e6df3382230ed586980dcc8f7375a6f40523cfebeb0e295ad", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Attempt 2, ordinary-5, artifact ID 12654363345, head dfdf9cab92ab94ed7b882553c8828f1337bac9d4, merge d6a794cd41ddefbffac5fb9f9195ded465d0c358; complete passing original TRX; ceil summed case ms/minimum 1; advisory, not wall time." + }, + "pr38-df-2-ordinary-8": { + "kind": "hosted_trx", + "artifactSha256": "c7fbd6f616af4674de0cf0ce3e1a694d2d60b5791fbf56191200aeb785beb176", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Attempt 2, ordinary-8, artifact ID 12655268010, head dfdf9cab92ab94ed7b882553c8828f1337bac9d4, merge d6a794cd41ddefbffac5fb9f9195ded465d0c358; complete passing original TRX; ceil summed case ms/minimum 1; advisory, not wall time." + }, + "pr38-df-2-ordinary-9": { + "kind": "hosted_trx", + "artifactSha256": "8e0e6870ca10e4c3e0f8408261ae68d74be5a9d769c7706fec3fe184a089a2cf", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Attempt 2, ordinary-9, artifact ID 12653204628, head dfdf9cab92ab94ed7b882553c8828f1337bac9d4, merge d6a794cd41ddefbffac5fb9f9195ded465d0c358; complete passing original TRX; ceil summed case ms/minimum 1; advisory, not wall time." + }, + "pr38-class-alias-job-owner": { + "kind": "hosted_trx", + "artifactSha256": "c183ef8d7fc84a8e55c417b2c2e370c32a7688f7bbae49eb0d69fee16439f3d4", + "sourceSha": "d84ac3009f8ba84a339d91e023f7f6f5f9269cc0", + "runId": "39417319998", + "note": "Alias JobExecutionMutationTests->JobOwnerMutationTests, method Background_job_owner_census_detects_actual_removals_extra_subtypes_async_calls_and_delegates; unchanged Fact body SHA256 a18d18ee4893a501c4745978df1b24952e01bf24d6e443364c5c096132f10e37; inherits hosted-architecture-39417319998-2-1. Advisory scalar; new name not executed." + }, + "pr38-class-alias-job-orchestration": { + "kind": "hosted_trx", + "artifactSha256": "62975572f9d8aaa8ba479063ccc7b4cbea759b547edaf6c963043c9e92fec99b", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Alias JobExecutionMutationTests->JobOrchestrationMutationTests, method External_job_orchestration_rejects_missing_seams_helpers_delegates_signatures_and_resource_carriers; unchanged Fact body SHA256 1f8352511ad2141801da6a1c4f8d0885550b70b703d42df8e28f176bf0d1f8d1; inherits pr38-df-2-architecture-5. Advisory scalar; new name not executed." + }, + "pr38-class-alias-job-capacity": { + "kind": "hosted_trx", + "artifactSha256": "97893f76633c41b6046d90bf2ec35c3bbc02d6249b28fd849d916f7e7f5dcdb5", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Alias JobLifecycleMutationTests->JobCapacityMutationTests, method Background_job_capacity_census_rejects_forged_cleanup_recovery_and_checkpoint_owners; unchanged Fact body SHA256 0b07c37090e62af54d3b06ebc04473e74726b42da30b7dad16b00f45c4570527; inherits pr38-df-1-architecture-2. Advisory scalar; new name not executed." + }, + "pr38-class-alias-job-recipient": { + "kind": "hosted_trx", + "artifactSha256": "dd1213a26dbb87999c5545f71061f76dccc124e5950f44eec6dd237a240ffc02", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Alias JobLifecycleMutationTests->JobRecipientMutationTests, method Background_job_recipient_census_detects_extra_authority_and_missing_real_fences; unchanged Fact body SHA256 3f0a97d5d175979b66f2361d96b9223260c4402afeea8809c32ed6826d1ff5f6; inherits p031-hosted-architecture-3. Advisory scalar; new name not executed." + }, + "pr38-class-alias-hangfire-runtime": { + "kind": "hosted_trx", + "artifactSha256": "c183ef8d7fc84a8e55c417b2c2e370c32a7688f7bbae49eb0d69fee16439f3d4", + "sourceSha": "d84ac3009f8ba84a339d91e023f7f6f5f9269cc0", + "runId": "39417319998", + "note": "Alias JobLifecycleMutationTests->HangfireRuntimeMutationTests, method Hangfire_runtime_census_rejects_fatal_and_constructor_escapes; unchanged Fact body SHA256 748270afbda097f752e5c5dd32387bc4581eea0a74d544ddfc61d298297fa642; inherits hosted-architecture-39417319998-2-1. Advisory scalar; new name not executed." + }, + "pr38-class-alias-job-recurrence": { + "kind": "hosted_trx", + "artifactSha256": "6733ccbeb3fddcfeca2c4d4283a94a39e32b91d9cecaed18cc64a9ee77d01363", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Alias OutboxDispatchConventionTests->JobRecurrenceMutationTests, method Background_job_recurrence_runtime_controls_reject_changed_authority_and_cleanup; unchanged dedented Theory body SHA256 975ccdf103cc9626c2aeb68d8e064aa91cc6d26c1613104e953dafc3c7fe246c; inherits p031-hosted-architecture-5. Advisory scalar; new selector not executed hosted." + }, + "pr38-class-alias-resolution": { + "kind": "hosted_trx", + "artifactSha256": "113518ba341dcd597c26a6ed8ba6c8215a58b5107981a8869f582681f15532b6", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Alias OutboxDispatchConventionTests->ResolutionMutationTests, method Resolution_walk_detects_loading_construction_async_and_polymorphic_helpers; unchanged dedented Fact body SHA256 16a75e50ea90608d73b2b640588e06c5b8c9f8b40d5a5ab6058acd4da3949bc5; inherits pr38-df-1-architecture-3. Advisory scalar; new selector not executed hosted." + }, + "pr38-class-alias-cleanup-owner-1067e9c3": { + "kind": "hosted_trx", + "artifactSha256": "62975572f9d8aaa8ba479063ccc7b4cbea759b547edaf6c963043c9e92fec99b", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Alias OutboxDispatchConventionTests->CleanupOwnerMutationTests, method Cleanup_owner_census_rejects_extra_acquisition_disposal_capture_and_observation_paths; unchanged dedented Fact body SHA256 74043e6354b36489a5f5e16686d445660ca4cbf1bf725b7711a03a9603518e23; inherits pr38-df-2-architecture-5. Advisory scalar; new selector not executed hosted." + }, + "pr38-class-alias-delivery-lifecycle-4abc441d": { + "kind": "hosted_trx", + "artifactSha256": "62975572f9d8aaa8ba479063ccc7b4cbea759b547edaf6c963043c9e92fec99b", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Alias OutboxDispatchConventionTests->DeliveryLifecycleMutationTests, method Integration_delivery_lifecycle_census_rejects_typed_helper_async_delegate_and_missing_paths; unchanged dedented Fact body SHA256 aadc5f058bab1e61d4c0b8c32ba7e42fe170d6dd3191ac472d34b5ec9596e772; inherits pr38-df-2-architecture-5. Advisory scalar; new selector not executed hosted." + }, + "pr38-class-alias-bridge-credential-8d40b87a": { + "kind": "hosted_trx", + "artifactSha256": "26837faa8779817aab5f299d42c19b0d8cae668f6bdf2143ff3c4d3b303457dc", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Alias OutboxDispatchConventionTests->BridgeCredentialMutationTests, method Bridge_credential_census_rejects_extra_acquisition_forwarding_and_store_consumers; unchanged dedented Fact body SHA256 38cfb6cc97de0f4e724ee623df6e9a6ec9092bea5fc2e6a890280dee733d6c9c; inherits p031-hosted-architecture-1. Advisory scalar; new selector not executed hosted." + }, + "pr38-class-alias-bridge-credential-c6cb9e31": { + "kind": "hosted_trx", + "artifactSha256": "59d80797f359ad0aec494654e77cac2e6187ad1e744ab3e8abde3695345cfe90", + "sourceSha": "d84ac3009f8ba84a339d91e023f7f6f5f9269cc0", + "runId": "39417319998", + "note": "Alias OutboxDispatchConventionTests->BridgeCredentialMutationTests, method Bridge_credential_census_rejects_changed_signatures_captures_and_missing_subjects; unchanged dedented Fact body SHA256 c42eef5db89c31e571ab1d1a7a666b752f4410d9f08f4bf005afcd485900bc25; inherits hosted-architecture-39417319998-2-0. Advisory scalar; new selector not executed hosted." + }, + "pr38-class-alias-credential-binding-f900f146": { + "kind": "hosted_trx", + "artifactSha256": "6c923d6eb54664b3f0d7d889e6ea9eaa29f1b582f6173fefa9318524d3be3b0f", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Alias OutboxDispatchConventionTests->CredentialBindingMutationTests, method Credential_census_rejects_crossed_keys_changed_closures_and_missing_subjects; unchanged dedented Fact body SHA256 815c4e74ec047c3a7b2baaf9133e788fcd65a4a27a2e152724030d9a1d1b8d6c; inherits p031-hosted-architecture-0. Advisory scalar; new selector not executed hosted." + }, + "pr38-class-alias-credential-binding-1805dd42": { + "kind": "hosted_trx", + "artifactSha256": "26837faa8779817aab5f299d42c19b0d8cae668f6bdf2143ff3c4d3b303457dc", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Alias OutboxDispatchConventionTests->CredentialBindingMutationTests, method Credential_census_rejects_compiled_connection_string_indexers_and_composed_keys; unchanged dedented Fact body SHA256 a7f0dab0b9ccf9cebf71449fb480bd5249270e95c262c3019ebb12d2740482c8; inherits p031-hosted-architecture-1. Advisory scalar; new selector not executed hosted." + }, + "pr38-class-alias-integration-invocation-572fda26": { + "kind": "hosted_trx", + "artifactSha256": "97893f76633c41b6046d90bf2ec35c3bbc02d6249b28fd849d916f7e7f5dcdb5", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Alias OutboxDispatchConventionTests->IntegrationInvocationMutationTests, method Integration_invocation_census_rejects_all_layer_direct_interface_helper_async_and_delegate_bypasses; unchanged dedented Fact body SHA256 def20fa944e25cf4b1a8a4fab0f9297a663f5b042fb4a6b017ed646ec6aa391f; inherits pr38-df-1-architecture-2. Advisory scalar; new selector not executed hosted." + }, + "pr38-class-alias-delivery-credential-0fe0826f": { + "kind": "hosted_trx", + "artifactSha256": "97893f76633c41b6046d90bf2ec35c3bbc02d6249b28fd849d916f7e7f5dcdb5", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Alias OutboxDispatchConventionTests->DeliveryCredentialMutationTests, method Delivery_credentials_reject_extra_store_locators_forwarding_overloads_and_wrong_keys; unchanged dedented Fact body SHA256 1a15c08a9e002ce9810a63319a1ba4c7e91d13e8fc2575102c8961bbed7d1185; inherits pr38-df-1-architecture-2. Advisory scalar; new selector not executed hosted." + }, + "pr38-class-alias-job-orchestration-declaration-42dae548": { + "kind": "hosted_trx", + "artifactSha256": "6c923d6eb54664b3f0d7d889e6ea9eaa29f1b582f6173fefa9318524d3be3b0f", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Alias OutboxDispatchConventionTests->JobOrchestrationDeclarationMutationTests, method Background_job_orchestration_has_closed_finite_owners_and_rejects_extra_callers_and_lost_retention; unchanged dedented Fact body SHA256 126d54402544743466ff3d0557a71f050e721072a768e7fef6b79dd6e6bde90a; inherits p031-hosted-architecture-0. Advisory scalar; new selector not executed hosted." + }, + "pr38-class-alias-job-metric-bf372ff9": { + "kind": "hosted_trx", + "artifactSha256": "c183ef8d7fc84a8e55c417b2c2e370c32a7688f7bbae49eb0d69fee16439f3d4", + "sourceSha": "d84ac3009f8ba84a339d91e023f7f6f5f9269cc0", + "runId": "39417319998", + "note": "Alias OutboxDispatchConventionTests->JobMetricMutationTests, method Background_job_metric_callbacks_follow_the_actual_transitive_memory_graph_and_refuse_persistence_helpers; unchanged dedented Fact body SHA256 3f82b6de1b87ff1059613e5a3bdaccab051f292f7c24d83dc520cf3282aa0243; inherits hosted-architecture-39417319998-2-1. Advisory scalar; new selector not executed hosted." + }, + "pr38-class-alias-job-metric-a826fef6": { + "kind": "hosted_trx", + "artifactSha256": "dd1213a26dbb87999c5545f71061f76dccc124e5950f44eec6dd237a240ffc02", + "sourceSha": "3754e4eaa501b22ab97c70678e5622d48e6e8f63", + "runId": "40270967586", + "note": "Alias OutboxDispatchConventionTests->JobMetricMutationTests, method Background_job_metric_census_rejects_bait_callbacks_hidden_registration_and_skipped_binding; unchanged dedented Fact body SHA256 50ff6e956474be146837e346675629737c6d309c2cc9eedd1914af86ba373681; inherits p031-hosted-architecture-3. Advisory scalar; new selector not executed hosted." + }, + "pr38-class-alias-job-authority-census-ef981129": { + "kind": "hosted_trx", + "artifactSha256": "810581e38845581eb1b96afd5551b3da6a3d136af5443cfa7f6582ee50096e69", + "sourceSha": "d6a794cd41ddefbffac5fb9f9195ded465d0c358", + "runId": "40326601181", + "note": "Alias OutboxDispatchConventionTests+JobAuthorityMutationTests->JobAuthorityCensusMutationTests, method Background_job_authority_census_detects_extra_activation_and_removed_live_guards; unchanged dedented Fact body SHA256 7665f56665cd4acbc8ae85f135e0e41bd19c7e4499d17cb2a0cb6b8a1c8fd499; inherits pr38-df-1-architecture-1. Advisory scalar; new selector not executed hosted." } }, "weights": [ @@ -198,14 +709,56 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.AggregateWriteTests.Write_Port_Census_Distinguishes_Typed_Read_Keys_From_Wrapped_Domain_Writes", - "milliseconds": 4, - "source": "hosted-architecture-39417319998-2-5" + "milliseconds": 9, + "source": "p031-hosted-architecture-0" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.ApiConventionTests.Deployment_Mode_Is_Required_Configuration", + "method": "LearnStack.Tests.Architecture.AnalyzerWiringTests.Production_Analyzer_Reference_Is_Unconditional_And_Cannot_Be_Silenced_By_Build_Settings", + "milliseconds": 18, + "source": "p031-hosted-architecture-0" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.AnalyzerWiringTests.Production_Projects_Run_The_Bounded_Exception_Analyzers", + "milliseconds": 41572, + "source": "p031-hosted-architecture-1" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.AnalyzerWiringTests.The_Build_Setting_Control_Rejects_LS0002_Suppression", + "milliseconds": 2, + "source": "p031-hosted-architecture-4" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.AnalyzerWiringTests.The_EditorConfig_Control_Rejects_LS0002_Suppression", "milliseconds": 1, - "source": "local-architecture" + "source": "p031-hosted-architecture-2" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.AnalyzerWiringTests.The_Evaluated_Wiring_Control_Rejects_A_Library_Or_Duplicate_Reference", + "milliseconds": 3, + "source": "p031-hosted-architecture-5" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.AnalyzerWiringTests.The_Unconditional_Reference_Control_Rejects_Environment_Branches", + "milliseconds": 2, + "source": "p031-hosted-architecture-0" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.AnalyzerWiringTests.Unrelated_Analyzer_And_Warning_Settings_Are_Allowed", + "milliseconds": 2, + "source": "p031-hosted-architecture-1" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.ApiConventionTests.Deployment_Mode_Is_Required_Configuration", + "milliseconds": 3, + "source": "p031-hosted-architecture-0" }, { "assembly": "learnstack.tests.architecture", @@ -225,11 +778,71 @@ "milliseconds": 16, "source": "hosted-architecture-39417319998-2-0" }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.AsyncStoreInventoryTests.Durable_Async_Store_Inventory_Covers_The_Storage_Census", + "milliseconds": 1465, + "source": "p031-hosted-architecture-3" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.AsyncStoreInventoryTests.Inventory_coverage_rejects_added_removed_and_reclassified_storage", + "milliseconds": 1834, + "source": "p031-hosted-architecture-4" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.AsyncStoreInventoryTests.Inventory_coverage_rejects_every_removed_row_and_blank_vendor_classification", + "milliseconds": 4487, + "source": "p031-hosted-architecture-2" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.AsyncStoreInventoryTests.Inventory_coverage_requires_bounded_well_formed_tables", + "milliseconds": 1661, + "source": "p031-hosted-architecture-5" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.AsyncStoreInventoryTests.Migration_census_detects_select_into_after_escape_literals", + "milliseconds": 8, + "source": "p031-hosted-architecture-0" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.AsyncStoreInventoryTests.Migration_census_does_not_resolve_escape_literal_values", + "milliseconds": 23, + "source": "p031-hosted-architecture-1" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.AsyncStoreInventoryTests.Migration_census_preserves_literal_boundaries_before_table_declarations", + "milliseconds": 9, + "source": "p031-hosted-architecture-3" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.AsyncStoreInventoryTests.Migration_census_refuses_unsupported_ddl_for_the_expected_reason", + "milliseconds": 24, + "source": "p031-hosted-architecture-4" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.AsyncStoreInventoryTests.Migration_census_tracks_ordered_literal_and_typed_table_lifecycle", + "milliseconds": 8, + "source": "p031-hosted-architecture-2" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.AsyncStoreInventoryTests.Typed_migration_operations_cannot_hide_non_public_storage_or_schema_removal", + "milliseconds": 8, + "source": "p031-hosted-architecture-5" + }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.AuditConventionTests.AuditEntry_Inherits_Entity_Not_AuditableEntity", "milliseconds": 1, - "source": "hosted-architecture-39417319998-2-2" + "source": "p031-hosted-architecture-0" }, { "assembly": "learnstack.tests.architecture", @@ -240,8 +853,8 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.AuditConventionTests.Audit_Closed_Set_Columns_Store_What_Their_Check_Admits", - "milliseconds": 121, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 130, + "source": "p031-hosted-architecture-0" }, { "assembly": "learnstack.tests.architecture", @@ -252,8 +865,8 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.AuditConventionTests.IAuditStore_Exposes_No_Update_Method", - "milliseconds": 1, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 5, + "source": "p031-hosted-architecture-1" }, { "assembly": "learnstack.tests.architecture", @@ -276,26 +889,26 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.AuditConventionTests.The_AppendOnly_Sweep_Can_Actually_Fail", - "milliseconds": 2, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 6, + "source": "p031-hosted-architecture-1" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.AuditConventionTests.The_AuditLog_Write_Scan_Can_Actually_Fail", - "milliseconds": 28, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 32, + "source": "p031-hosted-architecture-1" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.AuditConventionTests.The_Matrix_Sweep_Can_Actually_Fail", "milliseconds": 1, - "source": "hosted-architecture-39417319998-2-0" + "source": "p031-hosted-architecture-2" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.AuditConventionTests.The_Set_Based_Write_Sweep_Can_Actually_Fail", "milliseconds": 5, - "source": "hosted-architecture-39417319998-2-0" + "source": "p031-hosted-architecture-3" }, { "assembly": "learnstack.tests.architecture", @@ -342,14 +955,14 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.AuditCoverageTests.Integration_Audit_Census_Catches_An_Unregistered_Handler_For_A_Shared_Event", - "milliseconds": 37, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 104, + "source": "p031-hosted-architecture-5" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.AuditCoverageTests.Integration_Audit_Census_Rejects_Event_Only_Classification", - "milliseconds": 8, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 17, + "source": "p031-hosted-architecture-4" }, { "assembly": "learnstack.tests.architecture", @@ -366,8 +979,8 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.AuditCoverageTests.The_Forward_Sweep_Rejects_A_Class_Or_A_Type_It_Cannot_Read", - "milliseconds": 1, - "source": "local-architecture" + "milliseconds": 13, + "source": "p031-hosted-architecture-3" }, { "assembly": "learnstack.tests.architecture", @@ -379,19 +992,19 @@ "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.AuditCoverageTests.The_Module_Sweep_Can_Actually_Fail", "milliseconds": 2, - "source": "hosted-architecture-39417319998-2-1" + "source": "p031-hosted-architecture-2" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.AuditCoverageTests.The_Request_Sweep_Can_Actually_Fail", - "milliseconds": 2, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 11, + "source": "p031-hosted-architecture-1" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.AuthenticatedHttpSurfaceTests.Authenticated_Http_Surface_Is_Enumerated_And_ReadOnly", - "milliseconds": 1414, - "source": "hosted-architecture-39417319998-2-4" + "milliseconds": 3172, + "source": "p031-hosted-architecture-5" }, { "assembly": "learnstack.tests.architecture", @@ -402,38 +1015,38 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.AuthenticatedHttpSurfaceTests.Authenticated_http_census_follows_production_helpers_and_nested_dispatch", - "milliseconds": 42406, - "source": "hosted-architecture-39417319998-2-4" + "milliseconds": 53305, + "source": "pr38-df-1-architecture-4" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.AuthenticationAuthorityTests.Authority_census_closes_shape_and_approved_owner_exports", - "milliseconds": 15693, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 53887, + "source": "pr38-df-1-architecture-5" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.AuthenticationAuthorityTests.Authority_census_detects_missing_subjects_mutability_and_extra_trust_writes", - "milliseconds": 12726, - "source": "hosted-architecture-39417319998-2-4" + "milliseconds": 35084, + "source": "pr38-df-1-architecture-3" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.AuthenticationAuthorityTests.Authority_census_rejects_actual_identity_forwarding_through_opaque_storage", - "milliseconds": 4453, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 7210, + "source": "p031-hosted-architecture-4" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.AuthenticationAuthorityTests.Authority_census_rejects_actual_identity_forwarding_to_opaque_helpers", - "milliseconds": 5288, - "source": "hosted-architecture-39417319998-2-5" + "milliseconds": 7942, + "source": "p031-hosted-architecture-1" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.AuthenticationAuthorityTests.Authority_census_rejects_compiled_claim_role_and_projection_bypasses", - "milliseconds": 48741, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 80749, + "source": "pr38-df-2-architecture-3" }, { "assembly": "learnstack.tests.architecture", @@ -450,14 +1063,14 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.CorpusConsistencyTests.No_Architecture_Test_Is_Skippable", - "milliseconds": 6, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 12, + "source": "p031-hosted-architecture-5" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.CorpusConsistencyTests.Standard_Status_Headers_Match_The_Index", - "milliseconds": 15, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 19, + "source": "p031-hosted-architecture-0" }, { "assembly": "learnstack.tests.architecture", @@ -480,8 +1093,8 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.CrossCuttingFoundationTests.Domain_Methods_Do_Not_Throw_For_Expected_Cases", - "milliseconds": 14278, - "source": "hosted-architecture-39417319998-2-4" + "milliseconds": 22908, + "source": "p031-hosted-architecture-1" }, { "assembly": "learnstack.tests.architecture", @@ -492,14 +1105,14 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.CrossCuttingFoundationTests.IErrorTrackingProvider_Is_Singleton", - "milliseconds": 152, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 184, + "source": "p031-hosted-architecture-5" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.CrossCuttingFoundationTests.IExceptionHandler_Registered_AtStartup", - "milliseconds": 14, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 16, + "source": "p031-hosted-architecture-5" }, { "assembly": "learnstack.tests.architecture", @@ -516,8 +1129,8 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.CrossCuttingFoundationTests.LearnStack_Modules_DoNotReference_Hub", - "milliseconds": 252, - "source": "hosted-architecture-39417319998-2-5" + "milliseconds": 294, + "source": "p031-hosted-architecture-3" }, { "assembly": "learnstack.tests.architecture", @@ -528,8 +1141,8 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.CrossCuttingFoundationTests.MediatR_Pipeline_Order_Matches_Canonical_Sequence", - "milliseconds": 3, - "source": "hosted-architecture-39417319998-2-1" + "milliseconds": 14, + "source": "p031-hosted-architecture-4" }, { "assembly": "learnstack.tests.architecture", @@ -540,8 +1153,8 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.CrossCuttingFoundationTests.Modules_Do_Not_Inject_Valkey_Directly", - "milliseconds": 213, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 270, + "source": "p031-hosted-architecture-2" }, { "assembly": "learnstack.tests.architecture", @@ -564,8 +1177,8 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.CrossCuttingFoundationTests.Registering_The_Pipeline_Twice_Registers_It_Once", - "milliseconds": 21, - "source": "hosted-architecture-39417319998-2-1" + "milliseconds": 23, + "source": "p031-hosted-architecture-0" }, { "assembly": "learnstack.tests.architecture", @@ -594,14 +1207,14 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.CustomizationProjectionTests.Projection_validator_guard_follows_domain_contracts_and_external_production_helpers", - "milliseconds": 105, - "source": "hosted-architecture-predecessor" + "milliseconds": 125, + "source": "p031-hosted-architecture-3" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.CustomizationRegistryTests.Composite_Renderer_Keys_Match_The_Frontend_Registry", - "milliseconds": 4, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 6, + "source": "p031-hosted-architecture-2" }, { "assembly": "learnstack.tests.architecture", @@ -609,6 +1222,54 @@ "milliseconds": 8, "source": "hosted-architecture-39417319998-2-2" }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.DataProtectionConventionTests.Census_is_deterministic_and_reports_no_annotation_or_property_values", + "milliseconds": 37, + "source": "p031-hosted-architecture-0" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.DataProtectionConventionTests.Classification_annotations_introduce_no_relational_schema_changes", + "milliseconds": 1370, + "source": "p031-hosted-architecture-1" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.DataProtectionConventionTests.Declaration_of_an_unmapped_name_does_not_create_a_property_or_partially_classify", + "milliseconds": 10, + "source": "p031-hosted-architecture-3" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.DataProtectionConventionTests.Invalid_category_or_blank_purpose_is_refused", + "milliseconds": 50, + "source": "p031-hosted-architecture-4" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.DataProtectionConventionTests.Mapped_Properties_Have_Explicit_Personal_Data_Classification", + "milliseconds": 16, + "source": "p031-hosted-architecture-2" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.DataProtectionConventionTests.Production_model_accepts_the_same_neutral_property_with_an_explicit_declaration", + "milliseconds": 111, + "source": "p031-hosted-architecture-5" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.DataProtectionConventionTests.Production_model_refuses_a_neutral_property_added_after_normal_customization", + "milliseconds": 347, + "source": "p031-hosted-architecture-0" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.DataProtectionConventionTests.Purpose_is_bounded_and_conflicting_declarations_cannot_overwrite_a_review", + "milliseconds": 4, + "source": "p031-hosted-architecture-1" + }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.DomainEventHandlerTests.Domain_Event_Handlers_Are_Outbox_Only", @@ -618,14 +1279,14 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.DomainEventHandlerTests.Domain_handler_census_recognizes_inherited_generic_contracts_and_excludes_other_notifications", - "milliseconds": 16, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 33, + "source": "p031-hosted-architecture-4" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.DomainEventHandlerTests.Domain_handler_guard_accepts_translation_and_pure_helpers_without_traversing_outbox_implementations", - "milliseconds": 16, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 113, + "source": "p031-hosted-architecture-5" }, { "assembly": "learnstack.tests.architecture", @@ -660,14 +1321,14 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.DomainGenericityTests.Demo_Identity_Projection_Is_Complete_And_The_Frontend_Snapshot_Matches", - "milliseconds": 62, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 65, + "source": "p031-hosted-architecture-3" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.DomainGenericityTests.Demo_Literal_Fence_Detects_Decoded_Identities_And_Admits_Platform_Data", - "milliseconds": 98, - "source": "hosted-architecture-39417319998-2-1" + "milliseconds": 286, + "source": "p031-hosted-architecture-1" }, { "assembly": "learnstack.tests.architecture", @@ -690,8 +1351,8 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.DomainGenericityTests.The_Domain_Term_Scan_Can_Actually_Fail", - "milliseconds": 85, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 90, + "source": "p031-hosted-architecture-2" }, { "assembly": "learnstack.tests.architecture", @@ -708,8 +1369,8 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.DomainModelTests.The_Aggregate_Shape_Rules_Can_Actually_Fail", - "milliseconds": 4, - "source": "hosted-architecture-39417319998-2-1" + "milliseconds": 27, + "source": "p031-hosted-architecture-0" }, { "assembly": "learnstack.tests.architecture", @@ -726,8 +1387,8 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.EntitlementKeyTests.FeatureKey_AllReferences_AreInRegistry", - "milliseconds": 405, - "source": "hosted-architecture-predecessor" + "milliseconds": 422, + "source": "p031-hosted-architecture-1" }, { "assembly": "learnstack.tests.architecture", @@ -738,8 +1399,86 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.EntitlementKeyTests.The_Entitlement_Key_Scans_Can_Actually_Fail", - "milliseconds": 255, - "source": "hosted-architecture-39417319998-2-1" + "milliseconds": 351, + "source": "p031-hosted-architecture-5" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.GlobalIdentityModelTests.Generated_snapshot_matches_the_current_Identity_model", + "milliseconds": 123, + "source": "p031-hosted-architecture-3" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.GlobalIdentityModelTests.Historical_Identity_migrations_retain_their_ordered_SQL_operations", + "milliseconds": 37, + "source": "pr38-df-1-architecture-3" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.GlobalIdentityModelTests.User_Aggregate_Has_No_TenantScoped_Columns", + "milliseconds": 515, + "source": "p031-hosted-architecture-4" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.GlobalIdentityModelTests.User_binding_has_permanent_unique_key_creation_pair_and_sensitive_raw_subject", + "milliseconds": 460, + "source": "p031-hosted-architecture-2" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.IdentityAuditConventionTests.A_new_minter_or_a_borrowed_core_edge_is_rejected", + "milliseconds": 13, + "source": "p031-hosted-architecture-5" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.IdentityAuditConventionTests.Global_Identity_Creation_Uses_The_Common_Audit_Owner", + "milliseconds": 1275, + "source": "p031-hosted-architecture-0" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.IdentityAuditConventionTests.Identity_infrastructure_core_edges_are_confined_to_exact_types_and_members", + "milliseconds": 627, + "source": "p031-hosted-architecture-1" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.IdentityAuditConventionTests.The_enrollment_reader_has_no_public_mutator_and_does_not_allocate_a_unit", + "milliseconds": 396, + "source": "p031-hosted-architecture-3" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.IdentityFoundationConventionTests.Identity_Membership_Invariants_Use_Fresh_Ordered_Locks", + "milliseconds": 1006, + "source": "p031-hosted-architecture-4" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.IdentityFoundationConventionTests.Identity_Seed_Uses_Finite_Adopted_Manifests", + "milliseconds": 19, + "source": "p031-hosted-architecture-2" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.IdentityFoundationConventionTests.Permission_Definitions_DeclareScope", + "milliseconds": 29, + "source": "p031-hosted-architecture-5" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.IdentityFoundationConventionTests.Registry_controls_detect_missing_duplicate_inactive_and_wrong_scope_definitions", + "milliseconds": 18, + "source": "p031-hosted-architecture-0" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.IdentityFoundationConventionTests.Session_api_control_detects_a_planted_borrowed_lifetime", + "milliseconds": 2, + "source": "p031-hosted-architecture-1" }, { "assembly": "learnstack.tests.architecture", @@ -756,14 +1495,14 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.IntegrationEventContractTests.Integration_Events_Inherit_From_IntegrationEventBase", - "milliseconds": 106, - "source": "hosted-architecture-39417319998-2-5" + "milliseconds": 110, + "source": "p031-hosted-architecture-5" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.ModuleDependencyTests.CoreApplication_DoesNotDependOn_Any_Infrastructure_Or_Module", - "milliseconds": 1, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 3, + "source": "p031-hosted-architecture-4" }, { "assembly": "learnstack.tests.architecture", @@ -792,38 +1531,38 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.ModuleDependencyTests.ModuleContracts_DoNotDependOn_AnyModuleDomain", - "milliseconds": 175, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 262, + "source": "p031-hosted-architecture-3" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.ModuleDependencyTests.ModuleContracts_Reference_Only_SharedKernel", "milliseconds": 10, - "source": "hosted-architecture-39417319998-2-2" + "source": "p031-hosted-architecture-0" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.ModuleDependencyTests.ModuleDomain_DoesNotDependOn_AnyApplicationOrInfrastructure", - "milliseconds": 3, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 21, + "source": "p031-hosted-architecture-5" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.ModuleDependencyTests.ModuleDomain_DoesNotDependOn_OtherModuleDomain", - "milliseconds": 56, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 117, + "source": "p031-hosted-architecture-1" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.ModuleDependencyTests.ModuleInfrastructure_References_Only_Its_Own_Layers_And_Core_Infrastructure", - "milliseconds": 11, - "source": "local-architecture" + "milliseconds": 13, + "source": "p031-hosted-architecture-2" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.ModuleDependencyTests.The_Dependency_Matrix_Can_Actually_Fail", - "milliseconds": 1, - "source": "local-architecture" + "milliseconds": 2, + "source": "p031-hosted-architecture-5" }, { "assembly": "learnstack.tests.architecture", @@ -833,195 +1572,219 @@ }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+JobAuthorityMutationTests.Background_job_application_source_ownership_has_exact_nonempty_callers_and_rejects_escapes", - "milliseconds": 70000, - "source": "hosted-architecture-first" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+BridgeCredentialMutationTests.Bridge_credential_census_rejects_changed_signatures_captures_and_missing_subjects", + "milliseconds": 157058, + "source": "pr38-class-alias-bridge-credential-c6cb9e31" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+JobAuthorityMutationTests.Background_job_authority_census_detects_extra_activation_and_removed_live_guards", - "milliseconds": 371000, - "source": "hosted-architecture-first" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+BridgeCredentialMutationTests.Bridge_credential_census_rejects_extra_acquisition_forwarding_and_store_consumers", + "milliseconds": 169833, + "source": "pr38-class-alias-bridge-credential-8d40b87a" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+JobAuthorityMutationTests.Credential_census_rejects_generic_direct_delegate_async_and_extra_helper_resolution", - "milliseconds": 334000, - "source": "hosted-architecture-current" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+CleanupOwnerMutationTests.Cleanup_owner_census_rejects_extra_acquisition_disposal_capture_and_observation_paths", + "milliseconds": 246241, + "source": "pr38-class-alias-cleanup-owner-1067e9c3" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+JobExecutionMutationTests.Background_job_owner_census_detects_actual_removals_extra_subtypes_async_calls_and_delegates", - "milliseconds": 391105, - "source": "hosted-architecture-39417319998-2-1" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+CredentialBindingMutationTests.Credential_census_rejects_compiled_connection_string_indexers_and_composed_keys", + "milliseconds": 42130, + "source": "pr38-class-alias-credential-binding-1805dd42" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+JobExecutionMutationTests.External_job_orchestration_rejects_missing_seams_helpers_delegates_signatures_and_resource_carriers", - "milliseconds": 327614, - "source": "hosted-architecture-39417319998-2-0" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+CredentialBindingMutationTests.Credential_census_rejects_crossed_keys_changed_closures_and_missing_subjects", + "milliseconds": 154403, + "source": "pr38-class-alias-credential-binding-f900f146" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+JobLifecycleMutationTests.Background_job_capacity_census_rejects_forged_cleanup_recovery_and_checkpoint_owners", - "milliseconds": 375316, - "source": "hosted-architecture-39417319998-2-4" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+DeliveryCredentialMutationTests.Delivery_credentials_reject_extra_store_locators_forwarding_overloads_and_wrong_keys", + "milliseconds": 122232, + "source": "pr38-class-alias-delivery-credential-0fe0826f" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+JobLifecycleMutationTests.Background_job_recipient_census_detects_extra_authority_and_missing_real_fences", - "milliseconds": 160981, - "source": "hosted-architecture-39417319998-2-4" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+DeliveryLifecycleMutationTests.Integration_delivery_lifecycle_census_rejects_typed_helper_async_delegate_and_missing_paths", + "milliseconds": 172694, + "source": "pr38-class-alias-delivery-lifecycle-4abc441d" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+JobLifecycleMutationTests.Hangfire_runtime_census_rejects_fatal_and_constructor_escapes", + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+HangfireRuntimeMutationTests.Hangfire_runtime_census_rejects_fatal_and_constructor_escapes", "milliseconds": 236768, - "source": "hosted-architecture-39417319998-2-1" + "source": "pr38-class-alias-hangfire-runtime" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.BackgroundJob_Capacity_Is_Tenant_Wide_And_Quiescence_Bound", - "milliseconds": 797, - "source": "hosted-architecture-predecessor" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+IntegrationInvocationMutationTests.Integration_invocation_census_rejects_all_layer_direct_interface_helper_async_and_delegate_bypasses", + "milliseconds": 132079, + "source": "pr38-class-alias-integration-invocation-572fda26" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.BackgroundJob_Completion_Is_Owner_Atomic_And_Fenced", - "milliseconds": 369, - "source": "local-architecture" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+JobAuthorityCensusMutationTests.Background_job_authority_census_detects_extra_activation_and_removed_live_guards", + "milliseconds": 603500, + "source": "pr38-class-alias-job-authority-census-ef981129" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.BackgroundJob_Definitions_Stay_In_Their_Owning_Module", - "milliseconds": 12851, - "source": "hosted-architecture-39417319998-2-0" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+JobAuthorityMutationTests.Background_job_application_source_ownership_has_exact_nonempty_callers_and_rejects_escapes", + "milliseconds": 101387, + "source": "pr38-df-2-architecture-1" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.BackgroundJob_External_Work_Has_No_Business_Transaction", - "milliseconds": 100965, - "source": "hosted-architecture-39417319998-2-1" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+JobAuthorityMutationTests.Credential_census_rejects_generic_direct_delegate_async_and_extra_helper_resolution", + "milliseconds": 469168, + "source": "p031-hosted-architecture-3" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.BackgroundJob_Fanout_Uses_Recipient_Bound_Tenant_Admission", - "milliseconds": 630, - "source": "hosted-architecture-39417319998-2-4" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+JobCapacityMutationTests.Background_job_capacity_census_rejects_forged_cleanup_recovery_and_checkpoint_owners", + "milliseconds": 486888, + "source": "pr38-class-alias-job-capacity" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.BackgroundJob_Ordinary_Execution_Has_No_Platform_Authority", - "milliseconds": 536, - "source": "local-architecture" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+JobMetricMutationTests.Background_job_metric_callbacks_follow_the_actual_transitive_memory_graph_and_refuse_persistence_helpers", + "milliseconds": 70110, + "source": "pr38-class-alias-job-metric-bf372ff9" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.BackgroundJob_Storage_And_Credentials_Are_Confined", - "milliseconds": 47779, - "source": "hosted-architecture-39417319998-2-4" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+JobMetricMutationTests.Background_job_metric_census_rejects_bait_callbacks_hidden_registration_and_skipped_binding", + "milliseconds": 34392, + "source": "pr38-class-alias-job-metric-a826fef6" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.BackgroundJob_Terminal_Audit_Is_Row_Bound", - "milliseconds": 340, - "source": "hosted-architecture-39417319998-2-5" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+JobOrchestrationDeclarationMutationTests.Background_job_orchestration_has_closed_finite_owners_and_rejects_extra_callers_and_lost_retention", + "milliseconds": 95987, + "source": "pr38-class-alias-job-orchestration-declaration-42dae548" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.BackgroundJob_Worker_Pools_Reserve_Independent_Capacity", - "milliseconds": 195171, - "source": "hosted-architecture-39417319998-2-5" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+JobOrchestrationMutationTests.External_job_orchestration_rejects_missing_seams_helpers_delegates_signatures_and_resource_carriers", + "milliseconds": 422593, + "source": "pr38-class-alias-job-orchestration" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Background_job_metric_callbacks_follow_the_actual_transitive_memory_graph_and_refuse_persistence_helpers", - "milliseconds": 70110, - "source": "hosted-architecture-39417319998-2-1" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+JobOwnerMutationTests.Background_job_owner_census_detects_actual_removals_extra_subtypes_async_calls_and_delegates", + "milliseconds": 391105, + "source": "pr38-class-alias-job-owner" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Background_job_metric_census_rejects_bait_callbacks_hidden_registration_and_skipped_binding", - "milliseconds": 30878, - "source": "hosted-architecture-39417319998-2-2" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+JobRecipientMutationTests.Background_job_recipient_census_detects_extra_authority_and_missing_real_fences", + "milliseconds": 206098, + "source": "pr38-class-alias-job-recipient" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Background_job_metric_registration_requires_the_actual_singleton_descriptor_and_rejects_substitutions", - "milliseconds": 16, - "source": "hosted-architecture-39417319998-2-2" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+JobRecurrenceMutationTests.Background_job_recurrence_runtime_controls_reject_changed_authority_and_cleanup", + "milliseconds": 290934, + "source": "pr38-class-alias-job-recurrence" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Background_job_orchestration_has_closed_finite_owners_and_rejects_extra_callers_and_lost_retention", - "milliseconds": 47325, - "source": "hosted-architecture-39417319998-2-5" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests+ResolutionMutationTests.Resolution_walk_detects_loading_construction_async_and_polymorphic_helpers", + "milliseconds": 277724, + "source": "pr38-class-alias-resolution" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Background_job_recipient_field_and_record_controls_detect_the_exact_owner_and_opcode", - "milliseconds": 6509, - "source": "hosted-architecture-39417319998-2-1" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.BackgroundJob_Capacity_Is_Tenant_Wide_And_Quiescence_Bound", + "milliseconds": 805, + "source": "p031-hosted-architecture-5" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Background_job_recipient_history_controls_reject_detached_cleanup_and_unfenced_status", - "milliseconds": 3776, - "source": "hosted-architecture-39417319998-2-2" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.BackgroundJob_Completion_Is_Owner_Atomic_And_Fenced", + "milliseconds": 599, + "source": "p031-hosted-architecture-2" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Background_job_recipient_shared_insert_controls_preserve_successful_production", - "milliseconds": 11345, - "source": "hosted-architecture-39417319998-2-4" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.BackgroundJob_Definitions_Stay_In_Their_Owning_Module", + "milliseconds": 16261, + "source": "p031-hosted-architecture-0" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Background_job_recurrence_runtime_controls_reject_changed_authority_and_cleanup", - "milliseconds": 208191, - "source": "hosted-architecture-39417319998-2-2" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.BackgroundJob_External_Work_Has_No_Business_Transaction", + "milliseconds": 100965, + "source": "hosted-architecture-39417319998-2-1" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Background_job_recurrence_runtime_keeps_exact_concrete_capability_owners", - "milliseconds": 2000, - "source": "hosted-architecture-predecessor" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.BackgroundJob_Fanout_Uses_Recipient_Bound_Tenant_Admission", + "milliseconds": 682, + "source": "p031-hosted-architecture-3" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Boundary_censuses_preserve_unkeyed_services_unrelated_publishers_and_both_real_keys", - "milliseconds": 2186, - "source": "hosted-architecture-39417319998-2-0" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.BackgroundJob_Ordinary_Execution_Has_No_Platform_Authority", + "milliseconds": 927, + "source": "p031-hosted-architecture-0" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Bridge_credential_census_rejects_changed_signatures_captures_and_missing_subjects", - "milliseconds": 157058, - "source": "hosted-architecture-39417319998-2-0" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.BackgroundJob_Storage_And_Credentials_Are_Confined", + "milliseconds": 68217, + "source": "pr38-df-1-architecture-3" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.BackgroundJob_Terminal_Audit_Is_Row_Bound", + "milliseconds": 774, + "source": "p031-hosted-architecture-1" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.BackgroundJob_Worker_Pools_Reserve_Independent_Capacity", + "milliseconds": 298416, + "source": "p031-hosted-architecture-4" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Bridge_credential_census_rejects_extra_acquisition_forwarding_and_store_consumers", - "milliseconds": 127690, + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Background_job_metric_registration_requires_the_actual_singleton_descriptor_and_rejects_substitutions", + "milliseconds": 16, "source": "hosted-architecture-39417319998-2-2" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Cleanup_owner_census_rejects_extra_acquisition_disposal_capture_and_observation_paths", - "milliseconds": 97302, - "source": "hosted-architecture-39417319998-2-5" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Background_job_recipient_field_and_record_controls_detect_the_exact_owner_and_opcode", + "milliseconds": 6509, + "source": "hosted-architecture-39417319998-2-1" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Credential_census_rejects_compiled_connection_string_indexers_and_composed_keys", - "milliseconds": 38008, + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Background_job_recipient_history_controls_reject_detached_cleanup_and_unfenced_status", + "milliseconds": 3776, "source": "hosted-architecture-39417319998-2-2" }, { "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Credential_census_rejects_crossed_keys_changed_closures_and_missing_subjects", - "milliseconds": 119269, - "source": "hosted-architecture-39417319998-2-4" + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Background_job_recipient_shared_insert_controls_preserve_successful_production", + "milliseconds": 12443, + "source": "p031-hosted-architecture-2" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Background_job_recurrence_runtime_keeps_exact_concrete_capability_owners", + "milliseconds": 2113, + "source": "p031-hosted-architecture-0" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Boundary_censuses_preserve_unkeyed_services_unrelated_publishers_and_both_real_keys", + "milliseconds": 2802, + "source": "p031-hosted-architecture-4" }, { "assembly": "learnstack.tests.architecture", @@ -1032,38 +1795,32 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Delivery_Execution_And_Observation_Are_Bounded", - "milliseconds": 572, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 801, + "source": "p031-hosted-architecture-3" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Delivery_SQL_census_rejects_quoted_CTE_helper_overload_missing_and_payload_paths", - "milliseconds": 5431, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 5809, + "source": "p031-hosted-architecture-5" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Delivery_SQL_writers_and_dynamic_helpers_are_closed", - "milliseconds": 469, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 681, + "source": "p031-hosted-architecture-3" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Delivery_Terminal_Audit_Identity_Is_Row_Bound", - "milliseconds": 485, - "source": "hosted-architecture-39417319998-2-2" - }, - { - "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Delivery_credentials_reject_extra_store_locators_forwarding_overloads_and_wrong_keys", - "milliseconds": 81202, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 586, + "source": "p031-hosted-architecture-5" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Delivery_execution_census_rejects_uncontrolled_direct_delegate_async_and_missing_paths", - "milliseconds": 5388, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 6667, + "source": "p031-hosted-architecture-4" }, { "assembly": "learnstack.tests.architecture", @@ -1080,20 +1837,20 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Delivery_owner_census_rejects_extra_direct_delegate_async_and_inherited_capabilities", - "milliseconds": 11383, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 17944, + "source": "p031-hosted-architecture-1" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Delivery_registration_census_rejects_missing_duplicate_replaced_and_detached_subjects", - "milliseconds": 20, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 27, + "source": "p031-hosted-architecture-3" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Hangfire_Bootstrap_Uses_Pinned_Schema_And_Confined_Role", - "milliseconds": 1226, - "source": "hosted-architecture-39417319998-2-4" + "milliseconds": 1493, + "source": "p031-hosted-architecture-1" }, { "assembly": "learnstack.tests.architecture", @@ -1101,47 +1858,35 @@ "milliseconds": 1405, "source": "hosted-architecture-39417319998-2-2" }, - { - "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Integration_delivery_lifecycle_census_rejects_typed_helper_async_delegate_and_missing_paths", - "milliseconds": 106416, - "source": "hosted-architecture-39417319998-2-0" - }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Integration_delivery_lifecycle_stays_with_its_enumerated_owners", - "milliseconds": 491, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 707, + "source": "p031-hosted-architecture-1" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Integration_handler_census_rejects_missing_assemblies_layers_and_production_subjects", - "milliseconds": 2160, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 2741, + "source": "p031-hosted-architecture-5" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Integration_handler_discovery_sees_inherited_generic_and_explicit_contracts", - "milliseconds": 24, - "source": "hosted-architecture-39417319998-2-0" - }, - { - "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Integration_invocation_census_rejects_all_layer_direct_interface_helper_async_and_delegate_bypasses", - "milliseconds": 83219, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 30, + "source": "p031-hosted-architecture-0" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Integration_invocation_compiled_controls_distinguish_helpers_inheritance_async_and_clean_methods", - "milliseconds": 516, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 829, + "source": "p031-hosted-architecture-4" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Integration_manifest_census_rejects_missing_rebound_duplicate_and_unscoped_bindings", - "milliseconds": 231, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 328, + "source": "p031-hosted-architecture-1" }, { "assembly": "learnstack.tests.architecture", @@ -1152,38 +1897,38 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Job_trace_source_and_actual_Activity_ownership_refuse_chained_Start_and_hidden_source_creation", - "milliseconds": 6739, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 7525, + "source": "p031-hosted-architecture-1" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.LearnStack_OutboxAdmin_Role_OnlyUsedBy_OutboxProcessor", - "milliseconds": 2189, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 3078, + "source": "p031-hosted-architecture-0" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Observation_registration_control_detects_missing_duplicate_or_replaced_worker_and_check", - "milliseconds": 69, - "source": "hosted-architecture-39417319998-2-5" + "milliseconds": 94, + "source": "p031-hosted-architecture-2" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Observation_walk_detects_persistence_locators_async_and_polymorphic_helpers", - "milliseconds": 4303, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 5029, + "source": "p031-hosted-architecture-3" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Observation_walk_keeps_clean_memory_helpers_and_checks_real_gauge_callbacks", - "milliseconds": 2000, - "source": "hosted-architecture-predecessor" + "milliseconds": 2056, + "source": "p031-hosted-architecture-3" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Outbox_Health_And_Metrics_Are_Bounded", - "milliseconds": 153, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 213, + "source": "p031-hosted-architecture-0" }, { "assembly": "learnstack.tests.architecture", @@ -1194,8 +1939,8 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Outbox_SQL_census_detects_quoted_schema_CTE_extra_and_missing_writer_paths", - "milliseconds": 3260, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 5128, + "source": "p031-hosted-architecture-0" }, { "assembly": "learnstack.tests.architecture", @@ -1212,8 +1957,8 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Outbox_Type_Resolution_Is_Declared_And_Bounded", - "milliseconds": 2884, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 4281, + "source": "p031-hosted-architecture-5" }, { "assembly": "learnstack.tests.architecture", @@ -1221,12 +1966,6 @@ "milliseconds": 9171, "source": "hosted-architecture-39417319998-2-4" }, - { - "assembly": "learnstack.tests.architecture", - "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Resolution_walk_detects_loading_construction_async_and_polymorphic_helpers", - "milliseconds": 85598, - "source": "hosted-architecture-39417319998-2-5" - }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Resolution_walk_preserves_declared_type_metadata_and_clean_helpers", @@ -1248,14 +1987,14 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Terminal_census_detects_interface_concrete_delegate_async_and_extra_writer_paths", - "milliseconds": 2422, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 2834, + "source": "p031-hosted-architecture-3" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxDispatchConventionTests.Terminal_census_detects_mutability_accessibility_missing_subjects_and_friend_access", - "milliseconds": 2934, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 3304, + "source": "p031-hosted-architecture-3" }, { "assembly": "learnstack.tests.architecture", @@ -1266,8 +2005,8 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.OutboxProducerConventionTests.Outbox_Enqueue_Uses_The_Announced_Transaction", - "milliseconds": 260, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 413, + "source": "p031-hosted-architecture-0" }, { "assembly": "learnstack.tests.architecture", @@ -1290,8 +2029,8 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.PersistenceConventionTests.Every_Database_Test_Carries_The_Docker_Trait", - "milliseconds": 13715, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 31394, + "source": "pr38-df-1-architecture-3" }, { "assembly": "learnstack.tests.architecture", @@ -1326,14 +2065,14 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.PersistenceConventionTests.Migrate_Target_Refuses_An_Aliased_Runtime_Credential", - "milliseconds": 55, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 67, + "source": "p031-hosted-architecture-3" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.PersistenceConventionTests.Migration_Startup_Project_References_EntityFrameworkCore_Design", "milliseconds": 2, - "source": "hosted-architecture-39417319998-2-5" + "source": "p031-hosted-architecture-2" }, { "assembly": "learnstack.tests.architecture", @@ -1362,14 +2101,14 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.PersistenceConventionTests.The_Migration_Order_Guard_Rejects_Each_Dependent_Chain_First", - "milliseconds": 30, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 49, + "source": "p031-hosted-architecture-0" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.PersistenceConventionTests.The_Parallelism_Scan_Can_Actually_Fail", - "milliseconds": 5, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 10, + "source": "p031-hosted-architecture-3" }, { "assembly": "learnstack.tests.architecture", @@ -1410,8 +2149,8 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.PlatformAdminScopeConventionTests.PlatformAdminScope_Entry_Requires_Platform_Permission", - "milliseconds": 118, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 139, + "source": "p031-hosted-architecture-1" }, { "assembly": "learnstack.tests.architecture", @@ -1470,8 +2209,8 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.PublicSurfaceTests.PublicSurface_Requests_Are_Registered_Off", - "milliseconds": 23, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 29, + "source": "p031-hosted-architecture-5" }, { "assembly": "learnstack.tests.architecture", @@ -1512,14 +2251,14 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.RequestSurfaceTests.PublicSurface_Marker_Set_Is_Enumerated", - "milliseconds": 16, - "source": "hosted-architecture-39417319998-2-4" + "milliseconds": 28, + "source": "p031-hosted-architecture-3" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.RequestSurfaceTests.PublicSurface_Requests_Are_Never_ReadSensitive", - "milliseconds": 22, - "source": "hosted-architecture-39417319998-2-4" + "milliseconds": 30, + "source": "p031-hosted-architecture-5" }, { "assembly": "learnstack.tests.architecture", @@ -1530,14 +2269,14 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.RequestSurfaceTests.The_PublicSurface_Cross_Check_Can_Actually_Fail", - "milliseconds": 3, - "source": "hosted-architecture-39417319998-2-4" + "milliseconds": 5, + "source": "p031-hosted-architecture-5" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.RequestSurfaceTests.The_Request_Filter_Sees_Every_Shape_MediatR_Dispatches", "milliseconds": 1, - "source": "hosted-architecture-39417319998-2-2" + "source": "p031-hosted-architecture-0" }, { "assembly": "learnstack.tests.architecture", @@ -1554,8 +2293,8 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.SeederConventionTests.Seeder_Caller_Fence_Catches_Calls_Method_Groups_And_Sql_But_Admits_Dispatch", - "milliseconds": 6, - "source": "hosted-architecture-39417319998-2-1" + "milliseconds": 51, + "source": "p031-hosted-architecture-1" }, { "assembly": "learnstack.tests.architecture", @@ -1572,8 +2311,20 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.SeederConventionTests.Seeder_Write_Fence_Catches_Ef_Mutations_And_Ad_Hoc_Commands", - "milliseconds": 4, - "source": "hosted-architecture-39417319998-2-1" + "milliseconds": 14, + "source": "p031-hosted-architecture-1" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.SensitiveExceptionMessageTests.Production_Exception_Messages_Do_Not_Contain_Sensitive_References", + "milliseconds": 69283, + "source": "p031-hosted-architecture-3" + }, + { + "assembly": "learnstack.tests.architecture", + "method": "LearnStack.Tests.Architecture.SensitiveExceptionMessageTests.The_Sensitive_Report_Sees_Suppressed_And_Conditional_Violations", + "milliseconds": 4123, + "source": "p031-hosted-architecture-4" }, { "assembly": "learnstack.tests.architecture", @@ -1620,14 +2371,14 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.TenancyConventionTests.Resolving_Host_Is_Set_In_One_Place", - "milliseconds": 68, - "source": "hosted-architecture-current" + "milliseconds": 151, + "source": "p031-hosted-architecture-5" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.TenancyConventionTests.Tenant_Headers_Are_Never_A_Resolution_Source", - "milliseconds": 1909, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 2825, + "source": "p031-hosted-architecture-1" }, { "assembly": "learnstack.tests.architecture", @@ -1638,32 +2389,32 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.TenancyConventionTests.The_Host_Read_Scan_Can_Actually_Fail", - "milliseconds": 2, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 9, + "source": "p031-hosted-architecture-3" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.TenancyConventionTests.The_Outbound_Dependency_Scan_Can_Actually_Fail", - "milliseconds": 14, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 35, + "source": "p031-hosted-architecture-1" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.TenancyConventionTests.The_Scope_Setter_Scan_Can_Actually_Fail", - "milliseconds": 3, - "source": "hosted-architecture-39417319998-2-2" + "milliseconds": 6, + "source": "p031-hosted-architecture-0" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.TenancyConventionTests.The_Setter_Scan_Can_Actually_Fail", - "milliseconds": 8, - "source": "hosted-architecture-39417319998-2-5" + "milliseconds": 76, + "source": "p031-hosted-architecture-3" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.TenancyConventionTests.The_Slug_Scan_Finds_The_Files_It_Exempts", - "milliseconds": 51, - "source": "local-architecture" + "milliseconds": 911, + "source": "p031-hosted-architecture-0" }, { "assembly": "learnstack.tests.architecture", @@ -1686,8 +2437,8 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.TenantContextConstructionTests.Organizations_Are_Read_By_Composite_Key", - "milliseconds": 308, - "source": "hosted-architecture-39417319998-2-0" + "milliseconds": 948, + "source": "p031-hosted-architecture-4" }, { "assembly": "learnstack.tests.architecture", @@ -1698,8 +2449,8 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.TenantContextConstructionTests.TenantContext_Is_Constructed_Only_By_The_Factory", - "milliseconds": 11, - "source": "hosted-architecture-39417319998-2-1" + "milliseconds": 79, + "source": "p031-hosted-architecture-3" }, { "assembly": "learnstack.tests.architecture", @@ -1716,20 +2467,20 @@ { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.TenantScopingTests.Every_Module_With_A_Schema_Is_Swept", - "milliseconds": 9, - "source": "hosted-architecture-39417319998-2-5" + "milliseconds": 12, + "source": "p031-hosted-architecture-1" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.TenantScopingTests.Every_OrgScoped_Entity_HasOrgIdAndFilter", - "milliseconds": 31, - "source": "local-architecture" + "milliseconds": 116, + "source": "p031-hosted-architecture-5" }, { "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.TenantScopingTests.Every_Scoping_Interface_Carries_Its_Marker", "milliseconds": 2, - "source": "hosted-architecture-39417319998-2-5" + "source": "p031-hosted-architecture-4" }, { "assembly": "learnstack.tests.architecture", @@ -1747,373 +2498,529 @@ "assembly": "learnstack.tests.architecture", "method": "LearnStack.Tests.Architecture.TenantScopingTests.The_Tenant_Term_Check_Can_Actually_Fail", "milliseconds": 2, - "source": "hosted-architecture-39417319998-2-4" + "source": "p031-hosted-architecture-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.ApiHandlerCompositionTests.Every_Shipped_Request_Handler_Resolves_From_The_Api_Container", - "milliseconds": 1013, - "source": "local-ordinary-scaled" + "milliseconds": 1331, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AmbientUnitOfWorkTests.A_Cross_Module_Read_Inside_The_Ambient_Transaction_Returns_Rows", - "milliseconds": 69, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.AuthenticatedRateLimitTests.Authenticated_Rate_Limits_Use_Validated_Subject", + "milliseconds": 567, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AmbientUnitOfWorkTests.An_Outer_Failure_After_An_Inner_Write_Leaves_Zero_Rows_In_Both_Modules", - "milliseconds": 205, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.AuthenticatedRateLimitTests.Blocked_acquisition_cleanup_holds_its_signed_request_until_fault_without_blocking_other_subjects", + "milliseconds": 390, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditCaptureWiringTests.One_scope_shares_one_capture_across_every_module_context", - "milliseconds": 3, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.AuthenticatedRateLimitTests.Production_visitor_quota_blocks_validated_subjects_with_replenishment_disabled", + "milliseconds": 1059, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditCaptureWiringTests.Saving_through_a_module_context_fills_the_request_capture", - "milliseconds": 64, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.AuthenticatedRateLimitTests.Signed_admission_exports_quota_capacity_and_sticky_fault_without_resolution_or_identity_labels", + "milliseconds": 1148, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditCaptureWiringTests.The_real_composition_root_keeps_the_audit_interceptor_behind_another_one", - "milliseconds": 5, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AccountSiteHttpTests.Account_query_parameters_are_rejected_before_configuration_and_stay_no_store", + "milliseconds": 6393, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditCaptureWiringTests.The_synchronous_save_path_fills_the_capture_too", - "milliseconds": 52, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AccountSiteHttpTests.Actual_account_HTTP_admits_only_the_enumerated_GET", + "milliseconds": 45638, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditConfigServiceTests.A_read_failure_falls_back_to_the_declared_tier", - "milliseconds": 5, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AccountSiteHttpTests.Actual_account_HTTP_reads_English_and_Yoga_row_9_under_ReadOnly_without_query_audits", + "milliseconds": 7845, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditConfigServiceTests.A_request_with_no_resolved_tenant_has_no_overrides_to_read", - "milliseconds": 2, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AccountSiteHttpTests.Actual_account_HTTP_rechecks_a_suspended_mapped_organization_after_host_cache_warmup", + "milliseconds": 8389, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditConfigServiceTests.A_tenant_never_sees_another_tenants_overrides", - "milliseconds": 32, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AccountSiteHttpTests.Actual_account_route_preserves_claim_and_membership_codes_and_durable_host_attribution", + "milliseconds": 39126, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditConfigServiceTests.An_operation_with_no_row_keeps_its_declared_tier", - "milliseconds": 28, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AccountSiteHttpTests.Actual_authenticated_header_rejection_preserves_actor_correlation_and_trusted_organization", + "milliseconds": 9747, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditConfigServiceTests.An_override_cannot_remove_a_MUST", - "milliseconds": 3, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AccountSiteHttpTests.Anonymous_header_mismatch_and_malformed_assertions_keep_their_distinct_errors_without_query_reads", + "milliseconds": 12133, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditConfigServiceTests.An_override_silences_a_SHOULD_operation", - "milliseconds": 31, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AccountSiteHttpTests.Anonymous_public_site_survives_an_unavailable_issuer_and_failed_credentials_never_fall_back", + "milliseconds": 5231, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditConfigServiceTests.The_cache_family_is_the_one_Standards_20_registers", - "milliseconds": 1, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AccountSiteHttpTests.Application_body_limit_refusals_keep_no_store_before_credential_admission", + "milliseconds": 10215, + "source": "pr38-b-ordinary-1" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditConfigServiceTests.The_override_read_names_its_tenant_where_row_security_would_not", - "milliseconds": 45, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AccountSiteHttpTests.Claimless_signed_profiles_keep_the_public_ceiling_and_emit_one_fixed_Debug_event_per_admitted_request", + "milliseconds": 7668, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditConfigServiceTests.The_override_staleness_bound_is_the_one_Standards_20_states", - "milliseconds": 1, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AccountSiteHttpTests.Future_platform_membership_success_still_masks_AccountSite_before_configuration_access", + "milliseconds": 7658, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditConfigServiceTests.The_projection_outlives_the_cache_implementations_own_default", - "milliseconds": 37, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AccountSiteQueryTests.Actual_account_query_cannot_join_a_writable_outer_owner_or_reach_its_reader", + "milliseconds": 118, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditPipelineTests.A_MUST_row_that_cannot_be_written_takes_its_business_write_down_with_it", - "milliseconds": 525, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AccountSiteQueryTests.Actual_account_query_hides_valid_empty_or_all_disabled_locale_configuration", + "milliseconds": 285, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditPipelineTests.Audit_Classification_Does_Not_Read_The_Database_On_The_Request_Path", - "milliseconds": 511, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AccountSiteQueryTests.Actual_account_query_physically_refuses_SQL_and_EF_writes_with_writable_controls", + "milliseconds": 187, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditPipelineTests.Audit_Survives_Transaction_Rollback", - "milliseconds": 608, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AccountSiteQueryTests.Actual_account_query_reads_contrasting_tenants_and_mapped_organization_without_query_audits", + "milliseconds": 246, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditPipelineTests.MustClass_Audit_Writes_Share_The_Business_Transaction", - "milliseconds": 596, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AccountSiteQueryTests.Actual_account_query_rechecks_live_tenant_mapped_and_claim_selected_organization", + "milliseconds": 1442, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditPipelineTests.The_host_mapping_row_carries_the_state_it_changed", - "milliseconds": 441, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AccountSiteQueryTests.Actual_account_query_refuses_foreign_tenant_or_sibling_organization_provenance_before_reading", + "milliseconds": 192, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditPipelineTests.The_row_carries_the_snapshot_the_interceptor_captured", - "milliseconds": 432, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AccountSiteQueryTests.Real_configuration_reader_independently_refuses_invalid_host_provenance_with_same_frame_control", + "milliseconds": 276, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditPipelineTests.The_row_carries_the_tenant_the_transaction_announced", - "milliseconds": 472, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AccountSiteQueryTests.Real_configuration_reader_refuses_an_announced_enlisted_writable_frame_with_read_only_control", + "milliseconds": 89, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.ARedactingUpdateByThePlatformRoleSucceeds", - "milliseconds": 17, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AccountSiteQueryTests.Real_configuration_reader_refuses_missing_or_foreign_EF_transaction_with_same_role_controls", + "milliseconds": 122, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.AnOrganizationScopedRowNeedsBothAnnouncements", - "milliseconds": 10, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AccountSiteQueryTests.Real_configuration_reader_refuses_unannounced_transaction_then_reads_after_announcement", + "milliseconds": 69, + "source": "pr38-b-ordinary-0" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.AnOrganizationScopedSessionReadsItsOwnRowsAndTheTenantWideOnes", - "milliseconds": 7, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AmbientUnitOfWorkTests.A_Cross_Module_Read_Inside_The_Ambient_Transaction_Returns_Rows", + "milliseconds": 341, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.AuditConfigKeepsItsForeignKeyToTenants", - "milliseconds": 9, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AmbientUnitOfWorkTests.An_Outer_Failure_After_An_Inner_Write_Leaves_Zero_Rows_In_Both_Modules", + "milliseconds": 340, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.AuditLogCarriesNoForeignKeyToTenants", - "milliseconds": 9, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AuditCaptureWiringTests.One_scope_shares_one_capture_across_every_module_context", + "milliseconds": 4, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.TheClosedSetColumnsRejectAValueOutsideTheirCheck", - "milliseconds": 17, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AuditCaptureWiringTests.Saving_through_a_module_context_fills_the_request_capture", + "milliseconds": 374, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.TheCompositeKeyAdmitsTheCommitInDoubtPairAndNothingElse", - "milliseconds": 10, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AuditCaptureWiringTests.The_real_composition_root_keeps_the_audit_interceptor_behind_another_one", + "milliseconds": 54, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.TheOwnerIsStoppedOnlyByTheTrigger", - "milliseconds": 25, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AuditCaptureWiringTests.The_synchronous_save_path_fills_the_capture_too", + "milliseconds": 349, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.ThePlatformRoleCannotUpdateAnythingElse", - "milliseconds": 20, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AuditConfigServiceTests.A_read_failure_falls_back_to_the_declared_tier", + "milliseconds": 69, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.ThePlatformRoleHoldsExactlyTheSixColumnUpdateGrant", - "milliseconds": 15, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AuditConfigServiceTests.A_request_with_no_resolved_tenant_has_no_overrides_to_read", + "milliseconds": 7, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.ThePlatformSentinelRowIsInvisibleToEveryTenant", - "milliseconds": 22, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AuditConfigServiceTests.A_tenant_never_sees_another_tenants_overrides", + "milliseconds": 50, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.TheRetentionDeleteByThePlatformRoleSucceeds", - "milliseconds": 4, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AuditConfigServiceTests.An_operation_with_no_row_keeps_its_declared_tier", + "milliseconds": 140, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.TheRuntimeRoleCannotMutateTheLog", - "milliseconds": 19, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AuditConfigServiceTests.An_override_cannot_remove_a_MUST", + "milliseconds": 13, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.TheSentinelCannotBeProvisionedAsATenant", - "milliseconds": 7, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AuditConfigServiceTests.An_override_silences_a_SHOULD_operation", + "milliseconds": 112, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.TheServerDefaultsFillARowTheStoreDidNotWrite", - "milliseconds": 8, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AuditConfigServiceTests.The_cache_family_is_the_one_Standards_20_registers", + "milliseconds": 2, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.TheTenantScopeHatchWidensTheReadAcrossOrganizations", - "milliseconds": 13, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AuditConfigServiceTests.The_override_read_names_its_tenant_where_row_security_would_not", + "milliseconds": 145, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.TruncateIsRefusedEvenForTheOwner", - "milliseconds": 7, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.AuditConfigServiceTests.The_override_staleness_bound_is_the_one_Standards_20_states", + "milliseconds": 1, + "source": "p031-hosted-ordinary-8" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditConfigServiceTests.The_projection_outlives_the_cache_implementations_own_default", + "milliseconds": 55, + "source": "p031-hosted-ordinary-7" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditPipelineTests.A_MUST_row_that_cannot_be_written_takes_its_business_write_down_with_it", + "milliseconds": 493, + "source": "p031-hosted-ordinary-10" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditPipelineTests.Audit_Classification_Does_Not_Read_The_Database_On_The_Request_Path", + "milliseconds": 841, + "source": "p031-hosted-ordinary-5" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditPipelineTests.Audit_Survives_Transaction_Rollback", + "milliseconds": 825, + "source": "p031-hosted-ordinary-0" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditPipelineTests.MustClass_Audit_Writes_Share_The_Business_Transaction", + "milliseconds": 1262, + "source": "p031-hosted-ordinary-8" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditPipelineTests.The_host_mapping_row_carries_the_state_it_changed", + "milliseconds": 1861, + "source": "p031-hosted-ordinary-11" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditPipelineTests.The_row_carries_the_snapshot_the_interceptor_captured", + "milliseconds": 1269, + "source": "p031-hosted-ordinary-10" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditPipelineTests.The_row_carries_the_tenant_the_transaction_announced", + "milliseconds": 3311, + "source": "p031-hosted-ordinary-9" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.ARedactingUpdateByThePlatformRoleSucceeds", + "milliseconds": 87, + "source": "p031-hosted-ordinary-9" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.AnOrganizationScopedRowNeedsBothAnnouncements", + "milliseconds": 50, + "source": "p031-hosted-ordinary-6" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.AnOrganizationScopedSessionReadsItsOwnRowsAndTheTenantWideOnes", + "milliseconds": 40, + "source": "p031-hosted-ordinary-5" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.AuditConfigKeepsItsForeignKeyToTenants", + "milliseconds": 23, + "source": "p031-hosted-ordinary-3" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.AuditLogCarriesNoForeignKeyToTenants", + "milliseconds": 69, + "source": "p031-hosted-ordinary-4" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.TheClosedSetColumnsRejectAValueOutsideTheirCheck", + "milliseconds": 28, + "source": "p031-hosted-ordinary-10" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.TheCompositeKeyAdmitsTheCommitInDoubtPairAndNothingElse", + "milliseconds": 45, + "source": "p031-hosted-ordinary-9" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.TheOwnerIsStoppedOnlyByTheTrigger", + "milliseconds": 64, + "source": "p031-hosted-ordinary-11" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.ThePlatformRoleCannotUpdateAnythingElse", + "milliseconds": 278, + "source": "p031-hosted-ordinary-6" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.ThePlatformRoleHoldsExactlyTheSixColumnUpdateGrant", + "milliseconds": 34, + "source": "p031-hosted-ordinary-11" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.ThePlatformSentinelRowIsInvisibleToEveryTenant", + "milliseconds": 54, + "source": "p031-hosted-ordinary-3" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.TheRetentionDeleteByThePlatformRoleSucceeds", + "milliseconds": 39, + "source": "p031-hosted-ordinary-1" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.TheRuntimeRoleCannotMutateTheLog", + "milliseconds": 68, + "source": "p031-hosted-ordinary-2" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.TheSentinelCannotBeProvisionedAsATenant", + "milliseconds": 40, + "source": "p031-hosted-ordinary-6" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.TheServerDefaultsFillARowTheStoreDidNotWrite", + "milliseconds": 20, + "source": "p031-hosted-ordinary-1" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.TheTenantScopeHatchWidensTheReadAcrossOrganizations", + "milliseconds": 59, + "source": "p031-hosted-ordinary-7" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditSchemaTests.TruncateIsRefusedEvenForTheOwner", + "milliseconds": 37, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.A_best_effort_failure_is_logged_and_dropped", - "milliseconds": 32, - "source": "local-ordinary-scaled" + "milliseconds": 72, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.A_best_effort_write_swallows_a_data_source_that_cannot_be_built", - "milliseconds": 3, - "source": "local-ordinary-scaled" + "milliseconds": 7, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.A_capture_of_another_entity_type_does_not_reach_the_row", - "milliseconds": 33, - "source": "local-ordinary-scaled" + "milliseconds": 48, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.A_duplicate_on_the_standalone_re_write_is_positive_evidence_and_is_swallowed", - "milliseconds": 45, - "source": "local-ordinary-scaled" + "milliseconds": 146, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.A_durable_duplicate_leaves_the_check_healthy", - "milliseconds": 30, - "source": "local-ordinary-scaled" + "milliseconds": 78, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.A_failure_the_store_cannot_translate_is_still_Critical_counted_and_unhealthy", - "milliseconds": 8, - "source": "local-ordinary-scaled" + "milliseconds": 34, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.A_later_standalone_write_clears_the_check", - "milliseconds": 33, - "source": "local-ordinary-scaled" + "milliseconds": 66, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.A_refused_insert_throws_so_the_business_write_rolls_back", - "milliseconds": 29, - "source": "local-ordinary-scaled" + "milliseconds": 114, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.A_rolled_back_transaction_takes_its_audit_rows_with_it", - "milliseconds": 36, - "source": "local-ordinary-scaled" + "milliseconds": 136, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.A_standalone_failure_is_Critical_counted_and_leaves_the_check_unhealthy", - "milliseconds": 44, - "source": "local-ordinary-scaled" + "milliseconds": 40, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.An_absorbed_inner_refusal_is_persisted_with_its_own_outcome", - "milliseconds": 44, - "source": "local-ordinary-scaled" + "milliseconds": 64, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.An_insert_followed_by_an_update_still_records_a_creation", - "milliseconds": 26, - "source": "local-ordinary-scaled" + "milliseconds": 38, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.An_update_followed_by_a_delete_records_that_the_row_is_gone", - "milliseconds": 57, - "source": "local-ordinary-scaled" + "milliseconds": 373, + "source": "p031-hosted-ordinary-7" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.Non_tenant_identifiers_are_refused_on_the_standalone_paths", + "milliseconds": 40, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.Several_captures_of_one_entity_merge_earliest_before_and_latest_after", - "milliseconds": 32, - "source": "local-ordinary-scaled" + "milliseconds": 63, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.The_best_effort_write_actually_writes_the_row", - "milliseconds": 70, - "source": "local-ordinary-scaled" + "milliseconds": 290, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.The_durable_duplicate_is_counted_as_well_as_logged", - "milliseconds": 38, - "source": "local-ordinary-scaled" + "milliseconds": 32, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.The_indeterminate_pair_is_two_rows_under_one_id", - "milliseconds": 39, - "source": "local-ordinary-scaled" + "milliseconds": 109, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.The_platform_scope_row_is_written_on_the_callers_connection", - "milliseconds": 9, - "source": "local-ordinary-scaled" + "milliseconds": 74, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.The_platform_scope_row_rolls_back_with_the_scope_that_wrote_it", - "milliseconds": 7, - "source": "local-ordinary-scaled" + "milliseconds": 43, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.The_row_takes_its_entity_id_from_the_captured_aggregate", - "milliseconds": 40, - "source": "local-ordinary-scaled" + "milliseconds": 179, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", @@ -2124,674 +3031,674 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.The_snapshot_columns_land_as_jsonb_and_the_diff_as_an_array", - "milliseconds": 36, - "source": "local-ordinary-scaled" + "milliseconds": 183, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.The_standalone_write_announces_both_session_variables", - "milliseconds": 60, - "source": "local-ordinary-scaled" + "milliseconds": 232, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.The_standalone_write_throws_when_the_row_cannot_be_written", - "milliseconds": 33, - "source": "local-ordinary-scaled" + "milliseconds": 66, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.Two_instances_of_one_type_under_one_intent_are_refused", - "milliseconds": 28, - "source": "local-ordinary-scaled" + "milliseconds": 128, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.WritePending_refuses_to_run_without_a_transaction", - "milliseconds": 4, - "source": "local-ordinary-scaled" + "milliseconds": 21, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.WritePending_sends_every_pending_row_in_one_round_trip", - "milliseconds": 38, - "source": "local-ordinary-scaled" + "milliseconds": 75, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.WritePending_writes_nothing_for_a_SHOULD_or_MAY_intent", - "milliseconds": 28, - "source": "local-ordinary-scaled" + "milliseconds": 123, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditStoreTests.WritePending_writes_one_row_per_MUST_intent_on_the_business_transaction", - "milliseconds": 71, - "source": "local-ordinary-scaled" + "milliseconds": 429, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditWorkflowTests.A_created_taxonomy_that_loses_bands_to_the_tracker_is_never_recorded_as_owning_the_rest", - "milliseconds": 442, - "source": "local-ordinary-scaled" + "milliseconds": 747, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditWorkflowTests.A_host_mapping_of_any_valid_length_commits_with_its_whole_key_on_the_row", - "milliseconds": 1479, - "source": "local-ordinary-scaled" + "milliseconds": 2894, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditWorkflowTests.A_partially_loaded_taxonomy_is_never_recorded_as_owning_only_what_was_loaded", - "milliseconds": 613, - "source": "local-ordinary-scaled" + "milliseconds": 722, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditWorkflowTests.A_refused_publication_is_recorded_against_its_subject_with_actor_and_correlation", - "milliseconds": 522, - "source": "local-ordinary-scaled" + "milliseconds": 884, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditWorkflowTests.A_removed_band_is_in_the_changes_of_the_persisted_row", - "milliseconds": 577, - "source": "local-ordinary-scaled" + "milliseconds": 1156, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditWorkflowTests.A_validation_refusal_writes_no_row_because_nothing_has_classified_it", - "milliseconds": 491, - "source": "local-ordinary-scaled" + "milliseconds": 1076, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditWorkflowTests.Replacing_a_live_content_type_is_one_row_about_the_successor", - "milliseconds": 507, - "source": "local-ordinary-scaled" + "milliseconds": 1008, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditWorkflowTests.Replacing_a_live_taxonomy_is_one_row_about_the_successor", - "milliseconds": 529, - "source": "local-ordinary-scaled" + "milliseconds": 3626, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.AuditWorkflowTests.The_bands_a_tenant_authors_are_in_the_row_that_records_the_taxonomy", - "milliseconds": 495, - "source": "local-ordinary-scaled" + "milliseconds": 860, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobAdmissionTests.A_held_start_COMMIT_acknowledgement_honors_the_SQL_deadline_with_an_unlimited_default", - "milliseconds": 5704, - "source": "local-ordinary-scaled" + "milliseconds": 6346, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobAdmissionTests.A_landed_start_with_a_dropped_COMMIT_acknowledgement_never_activates_a_receipt_or_restarts", - "milliseconds": 1133, - "source": "local-ordinary-scaled" + "milliseconds": 6386, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobAdmissionTests.A_post_acknowledgement_scope_disposal_fault_retains_the_committed_receipt_and_restores_context", - "milliseconds": 1103, - "source": "local-ordinary-scaled" + "milliseconds": 5869, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobAdmissionTests.A_preread_scope_disposal_fault_closes_its_actual_connection_and_cannot_start_an_attempt", - "milliseconds": 1073, - "source": "local-ordinary-scaled" + "milliseconds": 8233, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobAdmissionTests.A_routing_claim_spends_no_attempt_and_admission_commits_before_any_business_construction", - "milliseconds": 1930, - "source": "local-ordinary-scaled" + "milliseconds": 11502, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobAdmissionTests.A_throwing_Activity_stopped_observer_cannot_replace_a_confirmed_start_or_prevent_restoration", - "milliseconds": 2991, - "source": "local-ordinary-scaled" + "milliseconds": 8371, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobAdmissionTests.Closing_the_runtime_gate_during_the_actual_application_row_lock_spends_no_attempt", - "milliseconds": 1261, - "source": "local-ordinary-scaled" + "milliseconds": 4032, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobAdmissionTests.Competing_old_and_current_real_routing_claims_commit_exactly_one_start", - "milliseconds": 1177, - "source": "local-ordinary-scaled" + "milliseconds": 6739, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobAdmissionTests.DTO_construction_and_attempt_ID_factory_cannot_open_ordinary_or_privileged_work", - "milliseconds": 2379, - "source": "local-ordinary-scaled" + "milliseconds": 7624, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobAdmissionTests.Exact_framework_requests_outside_their_capability_are_refused_before_framework_handler_construction", - "milliseconds": 1035, - "source": "local-ordinary-scaled" + "milliseconds": 1967, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobAdmissionTests.Expiry_during_an_actual_row_lock_wait_spends_no_attempt", - "milliseconds": 5202, - "source": "local-ordinary-scaled" + "milliseconds": 8569, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobAdmissionTests.Invalid_scope_or_typed_envelope_cannot_construct_business_or_spend_an_attempt", - "milliseconds": 4530, - "source": "local-ordinary-scaled" + "milliseconds": 7549, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobAdmissionTests.The_preread_is_physically_readonly_RLS_scoped_and_framework_authority_is_sticky", - "milliseconds": 1172, - "source": "local-ordinary-scaled" + "milliseconds": 10535, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobAdmissionTests.Unready_early_stale_and_capacity_unavailable_callbacks_spend_no_attempt", - "milliseconds": 8451, - "source": "local-ordinary-scaled" + "milliseconds": 16794, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobApplicationSourceTests.A_disposal_request_retains_the_actual_source_until_both_job_and_messaging_work_clean_up", - "milliseconds": 953, - "source": "local-ordinary-scaled" + "milliseconds": 1815, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobApplicationSourceTests.Actual_job_inventory_fills_the_supported_pool_and_only_explicit_headroom_admits_unrelated_connections", - "milliseconds": 7695, - "source": "local-ordinary-scaled" + "milliseconds": 11971, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobApplicationSourceTests.Actual_main_and_audit_helpers_share_two_slots_and_clean_SQL_failure_permits_the_next_intent", - "milliseconds": 1082, - "source": "local-ordinary-scaled" + "milliseconds": 1684, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobApplicationSourceTests.Cache_waiter_timeout_retains_actual_connection_cleanup_and_dirty_cleanup_seals_replacement", - "milliseconds": 6957, - "source": "local-ordinary-scaled" + "milliseconds": 7296, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBridgeFaultTests.Created_but_uninitialized_stock_rows_and_queued_but_unacknowledged_rows_remain_repairable", - "milliseconds": 1531, - "source": "local-ordinary-scaled" + "milliseconds": 3419, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBridgeFaultTests.Rolled_back_authoritative_intent_never_becomes_a_bridge_obligation", - "milliseconds": 1029, - "source": "local-ordinary-scaled" + "milliseconds": 2298, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBridgeTests.A_synthetic_native_join_timer_fault_retains_the_owner_after_its_observer_returns", - "milliseconds": 1254, - "source": "local-ordinary-scaled" + "milliseconds": 2075, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBridgeTests.Acknowledgement_rechecks_database_expiry_after_an_actual_row_lock_wait", - "milliseconds": 3268, - "source": "local-ordinary-scaled" + "milliseconds": 3480, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBridgeTests.Actual_bridge_ACK_classifies_old_hint_before_old_expired_token_and_never_calls_unmarked_first_ever", - "milliseconds": 4547, - "source": "local-ordinary-scaled" + "milliseconds": 23271, + "source": "pr38-df-1-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBridgeTests.Actual_bridge_status_cleanup_must_return_before_visible_ACK_or_repair_accounting", - "milliseconds": 2897, - "source": "local-ordinary-scaled" + "milliseconds": 4934, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBridgeTests.Actual_mismatch_deferral_with_an_expired_fence_is_not_counted_as_a_durable_deferral", - "milliseconds": 1016, - "source": "local-ordinary-scaled" + "milliseconds": 1984, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBridgeTests.Actual_native_create_rechecks_gate_closure_after_native_thread_start", - "milliseconds": 4247, - "source": "local-ordinary-scaled" + "milliseconds": 9033, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBridgeTests.Actual_native_return_with_a_replaced_bridge_fence_counts_no_ACK_or_repair", - "milliseconds": 1129, - "source": "local-ordinary-scaled" + "milliseconds": 2272, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBridgeTests.Callback_admission_can_commit_before_its_matching_bridge_acknowledgement", - "milliseconds": 1448, - "source": "local-ordinary-scaled" + "milliseconds": 1802, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBridgeTests.Catchable_thread_start_failure_preserves_the_already_live_operation_and_its_observer", - "milliseconds": 1152, - "source": "local-ordinary-scaled" + "milliseconds": 1785, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBridgeTests.Expired_and_replaced_bridge_tokens_cannot_acknowledge_current_work", - "milliseconds": 1149, - "source": "local-ordinary-scaled" + "milliseconds": 3127, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBridgeTests.Four_actual_synchronous_calls_are_retained_across_finite_shutdown_wait_without_a_fifth_start", - "milliseconds": 1447, - "source": "local-ordinary-scaled" + "milliseconds": 9152, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBridgeTests.Future_intent_is_handed_to_the_real_stock_client_once_then_checked_after_due_plus_grace", - "milliseconds": 1338, - "source": "local-ordinary-scaled" + "milliseconds": 1883, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBridgeTests.Hangfire_Wakeups_Are_Recoverable_And_Generation_Fenced", - "milliseconds": 4268, - "source": "local-ordinary-scaled" + "milliseconds": 7828, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBridgeTests.Native_completion_cannot_release_a_slot_before_the_actual_owned_startup_task_returns", - "milliseconds": 1415, - "source": "local-ordinary-scaled" + "milliseconds": 4076, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBridgeTests.Separate_bridge_instances_claim_distinct_obligations_without_waiting_on_each_other", - "milliseconds": 1107, - "source": "local-ordinary-scaled" + "milliseconds": 1476, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBridgeTests.Stop_retains_queued_or_unpublished_startup_and_refuses_its_late_native_start", - "milliseconds": 2416, - "source": "local-ordinary-scaled" + "milliseconds": 5731, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBridgeTests.Unready_definitions_defer_durably_without_vendor_calls_or_attempts", - "milliseconds": 2217, - "source": "local-ordinary-scaled" + "milliseconds": 3746, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBusinessTests.A_landed_business_commit_without_acknowledgement_requires_reconciliation", - "milliseconds": 1317, - "source": "local-ordinary-scaled" + "milliseconds": 1799, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBusinessTests.Acknowledged_business_success_survives_actual_cleanup_and_Activity_observer_faults", - "milliseconds": 2454, - "source": "local-ordinary-scaled" + "milliseconds": 7842, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBusinessTests.Actual_transaction_reannouncement_invalidates_the_bound_completion", - "milliseconds": 2208, - "source": "local-ordinary-scaled" + "milliseconds": 4044, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBusinessTests.Admission_acknowledgement_is_published_while_actual_scope_cleanup_is_still_pending", - "milliseconds": 1066, - "source": "local-ordinary-scaled" + "milliseconds": 4419, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBusinessTests.BackgroundJob_Execution_Restores_Tenant_And_Trace", - "milliseconds": 5479, - "source": "local-ordinary-scaled" + "milliseconds": 7852, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBusinessTests.Business_aggregate_child_job_outbox_and_MUST_audit_share_the_final_completion", - "milliseconds": 10787, - "source": "local-ordinary-scaled" + "milliseconds": 27466, + "source": "pr38-df-2-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBusinessTests.Direct_and_fresh_scope_nested_escapes_refuse_before_any_second_transaction", - "milliseconds": 1107, - "source": "local-ordinary-scaled" + "milliseconds": 2384, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBusinessTests.Final_completion_samples_fresh_time_after_the_actual_row_lock_wait", - "milliseconds": 3749, - "source": "local-ordinary-scaled" + "milliseconds": 6241, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobBusinessTests.Preflight_refuses_stale_authority_before_constructing_the_handler", - "milliseconds": 4305, - "source": "local-ordinary-scaled" + "milliseconds": 7736, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobCapacityAdmissionTests.A_downgrade_preserves_existing_occupancy_and_each_new_admission_reads_the_current_source_answer", - "milliseconds": 1693, - "source": "local-ordinary-scaled" + "milliseconds": 4621, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobCapacityAdmissionTests.A_reservation_INSERT_fault_rolls_back_the_already_staged_attempt_and_summary", - "milliseconds": 1264, - "source": "local-ordinary-scaled" + "milliseconds": 1930, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobCapacityAdmissionTests.Admission_intersects_optional_Hard_projection_with_operational_ceiling_before_counting_a_start", - "milliseconds": 12381, - "source": "local-ordinary-scaled" + "milliseconds": 38291, + "source": "pr38-df-1-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobCapacityAdmissionTests.Business_effects_MUST_completion_and_exact_reservation_release_share_one_commit", - "milliseconds": 4289, - "source": "local-ordinary-scaled" + "milliseconds": 7623, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobCapacityAdmissionTests.Caller_cancellation_retains_the_actual_limit_task_and_cannot_admit_after_its_late_return", - "milliseconds": 1153, - "source": "local-ordinary-scaled" + "milliseconds": 1313, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobCapacityAdmissionTests.Expired_unknown_external_occupancy_still_blocks_its_tenant_while_another_tenant_progresses", - "milliseconds": 3710, - "source": "local-ordinary-scaled" + "milliseconds": 3054, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobCapacityAdmissionTests.Faulted_or_canceled_limit_lookup_spends_no_attempt_and_never_constructs_business", - "milliseconds": 2151, - "source": "local-ordinary-scaled" + "milliseconds": 3359, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobCapacityAdmissionTests.Two_independent_hosts_and_organizations_count_the_reservation_committed_during_the_actual_mutex_wait", - "milliseconds": 3194, - "source": "local-ordinary-scaled" + "milliseconds": 4346, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.A_lost_quarantine_rollback_response_never_becomes_an_observed_empty_queue", - "milliseconds": 1003, - "source": "local-ordinary-scaled" + "milliseconds": 1554, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.A_quarantine_read_requires_actual_rollback_acknowledgement_before_publishing_false", - "milliseconds": 886, - "source": "local-ordinary-scaled" + "milliseconds": 1653, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.A_refresh_fault_keeps_the_last_sample_until_another_successful_observation", - "milliseconds": 15358, - "source": "local-ordinary-scaled" + "milliseconds": 7995, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Acknowledged_terminal_durability_survives_held_or_failed_actual_scope_cleanup_while_other_control_progresses", - "milliseconds": 3044, - "source": "local-ordinary-scaled" + "milliseconds": 5732, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Actual_control_queries_seek_future_backlog_for_idle_and_partial_quanta_and_detect_volatile_cutoff", - "milliseconds": 58282, - "source": "local-ordinary-scaled" + "milliseconds": 147596, + "source": "pr38-b-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Actual_fenced_job_witness_refuses_every_draft_or_pair_substitution_and_rolls_back_state", - "milliseconds": 18341, - "source": "local-ordinary-scaled" + "milliseconds": 72175, + "source": "pr38-b-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Actual_quarantine_observation_seeks_its_partial_index_and_detects_its_absence", - "milliseconds": 3298, - "source": "local-ordinary-scaled" + "milliseconds": 3964, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Actual_renewal_owner_counts_physical_ACK_separately_from_original_locked_history_without_reopening_permission", - "milliseconds": 2887, - "source": "local-ordinary-scaled" + "milliseconds": 4362, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Actual_retry_owner_counts_ACK_or_locked_confirmation_once_but_never_a_later_owner", - "milliseconds": 29236, - "source": "local-ordinary-scaled" + "milliseconds": 18853, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Actual_terminal_no_start_selection_seeks_future_audit_backlog_and_detects_volatile_cutoff", - "milliseconds": 20286, - "source": "local-ordinary-scaled" + "milliseconds": 58772, + "source": "pr38-df-2-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Actual_terminal_owner_counts_committed_audit_after_scope_cleanup_even_when_cleanup_refuses_release", - "milliseconds": 3156, - "source": "local-ordinary-scaled" + "milliseconds": 4105, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Admission_probe_waits_for_the_actual_original_row_lock_before_interpreting_commit_or_rollback", - "milliseconds": 2978, - "source": "local-ordinary-scaled" + "milliseconds": 5466, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Another_instance_parks_expired_grouped_work_without_cleanup_and_keeps_its_occupancy_counted", - "milliseconds": 1398, - "source": "local-ordinary-scaled" + "milliseconds": 2552, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.BackgroundJob_Retries_And_Terminal_Faults_Preserve_Progress", - "milliseconds": 1985, - "source": "local-ordinary-scaled" + "milliseconds": 2512, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Batch_renewal_ignores_small_control_quantum_returns_actual_DB_time_and_never_resurrects_expiry", - "milliseconds": 1519, - "source": "local-ordinary-scaled" + "milliseconds": 3714, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Expired_routing_with_zero_or_prior_attempts_keeps_its_generation_and_spends_no_start", - "milliseconds": 1728, - "source": "local-ordinary-scaled" + "milliseconds": 3392, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Explicit_tombstone_terminalizes_but_unknown_and_Pending_remain_deferred", - "milliseconds": 1140, - "source": "local-ordinary-scaled" + "milliseconds": 1906, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Failed_terminal_audit_backoff_releases_only_the_exact_request_and_advances_past_the_poison_head", - "milliseconds": 1475, - "source": "local-ordinary-scaled" + "milliseconds": 1907, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Invalid_never_started_org_job_terminalizes_with_one_actual_row_bound_MUST_and_no_causal_payload_access", - "milliseconds": 1656, - "source": "local-ordinary-scaled" + "milliseconds": 12839, + "source": "pr38-b-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Locked_admission_history_distinguishes_absence_from_original_or_peer_occupancy", - "milliseconds": 6021, - "source": "local-ordinary-scaled" + "milliseconds": 18033, + "source": "pr38-a-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Locked_probe_timeout_retains_uncertainty_and_does_not_claim_rollback", - "milliseconds": 1367, - "source": "local-ordinary-scaled" + "milliseconds": 1442, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Memory_health_reads_do_not_replace_a_held_control_observation_or_issue_more_queries", - "milliseconds": 3679, - "source": "local-ordinary-scaled" + "milliseconds": 3145, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Missing_terminal_catalogue_refuses_the_real_writer_and_the_bound_witness_cannot_be_reused_after_COMMIT", - "milliseconds": 1418, - "source": "local-ordinary-scaled" + "milliseconds": 4510, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Prebound_renewal_wait_expiry_retains_the_actual_held_COMMIT_and_late_unknown_cannot_reopen_permission", - "milliseconds": 12765, - "source": "local-ordinary-scaled" + "milliseconds": 6720, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Quarantine_observation_sees_other_tenants_and_unknown_definitions_without_payload_grants", - "milliseconds": 947, - "source": "local-ordinary-scaled" + "milliseconds": 1399, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Real_retry_COMMIT_ack_loss_reconciles_the_locked_new_generation_without_reissuing_control", - "milliseconds": 1153, - "source": "local-ordinary-scaled" + "milliseconds": 1867, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Real_terminal_COMMIT_ack_loss_locks_durable_completion_and_cannot_append_a_second_audit", - "milliseconds": 1206, - "source": "local-ordinary-scaled" + "milliseconds": 2929, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Renewal_remains_compatible_with_the_actual_parent_keyshare_held_by_an_uncommitted_child_INSERT", - "milliseconds": 1181, - "source": "local-ordinary-scaled" + "milliseconds": 2558, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Runtime_control_retains_the_original_unknown_COMMIT_cursor_after_a_fresh_probe_fails_with_positive_cleanup", - "milliseconds": 2476, - "source": "local-ordinary-scaled" + "milliseconds": 2393, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobControlTests.Terminal_lock_wait_crossing_expiry_refuses_both_terminal_state_and_audit", - "milliseconds": 1943, - "source": "local-ordinary-scaled" + "milliseconds": 22670, + "source": "pr38-b-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.A_real_replacement_token_denies_the_old_exact_probe_without_erasing_its_acquisition_history", - "milliseconds": 2396, - "source": "local-ordinary-scaled" + "milliseconds": 2177, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Acknowledged_arm_cannot_open_provider_scope_after_its_actual_sql_lease_window_expires_without_a_timer", - "milliseconds": 16285, - "source": "local-ordinary-scaled" + "milliseconds": 8103, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Actual_app_checkpoints_preserve_canonical_bytes_and_release_only_the_recorded_completed_attempt", - "milliseconds": 7084, - "source": "local-ordinary-scaled" + "milliseconds": 14381, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Actual_app_finalize_admission_and_owner_preserve_selected_facts_without_reserving_or_reexecuting_external_work", - "milliseconds": 6322, - "source": "local-ordinary-scaled" + "milliseconds": 7058, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Actual_app_reader_preserves_the_selected_policy_and_rejects_projected_partial_or_conflicting_facts", - "milliseconds": 8120, - "source": "local-ordinary-scaled" + "milliseconds": 13295, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Actual_clean_permanent_Prepare_survives_expiry_but_cannot_clear_a_replaced_owner", - "milliseconds": 23684, - "source": "local-ordinary-scaled" + "milliseconds": 18119, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Actual_invalid_envelope_read_requests_exact_terminal_without_another_admission", - "milliseconds": 17577, - "source": "local-ordinary-scaled" + "milliseconds": 29189, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Actual_native_NoPlan_owner_requests_terminal_cleanup_and_one_MUST_without_another_attempt", - "milliseconds": 76466, - "source": "local-ordinary-scaled" + "milliseconds": 43978, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Actual_no_start_reader_preserves_a_stored_permanent_selection_before_exhaustion_without_inventing_provider_facts", - "milliseconds": 1402, - "source": "local-ordinary-scaled" + "milliseconds": 1761, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Actual_recovery_acquisition_preserves_expired_original_ledger_without_new_counted_attempt_or_execute_permission", - "milliseconds": 2350, - "source": "local-ordinary-scaled" + "milliseconds": 1718, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Actual_sixth_repeatable_outcome_reader_preserves_the_completed_state_and_exhaustion_reason", - "milliseconds": 4483, - "source": "local-ordinary-scaled" + "milliseconds": 7508, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", @@ -2802,20 +3709,20 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Admission_and_prepare_retain_the_actual_activity_when_start_throws_before_returning", - "milliseconds": 2133, - "source": "local-ordinary-scaled" + "milliseconds": 4022, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Armed_recovery_refuses_no_start_and_preserves_committed_facts_over_a_conflicting_later_report", - "milliseconds": 7978, - "source": "local-ordinary-scaled" + "milliseconds": 23347, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.BackgroundJob_Finalization_Retries_Are_Bounded", - "milliseconds": 19563, - "source": "local-ordinary-scaled" + "milliseconds": 23900, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", @@ -2826,8 +3733,8 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Closed_duplicate_prepare_has_no_own_commit_history_and_cannot_create_a_history_origin", - "milliseconds": 1138, - "source": "local-ordinary-scaled" + "milliseconds": 1341, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", @@ -2838,302 +3745,302 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Execute_bridge_requires_the_exact_clean_acknowledged_arm_and_trusted_read_before_scope_construction", - "milliseconds": 7918, - "source": "local-ordinary-scaled" + "milliseconds": 27454, + "source": "pr38-df-1-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Explicit_retired_NoPlan_uses_actual_cleanup_and_one_MUST_without_an_app_definition", - "milliseconds": 5609, - "source": "local-ordinary-scaled" + "milliseconds": 11689, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.External_recovery_probe_cannot_reconstruct_authority_from_a_changed_or_substituted_descriptor", - "milliseconds": 11624, - "source": "local-ordinary-scaled" + "milliseconds": 22977, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Fresh_recovery_reads_absent_plan_and_records_no_start_without_inventing_a_provider_report", - "milliseconds": 2638, - "source": "local-ordinary-scaled" + "milliseconds": 1995, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Held_actual_terminal_app_scope_does_not_stop_independent_terminal_audit_and_is_joined_at_shutdown", - "milliseconds": 3141, - "source": "local-ordinary-scaled" + "milliseconds": 3627, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.History_never_publishes_before_the_actual_probe_rollback_ack_and_a_new_probe_cannot_rewrite_the_old_failure", - "milliseconds": 2784, - "source": "local-ordinary-scaled" + "milliseconds": 3202, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.History_reads_the_original_stamped_attempt_after_a_real_later_admission_replaces_current_attempt_and_generation", - "milliseconds": 3008, - "source": "local-ordinary-scaled" + "milliseconds": 4951, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Known_retry_fresh_recovery_can_schedule_positive_no_plan_no_start_after_the_original_deadline", - "milliseconds": 2391, - "source": "local-ordinary-scaled" + "milliseconds": 2090, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Known_retry_lost_commit_probe_distinguishes_exact_rollback_routing_and_a_new_admission", - "milliseconds": 10209, - "source": "local-ordinary-scaled" + "milliseconds": 13188, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Known_retry_refused_final_update_rolls_back_the_private_live_owner_handoff", - "milliseconds": 1259, - "source": "local-ordinary-scaled" + "milliseconds": 1596, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Known_retry_refuses_unresolved_nonrepeatable_or_expired_original_facts_without_a_handoff", - "milliseconds": 7742, - "source": "local-ordinary-scaled" + "milliseconds": 12871, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Known_retry_uses_actual_released_history_and_fixed_backoff_without_spending_an_attempt", - "milliseconds": 16322, - "source": "local-ordinary-scaled" + "milliseconds": 33919, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Locked_history_resolves_the_exact_lost_ack_without_reopening_stopped_work_or_rewriting_physical_history", - "milliseconds": 26454, - "source": "local-ordinary-scaled" + "milliseconds": 56020, + "source": "pr38-df-1-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Named_recovery_no_start_uses_its_exact_read_without_fabricating_provider_facts", - "milliseconds": 2358, - "source": "local-ordinary-scaled" + "milliseconds": 3616, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Named_writer_cancellation_closes_the_run_before_issuance_or_during_actual_activity_cleanup", - "milliseconds": 2189, - "source": "local-ordinary-scaled" + "milliseconds": 2994, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Named_writer_cannot_borrow_an_old_gates_known_rollback_and_a_new_gate_can_commit", - "milliseconds": 1231, - "source": "local-ordinary-scaled" + "milliseconds": 2918, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Named_writer_keeps_physical_ack_and_exact_resources_through_held_or_failed_scope_cleanup", - "milliseconds": 4656, - "source": "local-ordinary-scaled" + "milliseconds": 6019, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Named_writer_owns_activity_even_when_its_start_or_stop_observer_throws", - "milliseconds": 2309, - "source": "local-ordinary-scaled" + "milliseconds": 2983, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Named_writer_refuses_another_jobs_read_handle_before_spending_its_actual_gate", - "milliseconds": 1307, - "source": "local-ordinary-scaled" + "milliseconds": 1683, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Named_writer_retains_its_exact_unacknowledged_commit_when_postgres_committed_before_socket_loss", - "milliseconds": 2772, - "source": "local-ordinary-scaled" + "milliseconds": 3123, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Named_writer_stop_after_handler_before_commit_is_an_acknowledged_rollback_not_unknown_history", - "milliseconds": 2404, - "source": "local-ordinary-scaled" + "milliseconds": 2945, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Named_writers_use_distinct_app_transactions_and_only_actual_read_causal_facts", - "milliseconds": 2567, - "source": "local-ordinary-scaled" + "milliseconds": 3856, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.No_plan_request_refuses_a_committed_plan_or_an_expired_original_without_changing_history", - "milliseconds": 2384, - "source": "local-ordinary-scaled" + "milliseconds": 4670, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.No_plan_sixth_recovery_requests_exhaustion_without_spending_a_seventh_admission_or_releasing_capacity", - "milliseconds": 2696, - "source": "local-ordinary-scaled" + "milliseconds": 5489, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.No_plan_terminal_commit_loss_confirms_exact_history_without_rewriting_ack_or_a_second_audit", - "milliseconds": 4848, - "source": "local-ordinary-scaled" + "milliseconds": 10932, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.No_plan_terminal_request_lost_commit_distinguishes_the_exact_reason_from_rollback", - "milliseconds": 4540, - "source": "local-ordinary-scaled" + "milliseconds": 7712, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.No_plan_terminal_request_preserves_actual_prepare_refusal_before_no_start_release_or_audit", - "milliseconds": 3830, - "source": "local-ordinary-scaled" + "milliseconds": 6382, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.No_plan_terminal_store_waits_for_actual_no_start_then_commits_one_real_MUST_atomically", - "milliseconds": 5553, - "source": "local-ordinary-scaled" + "milliseconds": 12596, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Positive_repeatable_outcome_preserves_probe_count_until_the_next_counted_admission", - "milliseconds": 15236, - "source": "local-ordinary-scaled" + "milliseconds": 8462, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Post_handler_commit_admission_cannot_borrow_an_expired_database_lease", - "milliseconds": 41617, - "source": "local-ordinary-scaled" + "milliseconds": 28670, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Prepared_terminal_actual_commit_loss_requires_its_exact_claim_history_and_never_a_second_audit", - "milliseconds": 4925, - "source": "local-ordinary-scaled" + "milliseconds": 12664, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Prepared_terminal_rechecks_actual_occupancy_history_and_live_owner_after_acquisition", - "milliseconds": 4814, - "source": "local-ordinary-scaled" + "milliseconds": 9355, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Prepared_terminal_refusal_preserves_selected_success_and_commits_incomplete_with_one_real_MUST", - "milliseconds": 3524, - "source": "local-ordinary-scaled" + "milliseconds": 6952, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Production_prepare_and_outcome_parameters_preserve_the_inclusive_typed_byte_boundary", - "milliseconds": 6255, - "source": "local-ordinary-scaled" + "milliseconds": 12040, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Read_acknowledgement_requires_the_exact_candidate_recorded_by_its_actual_read_only_owner", - "milliseconds": 14047, - "source": "local-ordinary-scaled" + "milliseconds": 11889, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Read_cancellation_closes_the_run_even_before_issuance_or_during_actual_activity_cleanup", - "milliseconds": 2146, - "source": "local-ordinary-scaled" + "milliseconds": 2750, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Read_driver_retains_actual_scope_cleanup_and_never_publishes_a_handle_from_failed_cleanup", - "milliseconds": 6812, - "source": "local-ordinary-scaled" + "milliseconds": 39679, + "source": "pr38-b-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Real_external_acquisition_ack_loss_requires_a_clean_exact_probe_and_repeated_probes_share_one_receipt", - "milliseconds": 2392, - "source": "local-ordinary-scaled" + "milliseconds": 4359, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Reconcile_bridge_uses_actual_recovery_read_and_never_constructs_provider_for_already_decidable_history", - "milliseconds": 4757, - "source": "local-ordinary-scaled" + "milliseconds": 38069, + "source": "pr38-b-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Recovery_first_publication_requires_actual_probe_ack_and_cleanup_without_rebasing_its_observed_window", - "milliseconds": 52664, - "source": "local-ordinary-scaled" + "milliseconds": 27002, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Recovery_skips_a_live_job_lock_instead_of_claiming_or_interpreting_the_skipped_row_as_absence", - "milliseconds": 2377, - "source": "local-ordinary-scaled" + "milliseconds": 2647, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Retained_marker_cannot_confirm_a_rolled_back_selection_and_lost_ack_confirms_the_exact_selection", - "milliseconds": 8963, - "source": "local-ordinary-scaled" + "milliseconds": 18131, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Retired_prepared_selected_outcome_survives_actual_finalize_admission_and_one_bypass_MUST", - "milliseconds": 3778, - "source": "local-ordinary-scaled" + "milliseconds": 6390, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Retired_prepared_unarmed_cleanup_preserves_original_or_reused_plan_and_positive_prior_outcome", - "milliseconds": 6177, - "source": "local-ordinary-scaled" + "milliseconds": 8645, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Retired_selected_request_commit_loss_uses_exact_original_metadata_across_physical_TimeZones", - "milliseconds": 4187, - "source": "local-ordinary-scaled" + "milliseconds": 8146, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Retirement_defers_unknown_Pending_unresolved_and_live_owners_without_releasing_occupancy", - "milliseconds": 4884, - "source": "local-ordinary-scaled" + "milliseconds": 7563, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Retirement_positive_selection_passes_more_than_a_full_batch_of_earlier_unresolved_heads", - "milliseconds": 1590, - "source": "local-ordinary-scaled" + "milliseconds": 2121, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Running_beyond_the_original_deadline_and_grace_quarantines_without_proving_quiescence", - "milliseconds": 5836, - "source": "local-ordinary-scaled" + "milliseconds": 3506, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Sixth_reused_plan_admission_stopped_before_arm_commits_no_start_release_and_failure_selection", - "milliseconds": 5059, - "source": "local-ordinary-scaled" + "milliseconds": 6508, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Stored_selection_uses_fresh_policy_and_refuses_missing_or_early_repeatable_facts", - "milliseconds": 9232, - "source": "local-ordinary-scaled" + "milliseconds": 11839, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", @@ -3144,182 +4051,182 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Terminal_no_start_acquisition_lost_commit_never_publishes_a_rollback_or_changes_its_purpose", - "milliseconds": 2689, - "source": "local-ordinary-scaled" + "milliseconds": 7651, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Terminal_no_start_lost_commit_confirms_only_its_actual_issued_pair_without_rewriting_ack", - "milliseconds": 2985, - "source": "local-ordinary-scaled" + "milliseconds": 7114, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Terminal_no_start_release_refusal_rolls_back_the_preceding_marker", - "milliseconds": 1356, - "source": "local-ordinary-scaled" + "milliseconds": 16643, + "source": "pr38-b-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Terminal_no_start_uses_actual_fresh_purpose_and_app_history_without_a_contract_or_provider", - "milliseconds": 19186, - "source": "local-ordinary-scaled" + "milliseconds": 12404, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Terminal_storage_accepts_complete_actual_app_no_start_history", - "milliseconds": 3582, - "source": "local-ordinary-scaled" + "milliseconds": 4631, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Terminal_storage_distinguishes_unadmitted_retirement_from_invented_failure", - "milliseconds": 2731, - "source": "local-ordinary-scaled" + "milliseconds": 3885, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Terminal_storage_freezes_the_requested_reason_before_app_cleanup", - "milliseconds": 4387, - "source": "local-ordinary-scaled" + "milliseconds": 10070, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Terminal_storage_requires_complete_positive_no_start_history", - "milliseconds": 5745, - "source": "local-ordinary-scaled" + "milliseconds": 7667, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Terminal_witness_requires_actual_returned_profile_and_external_proof_to_agree", - "milliseconds": 4567, - "source": "local-ordinary-scaled" + "milliseconds": 5986, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Uninvokable_history_cannot_be_attached_to_foreign_actual_terminal_or_finalizer_descriptors", - "milliseconds": 1768, - "source": "local-ordinary-scaled" + "milliseconds": 2141, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Unresolved_final_park_refusal_rolls_back_shortening_and_counter_together", - "milliseconds": 1350, - "source": "local-ordinary-scaled" + "milliseconds": 1709, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Unresolved_lost_commit_has_exact_history_without_replaying_a_count_or_borrowing_a_successor", - "milliseconds": 30703, - "source": "local-ordinary-scaled" + "milliseconds": 26310, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Unresolved_stale_report_refuses_durable_known_facts_or_closed_authority", - "milliseconds": 5783, - "source": "local-ordinary-scaled" + "milliseconds": 15939, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Unresolved_status_paces_or_quarantines_without_outcome_release_or_another_admission", - "milliseconds": 11505, - "source": "local-ordinary-scaled" + "milliseconds": 37505, + "source": "pr38-b-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalCheckpointStoreTests.Unsuccessful_probes_count_once_running_preserves_count_and_sixth_failure_quarantines", - "milliseconds": 70512, - "source": "local-ordinary-scaled" + "milliseconds": 32263, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalIsolationTests.Actual_frame_disposal_under_external_denial_still_rolls_back_and_disposes_its_owned_transaction", - "milliseconds": 1677, - "source": "local-ordinary-scaled" + "milliseconds": 4100, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalIsolationTests.Concrete_cold_helpers_refuse_source_less_live_and_retained_external_flows_before_lazy_source_or_physical_SQL", - "milliseconds": 3302, - "source": "local-ordinary-scaled" + "milliseconds": 4996, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalIsolationTests.External_live_and_retained_flow_cannot_open_the_actual_app_unit_but_the_original_flow_remains_usable", - "milliseconds": 874, - "source": "local-ordinary-scaled" + "milliseconds": 1946, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalIsolationTests.Refused_external_complete_preserves_the_original_handle_for_real_commit_after_restoration", - "milliseconds": 1114, - "source": "local-ordinary-scaled" + "milliseconds": 1475, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobExternalIsolationTests.Refused_external_owner_failure_cannot_rollback_live_joiners_or_poison_the_original_unit", - "milliseconds": 872, - "source": "local-ordinary-scaled" + "milliseconds": 1185, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobLifecycleProjectionTests.Only_the_eight_named_columns_are_visible_and_an_extra_grant_is_detected", - "milliseconds": 862, - "source": "local-ordinary-scaled" + "milliseconds": 1264, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobLifecycleProjectionTests.Projection_does_not_grant_names_wider_reads_or_tenancy_mutation", - "milliseconds": 28, - "source": "local-ordinary-scaled" + "milliseconds": 62, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobLifecycleProjectionTests.Projection_grant_down_and_reapply_change_only_the_named_column_budget", - "milliseconds": 1032, - "source": "local-ordinary-scaled" + "milliseconds": 1579, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Actual_Outcome_ACK_settles_renewal_before_its_held_cleanup_can_release_the_native_identity", - "milliseconds": 73248, - "source": "local-ordinary-scaled" + "milliseconds": 48652, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Actual_Reconcile_entry_requires_its_fresh_recovery_window_after_an_expired_original_and_held_constructor", - "milliseconds": 55572, - "source": "local-ordinary-scaled" + "milliseconds": 27326, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Actual_acknowledged_recovery_renewal_extends_live_method_entry_but_cannot_resurrect_a_spent_window", - "milliseconds": 89359, - "source": "local-ordinary-scaled" + "milliseconds": 41312, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Actual_external_publication_uses_its_exact_native_stage_and_Prepare_ACK_does_not_end_renewal", - "milliseconds": 4507, - "source": "local-ordinary-scaled" + "milliseconds": 4369, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Actual_external_recovery_wakes_advance_once_preserve_history_and_fence_old_callbacks", - "milliseconds": 22187, - "source": "local-ordinary-scaled" + "milliseconds": 13504, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Actual_facade_native_wakeups_run_Prepare_provider_Outcome_and_fresh_Finalize", - "milliseconds": 43304, - "source": "local-ordinary-scaled" + "milliseconds": 38735, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Actual_facade_parks_expired_external_work_reconciles_or_uses_retained_facts_and_finalizes", - "milliseconds": 27537, - "source": "local-ordinary-scaled" + "milliseconds": 28677, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", @@ -3330,116 +4237,122 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Actual_native_recovery_owner_renews_past_old_deadlines_without_admission_or_another_Execute", - "milliseconds": 89746, - "source": "local-ordinary-scaled" + "milliseconds": 42508, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Actual_recovery_renewal_preserves_original_expired_ledger_and_uses_only_its_fresh_owner", - "milliseconds": 22907, - "source": "local-ordinary-scaled" + "milliseconds": 12032, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Actual_stock_recovery_counts_late_settlement_only_after_provider_and_private_cleanup", - "milliseconds": 33616, - "source": "local-ordinary-scaled" + "milliseconds": 17894, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Actual_stored_recovery_selection_repairs_the_early_finalize_hint_only_after_its_real_cleanup", - "milliseconds": 49506, - "source": "local-ordinary-scaled" + "milliseconds": 33241, + "source": "pr38-b-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Actual_typed_provider_method_rechecks_the_acknowledged_Arm_window_after_a_held_constructor", - "milliseconds": 17601, - "source": "local-ordinary-scaled" + "milliseconds": 13887, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.BackgroundJob_External_Recovery_Never_Assumes_Quiescence", - "milliseconds": 49702, - "source": "local-ordinary-scaled" + "milliseconds": 25405, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Either_real_MUST_audit_failure_rolls_back_domain_and_terminal_state_but_preserves_prior_provider_facts", - "milliseconds": 3435, - "source": "local-ordinary-scaled" + "milliseconds": 5328, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Expired_external_routing_is_repaired_in_both_pending_stages_without_spending_admission", - "milliseconds": 5863, - "source": "local-ordinary-scaled" + "milliseconds": 3516, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.External_capacity_refusal_is_durably_deferred_by_the_actual_control_owner_without_spending_an_attempt", - "milliseconds": 13241, - "source": "local-ordinary-scaled" + "milliseconds": 8941, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Genuine_sdk_and_provider_preserve_one_logical_effect_and_commit_domain_finalization_with_its_real_MUST_audits", - "milliseconds": 6917, - "source": "local-ordinary-scaled" + "milliseconds": 11752, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Native_Finalize_preserves_a_cleaned_permanent_decision_across_observer_join_but_respects_stop_and_owned_cancellation", - "milliseconds": 8080, - "source": "local-ordinary-scaled" + "milliseconds": 10548, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Native_Finalize_retry_rolls_back_the_first_nested_write_and_uses_fresh_authority_without_reexecuting_provider", - "milliseconds": 71879, - "source": "local-ordinary-scaled" + "milliseconds": 39796, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Native_NoPlan_keeps_a_cleaned_permanent_Prepare_decision_after_wait_closure_but_not_host_stop_or_owned_cancellation", - "milliseconds": 39920, - "source": "local-ordinary-scaled" + "milliseconds": 21812, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Native_completed_cancellation_survives_restart_and_independent_failure_is_not_reclassified", - "milliseconds": 235758, - "source": "p02b7-local-causal-retry" + "milliseconds": 112798, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Native_external_constructor_uses_the_long_external_wait_after_short_Prepare_finishes", - "milliseconds": 12703, - "source": "local-ordinary-scaled" + "milliseconds": 8827, + "source": "p031-hosted-ordinary-7" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Native_fixture_start_waits_for_previous_actual_cleanup_before_one_same_generation_hint", + "milliseconds": 3888, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Native_history_retries_an_actual_skipped_row_until_exact_confirmation", - "milliseconds": 4948, - "source": "local-ordinary-scaled" + "milliseconds": 19393, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Native_known_recovery_preserves_exact_policy_before_retry_or_failure_finalization", - "milliseconds": 197596, - "source": "local-ordinary-scaled" + "milliseconds": 100450, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Native_known_repeatable_outcome_retries_a_distinct_attempt_with_the_same_operation", - "milliseconds": 146499, - "source": "local-ordinary-scaled" + "milliseconds": 84764, + "source": "pr38-b-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Native_lost_checkpoint_ACK_uses_the_exact_issued_history_and_never_repeats_the_provider", - "milliseconds": 10832, - "source": "local-ordinary-scaled" + "milliseconds": 40537, + "source": "pr38-df-1-ordinary-10" }, { "assembly": "learnstack.tests.integration", @@ -3450,32 +4363,32 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Native_recovery_timer_initialization_keeps_host_stop_independent_and_requires_the_actual_handle", - "milliseconds": 85817, - "source": "local-ordinary-scaled" + "milliseconds": 45213, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Native_stop_returns_the_wrapper_before_a_held_external_constructor_really_cleans_up", - "milliseconds": 6427, - "source": "local-ordinary-scaled" + "milliseconds": 6862, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Native_transactional_pool_completes_at_the_app_source_floor_while_actual_external_reconcile_is_held", - "milliseconds": 36468, - "source": "local-ordinary-scaled" + "milliseconds": 32726, + "source": "pr38-df-1-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobPositiveSdkTests.Owned_external_retry_counts_only_its_acknowledged_or_exact_locked_original_disposition", - "milliseconds": 4885, - "source": "local-ordinary-scaled" + "milliseconds": 15484, + "source": "pr38-b-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.A_cold_empty_registry_observes_each_future_unsupported_obligation_without_a_deferred_marker", - "milliseconds": 5350, - "source": "local-ordinary-scaled" + "milliseconds": 7091, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", @@ -3486,62 +4399,62 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.A_held_actual_native_callback_preserves_durable_progress_and_both_sources_until_real_return", - "milliseconds": 3731, - "source": "local-ordinary-scaled" + "milliseconds": 3378, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.A_later_acquisitions_child_receipt_wins_without_attributing_its_ACK_to_the_original_attempt", - "milliseconds": 1543, - "source": "local-ordinary-scaled" + "milliseconds": 1599, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Actual_control_quarantine_observation_seeks_each_partial_index_and_detects_each_missing_index", - "milliseconds": 4044, - "source": "local-ordinary-scaled" + "milliseconds": 3868, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Actual_facade_start_after_final_admission_joins_when_stop_wins_the_parent_start_lock", - "milliseconds": 1441, - "source": "local-ordinary-scaled" + "milliseconds": 1419, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Actual_lifecycle_page_seeks_past_a_large_ineligible_prefix_without_rescanning_it", - "milliseconds": 1044, - "source": "local-ordinary-scaled" + "milliseconds": 1323, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Actual_observation_hash_matches_frozen_dotnet_manifests_across_schedules_policies_precision_and_session_formats", - "milliseconds": 1570, - "source": "local-ordinary-scaled" + "milliseconds": 2433, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Actual_recipient_cancellation_or_scope_cleanup_pins_both_sources_after_all_siblings_join", - "milliseconds": 5171, - "source": "local-ordinary-scaled" + "milliseconds": 8141, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Actual_recipient_scope_cleanup_failure_refuses_a_new_history_operation_even_after_positive_COMMIT_ACK", - "milliseconds": 1103, - "source": "local-ordinary-scaled" + "milliseconds": 1458, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Actual_runtime_fans_out_to_both_scopes_and_duplicate_native_ticks_create_no_extra_children", - "milliseconds": 6620, - "source": "local-ordinary-scaled" + "milliseconds": 5987, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Actual_vendor_transaction_blocks_nonkey_supersession_and_key_share_control_does_not", - "milliseconds": 2093, - "source": "local-ordinary-scaled" + "milliseconds": 2874, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", @@ -3552,68 +4465,68 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.An_expired_database_lease_does_not_reissue_a_locally_retained_recipient", - "milliseconds": 980, - "source": "local-ordinary-scaled" + "milliseconds": 2537, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.BackgroundJob_Recurrence_Is_Durable_And_Deduplicated", - "milliseconds": 1063, - "source": "local-ordinary-scaled" + "milliseconds": 1635, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Bootstrap_rejects_snapshot_volatility_drift_with_the_same_function_body", - "milliseconds": 2264, - "source": "local-ordinary-scaled" + "milliseconds": 2842, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Child_insert_or_final_receipt_refusal_rolls_back_both_writes", - "milliseconds": 4729, - "source": "local-ordinary-scaled" + "milliseconds": 2755, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Closed_recipient_gate_never_opens_an_application_owner_or_creates_a_child", - "milliseconds": 1070, - "source": "local-ordinary-scaled" + "milliseconds": 1357, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Confined_recipient_skip_rechecks_current_lifecycle_and_defers_a_restored_route", - "milliseconds": 2673, - "source": "local-ordinary-scaled" + "milliseconds": 4124, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Conflicting_same_revision_binary_cannot_materialize_or_fan_out_the_stored_manifest", - "milliseconds": 3530, - "source": "local-ordinary-scaled" + "milliseconds": 2552, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Construction_free_manifest_declarations_remain_valid_through_recipient_acquisition", - "milliseconds": 3174, - "source": "local-ordinary-scaled" + "milliseconds": 4780, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Corrupted_recipient_routing_cannot_reach_child_identity_creation", - "milliseconds": 16570, - "source": "local-ordinary-scaled" + "milliseconds": 10736, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Durable_recurrence_progresses_before_ticks_while_the_actual_control_generation_remains_drained", - "milliseconds": 14516, - "source": "local-ordinary-scaled" + "milliseconds": 8803, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Empty_inventory_completes_a_frozen_empty_cohort_without_fabricating_a_recipient", - "milliseconds": 1012, - "source": "local-ordinary-scaled" + "milliseconds": 1858, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", @@ -3624,26 +4537,26 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Future_activation_is_index_deferred_until_its_first_aligned_slot", - "milliseconds": 1037, - "source": "local-ordinary-scaled" + "milliseconds": 1291, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Higher_revision_compares_a_nonrepresentable_incumbent_activation_in_postgres", - "milliseconds": 3558, - "source": "local-ordinary-scaled" + "milliseconds": 3036, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Independent_sources_publish_only_one_acknowledged_recipient_claim_with_the_exact_stored_route", - "milliseconds": 1879, - "source": "local-ordinary-scaled" + "milliseconds": 2338, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Invalid_occurrence_facts_quarantine_only_the_locked_row_before_a_healthy_page", - "milliseconds": 1953, - "source": "local-ordinary-scaled" + "milliseconds": 2662, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", @@ -3654,50 +4567,50 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Invalid_stored_timestamp_is_quarantined_before_the_next_healthy_recurrence_quantum", - "milliseconds": 3557, - "source": "local-ordinary-scaled" + "milliseconds": 3860, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Native_replacement_rechecks_activation_after_real_manifest_or_pretrigger_hash_waits", - "milliseconds": 5471, - "source": "local-ordinary-scaled" + "milliseconds": 5872, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Native_revision_guard_down_up_and_independent_canonical_replacement_preserve_the_storage_shape", - "milliseconds": 1835, - "source": "local-ordinary-scaled" + "milliseconds": 1941, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.New_binary_materializes_old_frozen_target_and_policy_only_before_its_activation_boundary", - "milliseconds": 897, - "source": "local-ordinary-scaled" + "milliseconds": 1341, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Observation_checks_current_revision_without_rejecting_supported_frozen_history", - "milliseconds": 5478, - "source": "local-ordinary-scaled" + "milliseconds": 4024, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Observation_refuses_independently_invalid_frozen_facts_without_overflow_or_mutating_a_marker", - "milliseconds": 5212, - "source": "local-ordinary-scaled" + "milliseconds": 6410, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Occurrence_insert_failure_rolls_back_manifest_progress_and_a_clean_retry_converges", - "milliseconds": 918, - "source": "local-ordinary-scaled" + "milliseconds": 1680, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Older_binary_cannot_materialize_a_newer_manifest_or_advance_its_checkpoint", - "milliseconds": 911, - "source": "local-ordinary-scaled" + "milliseconds": 1034, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", @@ -3708,38 +4621,38 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Organization_pages_filter_only_after_raw_seek_and_recheck_the_parent_lifecycle", - "milliseconds": 1059, - "source": "local-ordinary-scaled" + "milliseconds": 1524, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Original_recurrence_COMMIT_with_lost_ACK_never_becomes_acknowledged_progress_from_a_returned_value", - "milliseconds": 4601, - "source": "local-ordinary-scaled" + "milliseconds": 3032, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Parent_start_already_admitted_before_child_stop_joins_without_false_cleanup_failure", - "milliseconds": 1081, - "source": "local-ordinary-scaled" + "milliseconds": 1293, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Pending_or_unknown_target_defers_without_advancing_its_slot_and_yields_to_healthy_work", - "milliseconds": 2053, - "source": "local-ordinary-scaled" + "milliseconds": 2693, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Real_native_manager_cannot_replace_the_newest_tick_with_an_obsolete_revision", - "milliseconds": 1198, - "source": "local-ordinary-scaled" + "milliseconds": 1366, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Recipient_Start_observer_fault_disposes_the_exact_owned_span_without_creating_a_child", - "milliseconds": 1075, - "source": "local-ordinary-scaled" + "milliseconds": 1370, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", @@ -3750,146 +4663,146 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Recipient_admission_samples_database_time_after_the_actual_row_lock_wait", - "milliseconds": 1134, - "source": "local-ordinary-scaled" + "milliseconds": 1411, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Recipient_claim_uses_its_pending_index_without_sorting_a_zero_jitter_backlog", - "milliseconds": 2998, - "source": "local-ordinary-scaled" + "milliseconds": 2857, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Recipient_exclusions_reject_invalid_or_unbounded_sets_before_source_resolution", - "milliseconds": 7, - "source": "local-ordinary-scaled" + "milliseconds": 346, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Recipient_history_resolves_real_COMMIT_loss_without_a_second_identity_or_invented_acknowledgement", - "milliseconds": 2675, - "source": "local-ordinary-scaled" + "milliseconds": 3432, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Recipient_history_yields_to_a_real_row_lock_and_observes_the_receipt_only_after_the_barrier", - "milliseconds": 1106, - "source": "local-ordinary-scaled" + "milliseconds": 1694, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Recipient_identity_factory_callback_is_revalidated_before_the_actual_INSERT", - "milliseconds": 2236, - "source": "local-ordinary-scaled" + "milliseconds": 3118, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Recipient_insert_fault_rolls_back_bounds_claim_and_checkpoint_before_a_clean_page_retry", - "milliseconds": 1124, - "source": "local-ordinary-scaled" + "milliseconds": 2549, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Recipient_resolution_never_changes_a_replaced_or_expired_acquisition", - "milliseconds": 4700, - "source": "local-ordinary-scaled" + "milliseconds": 3424, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Recipient_submission_commits_one_fixed_occurrence_child_and_reciprocal_receipt_without_constructing_feature_work", - "milliseconds": 2769, - "source": "local-ordinary-scaled" + "milliseconds": 2956, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Recipient_submission_rechecks_current_tenant_or_organization_eligibility_before_creating_a_child", - "milliseconds": 2628, - "source": "local-ordinary-scaled" + "milliseconds": 2875, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Registration_converges_across_sources_and_rejects_obsolete_or_conflicting_revisions", - "milliseconds": 915, - "source": "local-ordinary-scaled" + "milliseconds": 1302, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Stop_after_the_actual_recipient_receipt_UPDATE_rolls_back_the_child_and_receipt_before_COMMIT", - "milliseconds": 1101, - "source": "local-ordinary-scaled" + "milliseconds": 1552, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Stopped_parent_keeps_late_first_start_neutral_without_issuing_control_loops", - "milliseconds": 1075, - "source": "local-ordinary-scaled" + "milliseconds": 1448, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Stopped_recurrence_child_keeps_late_setup_neutral_without_issuing_work", - "milliseconds": 4364, - "source": "local-ordinary-scaled" + "milliseconds": 3338, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.Tenant_pages_bound_examined_keys_preserve_the_cohort_and_apply_the_declared_policy", - "milliseconds": 2521, - "source": "local-ordinary-scaled" + "milliseconds": 3211, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRecurrenceStoreTests.The_same_no_construction_assertion_detects_actual_target_request_and_handler_construction", - "milliseconds": 3620, - "source": "local-ordinary-scaled" + "milliseconds": 2696, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRoutingCleanupTests.A_queued_routing_read_rechecks_the_process_gate_at_actual_acquisition", - "milliseconds": 1657, - "source": "local-ordinary-scaled" + "milliseconds": 1605, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRoutingCleanupTests.Actual_SQL_refusal_confirms_cleanup_preserves_the_public_exception_and_can_route_after_restoration", - "milliseconds": 897, - "source": "local-ordinary-scaled" + "milliseconds": 1433, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRoutingCleanupTests.An_owned_success_returns_the_committed_claim_after_actual_cleanup_without_spending_an_attempt", - "milliseconds": 920, - "source": "local-ordinary-scaled" + "milliseconds": 837, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRoutingCleanupTests.An_unknown_definition_finishes_cleanly_without_claim_or_attempt", - "milliseconds": 855, - "source": "local-ordinary-scaled" + "milliseconds": 834, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRoutingCleanupTests.COMMIT_failure_never_publishes_the_candidate_claim_or_spends_an_attempt", - "milliseconds": 943, - "source": "local-ordinary-scaled" + "milliseconds": 1331, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRoutingCleanupTests.Cancellation_during_an_actual_routing_lock_wait_finishes_cleanup_and_closed_gate_refuses_fresh_SQL", - "milliseconds": 12275, - "source": "local-ordinary-scaled" + "milliseconds": 1347, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Actual_API_composition_keeps_both_sources_after_host_disposal_until_the_last_messaging_SQL_owner_joins", - "milliseconds": 2732, - "source": "local-ordinary-scaled" + "milliseconds": 3496, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Actual_common_database_outage_drains_all_pools_and_recovery_keeps_the_old_held_pool_closed_despite_its_spare_slot", - "milliseconds": 87104, - "source": "local-ordinary-scaled" + "milliseconds": 39914, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", @@ -3900,50 +4813,50 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Actual_metadata_heartbeat_fault_is_unhealthy_before_drain_and_only_stored_success_restores_health", - "milliseconds": 15103, - "source": "local-ordinary-scaled" + "milliseconds": 7678, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Actual_native_pool_named_none_keeps_aggregate_and_pool_metrics_distinct_without_private_labels", - "milliseconds": 1211, - "source": "local-ordinary-scaled" + "milliseconds": 2022, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Actual_runtime_projects_disjoint_bridge_repair_ACKs_without_reclassifying_unmarked_work", - "milliseconds": 2588, - "source": "local-ordinary-scaled" + "milliseconds": 6538, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Actual_stored_metadata_heartbeat_resets_the_owner_cutoff_and_the_exact_boundary_issues_no_SQL", - "milliseconds": 24252, - "source": "local-ordinary-scaled" + "milliseconds": 11373, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Admitted_native_business_renews_across_local_drain_and_commits_after_two_initial_leases", - "milliseconds": 71997, - "source": "local-ordinary-scaled" + "milliseconds": 32933, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Bootstrap_wait_and_stop_deadlines_retain_actual_SQL_and_late_publication_starts_no_pool", - "milliseconds": 5763, - "source": "local-ordinary-scaled" + "milliseconds": 4273, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Direct_real_composition_uses_one_pool_manifest_and_joins_all_owners_before_source_disposal", - "milliseconds": 6865, - "source": "local-ordinary-scaled" + "milliseconds": 4514, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Independent_bridge_repairs_a_due_delayed_job_while_the_actual_control_generation_is_held", - "milliseconds": 40298, - "source": "local-ordinary-scaled" + "milliseconds": 18503, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", @@ -3954,50 +4867,56 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Native_cache_waiter_timeout_joins_late_actual_auxiliary_cleanup_and_retains_disposal_faults", - "milliseconds": 47037, - "source": "local-ordinary-scaled" + "milliseconds": 22572, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Native_capacity_checkpoint_lost_ACK_uses_exact_committed_cleanup_and_release_history_without_a_second_start", - "milliseconds": 13274, - "source": "local-ordinary-scaled" + "milliseconds": 7070, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Native_capacity_completion_releases_with_business_child_outbox_and_MUST_even_when_business_ACK_is_lost", - "milliseconds": 3205, - "source": "local-ordinary-scaled" + "milliseconds": 3927, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Native_capacity_recovery_reprobes_settled_history_after_peer_takes_over_between_probe_and_acquisition", - "milliseconds": 98420, - "source": "local-ordinary-scaled" + "milliseconds": 47971, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Native_clean_control_lock_timeout_retains_the_permanent_refusal_until_terminal_audit", - "milliseconds": 21895, - "source": "local-ordinary-scaled" + "milliseconds": 10141, + "source": "p031-hosted-ordinary-0" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Native_completion_qualification_resends_the_locked_retry_generation_after_actual_rollback", + "milliseconds": 4623, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Native_final_completion_rechecks_database_expiry_after_its_real_app_row_lock_and_preserves_atomic_effects", - "milliseconds": 3397, - "source": "local-ordinary-scaled" + "milliseconds": 3680, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Native_framework_wait_retains_actual_cleanup_and_releases_its_slot_before_host_stop", - "milliseconds": 3977, - "source": "local-ordinary-scaled" + "milliseconds": 3074, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Native_grouped_admission_never_started_releases_only_after_actual_scope_and_private_callback_join", - "milliseconds": 27226, - "source": "local-ordinary-scaled" + "milliseconds": 14546, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", @@ -4008,2480 +4927,3188 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Native_grouped_rollback_checkpoints_only_after_original_auxiliary_and_private_callback_cleanup", - "milliseconds": 23480, - "source": "local-ordinary-scaled" + "milliseconds": 12303, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Native_host_stop_after_recovery_ACK_does_not_issue_capacity_checkpoint", - "milliseconds": 1436, - "source": "local-ordinary-scaled" + "milliseconds": 2797, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Native_host_stop_joins_issued_capacity_checkpoint_private_callback_before_disposing_sources", - "milliseconds": 2053, - "source": "local-ordinary-scaled" + "milliseconds": 2256, + "source": "p031-hosted-ordinary-6" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Native_lifecycle_qualification_resends_after_a_locked_hint_and_confirmed_handoff", + "milliseconds": 1910, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Native_lost_business_ACK_retains_the_actual_identity_until_a_locked_fresh_probe_resolves_without_duplicate_effects", - "milliseconds": 1747, - "source": "local-ordinary-scaled" + "milliseconds": 2073, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Native_rolled_back_capacity_admission_joins_after_peer_clears_the_original_routing_token", - "milliseconds": 1511, - "source": "local-ordinary-scaled" + "milliseconds": 1392, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Pooled_boundary_52_keeps_actual_expiration_checkout_after_caller_timeout_while_transactional_admission_progresses", - "milliseconds": 5851, - "source": "local-ordinary-scaled" + "milliseconds": 3505, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Supported_pool_serves_native_business_during_combined_actual_messaging_and_expiration_ownership", - "milliseconds": 4165, - "source": "local-ordinary-scaled" + "milliseconds": 5180, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobRuntimeFacadeTests.Terminal_audit_backlog_remains_faulted_beyond_two_leases_while_native_business_commits", - "milliseconds": 74045, - "source": "local-ordinary-scaled" + "milliseconds": 63396, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.A_pending_bypass_reason_cannot_be_rewritten_into_ordinary_completed_failure", - "milliseconds": 1138, - "source": "local-ordinary-scaled" + "milliseconds": 1488, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Actual_eligibility_plans_seek_partial_indexes_through_completed_and_future_backlog_and_detect_removal", - "milliseconds": 5599, - "source": "local-ordinary-scaled" + "milliseconds": 9336, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Attempt_ledger_and_summary_commit_together_and_missing_deferred_guards_are_detected", - "milliseconds": 954, - "source": "local-ordinary-scaled" + "milliseconds": 966, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Attempt_organization_must_mirror_its_job_even_when_the_tenant_read_hatch_reveals_the_parent", - "milliseconds": 14, - "source": "local-ordinary-scaled" + "milliseconds": 20, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Canonical_document_ddl_produces_the_same_job_inventory_as_the_migration", - "milliseconds": 475, - "source": "local-ordinary-scaled" + "milliseconds": 555, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Capacity_cleanup_forward_migration_reapplies_and_preserves_the_nonkey_count_lock", - "milliseconds": 1283, - "source": "local-ordinary-scaled" + "milliseconds": 1552, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Capacity_mutex_and_occupancy_are_shared_across_organizations_but_isolated_by_tenant", - "milliseconds": 31, - "source": "local-ordinary-scaled" + "milliseconds": 59, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Child_job_and_reciprocal_recipient_receipt_are_deferred_atomic_and_missing_guards_are_detected", - "milliseconds": 914, - "source": "local-ordinary-scaled" + "milliseconds": 1307, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Composite_foreign_keys_independently_refuse_cross_tenant_parent_attempt_and_reservation_links", - "milliseconds": 3321, - "source": "local-ordinary-scaled" + "milliseconds": 4639, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Control_manifests_and_recipient_routes_remain_immutable_below_the_acl", - "milliseconds": 2765, - "source": "local-ordinary-scaled" + "milliseconds": 4437, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Control_quarantine_presence_migration_reverses_only_its_three_indexes_and_reapplies_exactly", - "milliseconds": 1053, - "source": "local-ordinary-scaled" + "milliseconds": 1437, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Control_tables_have_force_rls_and_no_policies_or_app_platform_public_grants", - "milliseconds": 12, - "source": "local-ordinary-scaled" + "milliseconds": 16, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Every_authoritative_column_has_the_exact_app_dispatcher_platform_and_public_budget", - "milliseconds": 1562, - "source": "local-ordinary-scaled" + "milliseconds": 1927, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Every_control_and_vendor_table_is_nonempty_but_denies_application_select", - "milliseconds": 98, - "source": "local-ordinary-scaled" + "milliseconds": 150, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Expired_routing_or_execution_ownership_does_not_release_unresolved_occupancy", - "milliseconds": 1026, - "source": "local-ordinary-scaled" + "milliseconds": 1333, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.External_evidence_requires_exact_atomic_release_and_removing_only_the_deferred_guard_exposes_the_half_write", - "milliseconds": 6333, - "source": "local-ordinary-scaled" + "milliseconds": 7969, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.External_failure_policy_shape_is_explicit_and_SQL_NULL_cannot_bypass_it", - "milliseconds": 11924, - "source": "local-ordinary-scaled" + "milliseconds": 15731, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.External_finalization_selection_matches_actual_normal_ordinal_and_policy", - "milliseconds": 20415, - "source": "local-ordinary-scaled" + "milliseconds": 20462, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.External_plan_intent_outcome_and_quiescence_are_write_once_with_removed_guard_controls", - "milliseconds": 4853, - "source": "local-ordinary-scaled" + "milliseconds": 5603, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.External_policy_cannot_be_rewritten_but_the_removed_trigger_control_exposes_the_attack", - "milliseconds": 2018, - "source": "local-ordinary-scaled" + "milliseconds": 2796, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.External_policy_migration_refuses_legacy_failure_history_without_guessing_and_preserves_success", - "milliseconds": 3297, - "source": "local-ordinary-scaled" + "milliseconds": 3195, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.External_recovery_retries_only_unselected_failed_or_cancelled_outcomes", - "milliseconds": 9095, - "source": "local-ordinary-scaled" + "milliseconds": 11157, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Forged_release_has_no_positive_evidence_and_the_removed_guard_control_exposes_the_attack", - "milliseconds": 4788, - "source": "local-ordinary-scaled" + "milliseconds": 4659, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Forward_count_lock_correction_reverts_and_reapplies_only_its_function", - "milliseconds": 1291, - "source": "local-ordinary-scaled" + "milliseconds": 1967, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Fresh_down_reapply_restores_every_job_object_and_retains_existing_event_storage", - "milliseconds": 1573, - "source": "local-ordinary-scaled" + "milliseconds": 2245, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Idle_and_partial_quantums_seek_past_future_backlog_and_detect_a_volatile_clock", - "milliseconds": 11158, - "source": "local-ordinary-scaled" + "milliseconds": 26696, + "source": "pr38-df-2-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Immutable_facts_are_owner_enforced_and_the_same_attack_succeeds_with_only_its_guard_removed", - "milliseconds": 4622, - "source": "local-ordinary-scaled" + "milliseconds": 3957, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Initial_state_forgery_is_refused_even_for_the_owner_and_the_removed_guard_control_accepts_it", - "milliseconds": 3498, - "source": "local-ordinary-scaled" + "milliseconds": 3086, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Job_envelopes_refuse_foreign_tenant_and_mismatched_organization_backreferences", - "milliseconds": 29, - "source": "local-ordinary-scaled" + "milliseconds": 26, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.No_runtime_role_can_delete_or_truncate_job_history", - "milliseconds": 192, - "source": "local-ordinary-scaled" + "milliseconds": 293, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Null_organization_recipient_routes_are_deduplicated_for_the_same_occurrence", - "milliseconds": 958, - "source": "local-ordinary-scaled" + "milliseconds": 1226, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Ordinary_terminal_policy_requires_actual_app_finalization_and_rejects_reason_substitution", - "milliseconds": 4986, - "source": "local-ordinary-scaled" + "milliseconds": 6599, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Org_scoped_job_rows_preserve_cross_org_and_tenantwide_read_semantics", - "milliseconds": 41, - "source": "local-ordinary-scaled" + "milliseconds": 52, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Parameter_utf8_cap_is_inclusive_and_refuses_an_extra_multibyte_character", - "milliseconds": 1833, - "source": "local-ordinary-scaled" + "milliseconds": 2398, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Payloads_are_objects_with_unique_keys_before_any_runtime_deserializer", - "milliseconds": 2603, - "source": "local-ordinary-scaled" + "milliseconds": 3487, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Policy_down_refuses_every_governed_failure_and_preserves_grants_and_FORCE", - "milliseconds": 3216, - "source": "local-ordinary-scaled" + "milliseconds": 4217, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Policy_upgrade_validates_actual_predecessor_selection_and_atomic_release_without_rewriting_history", - "milliseconds": 4872, - "source": "local-ordinary-scaled" + "milliseconds": 5857, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Prepared_control_terminal_request_and_claim_leave_incomplete_false_until_actual_terminal_write", - "milliseconds": 6867, - "source": "local-ordinary-scaled" + "milliseconds": 6824, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Prepared_plan_cap_counts_utf8_bytes_and_preserves_the_inclusive_boundary", - "milliseconds": 981, - "source": "local-ordinary-scaled" + "milliseconds": 1259, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Quarantine_observation_migration_reverses_only_its_index_and_reapplies_exactly", - "milliseconds": 1189, - "source": "local-ordinary-scaled" + "milliseconds": 1291, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Real_role_denied_columns_refuse_before_any_row_is_read_or_changed", - "milliseconds": 71, - "source": "local-ordinary-scaled" + "milliseconds": 157, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Recurrence_and_logical_slots_preserve_database_microsecond_precision", - "milliseconds": 18, - "source": "local-ordinary-scaled" + "milliseconds": 20, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Six_quiescent_external_starts_and_six_finalize_starts_retain_twelve_receipts_and_refuse_a_seventh", - "milliseconds": 1851, - "source": "local-ordinary-scaled" + "milliseconds": 2676, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Sixth_normal_start_is_counted_and_a_seventh_cannot_create_a_receipt", - "milliseconds": 1294, - "source": "local-ordinary-scaled" + "milliseconds": 1995, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Successful_transactional_completion_releases_once_and_retains_the_durable_receipt", - "milliseconds": 1141, - "source": "local-ordinary-scaled" + "milliseconds": 2147, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Terminal_history_guard_down_restores_only_the_preceding_effective_function_and_reapplies_exactly", - "milliseconds": 970, - "source": "local-ordinary-scaled" + "milliseconds": 1111, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.The_app_denial_sweep_rejects_a_granted_empty_vendor_or_control_table", - "milliseconds": 1869, - "source": "local-ordinary-scaled" + "milliseconds": 3540, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.The_locking_grant_permits_a_real_lock_but_cannot_rewrite_the_capacity_group", - "milliseconds": 13, - "source": "local-ordinary-scaled" + "milliseconds": 21, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobStorageMigrationTests.Transactional_cleanup_and_release_are_atomic_and_migration_reversal_refuses_new_history", - "milliseconds": 2360, - "source": "local-ordinary-scaled" + "milliseconds": 4573, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobSubmissionTests.A_blocked_typed_INSERT_honors_the_SQL_budget_with_an_unlimited_default_and_poisons_before_absorption", - "milliseconds": 3588, - "source": "local-ordinary-scaled" + "milliseconds": 2299, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobSubmissionTests.A_child_submission_preserves_causal_human_and_incoming_event_while_keeping_parent_and_job_id_distinct", - "milliseconds": 2790, - "source": "local-ordinary-scaled" + "milliseconds": 1096, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobSubmissionTests.A_handler_refusal_or_exception_rolls_back_observed_job_business_and_audit", - "milliseconds": 2147, - "source": "local-ordinary-scaled" + "milliseconds": 2650, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobSubmissionTests.A_raw_or_orphan_announced_transaction_cannot_lend_producer_authority", - "milliseconds": 1752, - "source": "local-ordinary-scaled" + "milliseconds": 1031, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobSubmissionTests.A_real_SQL_fault_poisons_before_absorption_and_records_no_false_receipt", - "milliseconds": 1038, - "source": "local-ordinary-scaled" + "milliseconds": 1242, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobSubmissionTests.An_absorbed_descendant_refusal_poison_depends_on_actual_produced_work", - "milliseconds": 2121, - "source": "local-ordinary-scaled" + "milliseconds": 2610, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobSubmissionTests.BackgroundJob_Submission_Is_Transactional_And_Stamped", - "milliseconds": 2065, - "source": "local-ordinary-scaled" + "milliseconds": 2155, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobSubmissionTests.Foreign_module_wrong_scope_and_physical_readonly_submission_are_refused", - "milliseconds": 4114, - "source": "local-ordinary-scaled" + "milliseconds": 5110, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobSubmissionTests.Submission_rechecks_the_real_physical_generation_after_each_arbitrary_callback", - "milliseconds": 2832, - "source": "local-ordinary-scaled" + "milliseconds": 3646, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.BackgroundJobSubmissionTests.Typed_Pending_submission_commits_backlog_but_cannot_route_or_spend_an_attempt", - "milliseconds": 1284, - "source": "local-ordinary-scaled" + "milliseconds": 2366, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CourseContentAccessMigrationTests.Legacy_rows_are_restricted_without_changing_payload_pins_scope_or_publication_and_reapply_is_safe", - "milliseconds": 1760, - "source": "local-ordinary-scaled" + "milliseconds": 1425, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationCatalogTests.The_catalogue_answers_with_the_keys_the_tenant_declared", - "milliseconds": 102, - "source": "local-ordinary-scaled" + "milliseconds": 542, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationCatalogTests.Two_overlapping_bumps_do_not_lose_one", - "milliseconds": 57, - "source": "local-ordinary-scaled" + "milliseconds": 68, + "source": "p031-hosted-ordinary-9" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.CustomizationContentTypeQuotaTests.Different_key_registrations_serialize_at_the_last_slot_while_another_tenant_progresses", + "milliseconds": 1476, + "source": "p031-hosted-ordinary-6" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.CustomizationContentTypeQuotaTests.Revisions_and_retired_history_share_one_slot_until_its_last_nondeleted_revision_is_deleted", + "milliseconds": 1610, + "source": "p031-hosted-ordinary-5" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.CustomizationContentTypeQuotaTests.The_numeric_or_feature_unlimited_contract_bypasses_the_ceiling", + "milliseconds": 3188, + "source": "p031-hosted-ordinary-2" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.CustomizationContentTypeQuotaTests.The_real_feature_resolver_uses_its_five_key_catalog_floor_beside_the_builtin_then_refuses_the_sixth", + "milliseconds": 2947, + "source": "p031-hosted-ordinary-1" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.CustomizationContentTypeQuotaTests.The_registered_null_provider_keeps_its_accepted_unlimited_authoring_behavior", + "milliseconds": 988, + "source": "p031-hosted-ordinary-0" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.CustomizationContentTypeQuotaTests.Zero_allows_the_builtin_and_existing_revisions_but_no_new_custom_key", + "milliseconds": 1228, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationDefaultDeliveryTests.A_failed_MUST_audit_rolls_back_both_business_effects_and_inbox_completion", - "milliseconds": 3057, - "source": "local-ordinary-scaled" + "milliseconds": 3261, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationDefaultDeliveryTests.Reaccepting_the_exact_provisioning_fact_does_not_repeat_inbox_effect_or_audit", - "milliseconds": 2112, - "source": "local-ordinary-scaled" + "milliseconds": 3053, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationDefaultDeliveryTests.Real_Seeder_and_real_subscriber_serialize_on_each_builtin_concept", - "milliseconds": 8781, - "source": "local-ordinary-scaled" + "milliseconds": 19231, + "source": "pr38-df-1-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationDefaultDeliveryTests.Stored_backlog_and_fresh_provisioning_reach_both_real_subscribers", - "milliseconds": 4637, - "source": "local-ordinary-scaled" + "milliseconds": 8393, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationDefaultInitializationTests.An_untouched_concept_is_created_active_with_one_save_generation_and_must_audit", - "milliseconds": 2294, - "source": "local-ordinary-scaled" + "milliseconds": 4309, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationDefaultInitializationTests.Another_tenants_same_key_history_does_not_suppress_initialization", - "milliseconds": 2452, - "source": "local-ordinary-scaled" + "milliseconds": 2875, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationDefaultInitializationTests.Any_concept_history_preserves_every_field_and_generation_and_classifies_a_no_change_attempt", - "milliseconds": 10476, - "source": "local-ordinary-scaled" + "milliseconds": 13760, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationDefaultInitializationTests.Must_audit_refusal_rolls_back_the_active_root_and_generation", - "milliseconds": 2268, - "source": "local-ordinary-scaled" + "milliseconds": 3300, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationDefaultInitializationTests.Registration_and_initialization_share_the_concept_lock_in_both_winning_orders", - "milliseconds": 8774, - "source": "local-ordinary-scaled" + "milliseconds": 11048, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationProjectionTests.A_database_failure_is_not_converted_to_a_cache_miss_or_empty_projection", - "milliseconds": 918, - "source": "local-ordinary-scaled" + "milliseconds": 2066, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationProjectionTests.Accepted_source_depth_survives_snapshot_envelopes_for_unrelated_cold_and_partial_reads", - "milliseconds": 4236, - "source": "local-ordinary-scaled" + "milliseconds": 5687, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationProjectionTests.Admission_rejects_unannounced_frames_bad_pins_and_bad_locales_and_propagates_cancellation", - "milliseconds": 27, - "source": "local-ordinary-scaled" + "milliseconds": 38, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationProjectionTests.Api_and_seeder_roots_supply_the_same_scoped_guarded_contracts", - "milliseconds": 285, - "source": "local-ordinary-scaled" + "milliseconds": 99, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationProjectionTests.Cache_faults_degrade_to_complete_database_results_with_bounded_diagnostics", - "milliseconds": 89, - "source": "local-ordinary-scaled" + "milliseconds": 119, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationProjectionTests.Caller_cancellation_during_cache_get_or_set_propagates_without_factory_work", - "milliseconds": 74, - "source": "local-ordinary-scaled" + "milliseconds": 202, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationProjectionTests.Cold_warm_partial_and_locale_reads_use_two_or_one_select_and_never_a_shared_factory", - "milliseconds": 40, - "source": "local-ordinary-scaled" + "milliseconds": 159, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationProjectionTests.Composed_reader_returns_only_its_tenant_and_tracks_no_entities", - "milliseconds": 79, - "source": "local-ordinary-scaled" + "milliseconds": 113, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationProjectionTests.Concurrent_cold_callers_keep_their_own_transaction_and_awaited_loader", - "milliseconds": 55, - "source": "local-ordinary-scaled" + "milliseconds": 111, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationProjectionTests.Exact_batches_keep_deprecated_pins_and_distinguish_draft_deleted_absent_and_malformed", - "milliseconds": 2295, - "source": "local-ordinary-scaled" + "milliseconds": 3039, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationProjectionTests.Fatal_cache_failures_propagate_instead_of_attempting_recovery", - "milliseconds": 126, - "source": "local-ordinary-scaled" + "milliseconds": 123, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationProjectionTests.Independent_process_L1_maps_follow_the_same_durable_generation_without_events", - "milliseconds": 1253, - "source": "local-ordinary-scaled" + "milliseconds": 1129, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationProjectionTests.Missing_counter_distinguishes_empty_from_corrupt_nonempty_configuration", - "milliseconds": 927, - "source": "local-ordinary-scaled" + "milliseconds": 1258, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationProjectionTests.Nested_commands_share_the_dirty_reader_scope_and_cannot_fill_speculative_generation_keys", - "milliseconds": 981, - "source": "local-ordinary-scaled" + "milliseconds": 1621, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationProjectionTests.Publish_after_probe_with_a_partial_warm_hit_returns_the_loaded_generation_and_both_new_families", - "milliseconds": 1053, - "source": "local-ordinary-scaled" + "milliseconds": 918, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationProjectionTests.Rollback_only_without_a_customization_write_also_bypasses_warm_cache", - "milliseconds": 31, - "source": "local-ordinary-scaled" + "milliseconds": 337, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationProjectionTests.Seeded_local_measurement_records_statement_plans_payload_volume_and_end_to_end_timings", - "milliseconds": 6015, - "source": "local-ordinary-scaled" + "milliseconds": 5081, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationProjectionTests.Shared_warm_cache_alternates_tenants_without_crossing_definition_or_band_values", - "milliseconds": 89, - "source": "local-ordinary-scaled" + "milliseconds": 131, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationProjectionTests.Store_mutation_bypasses_warm_cache_before_bump_and_rollback_reissued_generation_is_clean", - "milliseconds": 2402, - "source": "local-ordinary-scaled" + "milliseconds": 2355, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationProjectionTests.Warm_cache_never_admits_closed_or_unannounced_transactions", - "milliseconds": 40, - "source": "local-ordinary-scaled" + "milliseconds": 143, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationPublicationConcurrencyTests.A_competitor_publishing_between_reads_is_refused_without_self_or_other_retirement", - "milliseconds": 4707, - "source": "local-ordinary-scaled" + "milliseconds": 5588, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationPublicationConcurrencyTests.An_absorbed_first_publication_save_failure_cannot_commit_the_dirty_successor_or_later_write", - "milliseconds": 4592, - "source": "local-ordinary-scaled" + "milliseconds": 5517, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationPublicationConcurrencyTests.Replacement_publication_rolls_back_both_revisions_and_generation_when_must_audit_fails", - "milliseconds": 2081, - "source": "local-ordinary-scaled" + "milliseconds": 3918, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationSchemaTests.ADeprecatedDefinitionDoesNotHoldTheKeyAgainstALiveOne", - "milliseconds": 14, - "source": "local-ordinary-scaled" + "milliseconds": 19, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationSchemaTests.ASoftDeletedDefinitionReleasesItsKeyToItsSuccessor", - "milliseconds": 14, - "source": "local-ordinary-scaled" + "milliseconds": 38, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.CustomizationSchemaTests.TheJsonbGuardAgreesWithTheColumn", - "milliseconds": 23, - "source": "local-ordinary-scaled" + "milliseconds": 38, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DatabaseRoleTests.ABypassRoleWithNoGrantIsStillRefused", - "milliseconds": 8, - "source": "local-ordinary-scaled" + "milliseconds": 407, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DatabaseRoleTests.ANewTableGrantsTheApplicationRoleNothingUntilItsMigrationSaysSo", - "milliseconds": 10, - "source": "local-ordinary-scaled" + "milliseconds": 125, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DatabaseRoleTests.EachRoleExistsWithItsDeclaredBypassPosture", - "milliseconds": 14, - "source": "local-ordinary-scaled" + "milliseconds": 399, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DatabaseRoleTests.EveryRoleCredentialActuallyLogsIn", - "milliseconds": 56, - "source": "local-ordinary-scaled" + "milliseconds": 204, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DatabaseRoleTests.NoDefaultPrivilegesExist_SoAnUngrantedTableIsAlwaysLoud", - "milliseconds": 199, - "source": "local-ordinary-scaled" + "milliseconds": 162, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DatabaseRoleTests.OnlyTheMigrationRoleMayCreateInSchemaPublic", - "milliseconds": 13, - "source": "local-ordinary-scaled" + "milliseconds": 56, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DatabaseRoleTests.PublicHoldsNoConnectPrivilegeOnTheDatabase", - "milliseconds": 9, - "source": "local-ordinary-scaled" + "milliseconds": 596, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DatabaseRoleTests.TheApplicationRoleIsNotAMemberOfTheBypassRoles", - "milliseconds": 5, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.DatabaseRoleTests.Superuser_transport_creates_and_drops_a_database_outside_an_aborted_ambient_transaction", + "milliseconds": 398, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DatabaseRoleTests.TheMigrationRoleOwnsWhatItCreates_AndOwnershipGrantsNoBypass", - "milliseconds": 12, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.DatabaseRoleTests.Superuser_transport_rolls_back_the_failed_batch_and_closes_its_observed_backend", + "milliseconds": 577, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DatabaseRoleTests.TheRolesScriptIsIdempotent", - "milliseconds": 78, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.DatabaseRoleTests.Superuser_transport_uses_the_container_identity_and_closes_each_physical_session", + "milliseconds": 180, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DatabaseRoleTests.TheRolesScriptRevokesAnEscalatedMembership", - "milliseconds": 485, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.DatabaseRoleTests.TheApplicationRoleIsNotAMemberOfTheBypassRoles", + "milliseconds": 102, + "source": "p031-hosted-ordinary-7" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DatabaseRoleTests.TheMigrationRoleOwnsWhatItCreates_AndOwnershipGrantsNoBypass", + "milliseconds": 21, + "source": "p031-hosted-ordinary-3" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DatabaseRoleTests.ThePublishedDatabasePortIsExclusivelyLoopback", + "milliseconds": 12, + "source": "p031-hosted-ordinary-4" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DatabaseRoleTests.TheRolesScriptIsIdempotent", + "milliseconds": 135, + "source": "p031-hosted-ordinary-3" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DatabaseRoleTests.TheRolesScriptRevokesAnEscalatedMembership", + "milliseconds": 501, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DatabaseRoleTests.TheRolesScriptTakesBackAnEscalatedAttribute", - "milliseconds": 187, - "source": "local-ordinary-scaled" + "milliseconds": 225, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests.Actual_claims_follow_all_five_index_order_keys", - "milliseconds": 1220, - "source": "local-ordinary-scaled" + "milliseconds": 913, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests.Audit_refusal_rolls_back_transition_then_reacquires_terminal_only_with_actual_metadata", - "milliseconds": 1428, - "source": "local-ordinary-scaled" + "milliseconds": 1514, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests.Completed_sixth_attempt_with_inert_lease_is_excluded_from_recovery_without_inbox_access", - "milliseconds": 1129, - "source": "local-ordinary-scaled" + "milliseconds": 1380, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests.Lost_terminal_commit_ack_reconciles_once_or_preserves_both_failures", - "milliseconds": 2026, - "source": "local-ordinary-scaled" + "milliseconds": 2947, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests.Normal_claim_cannot_terminalize_without_its_separate_acquisition", - "milliseconds": 1092, - "source": "local-ordinary-scaled" + "milliseconds": 1414, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests.Normal_failure_uses_each_database_delay_and_clears_ownership", - "milliseconds": 4772, - "source": "local-ordinary-scaled" + "milliseconds": 6414, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests.Normal_unknown_commit_and_expired_recovery_have_distinct_stored_diagnostics", - "milliseconds": 1102, - "source": "local-ordinary-scaled" + "milliseconds": 1334, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests.Pair_specific_holds_preserve_pending_and_privileged_but_allow_active_pending_sibling_and_unknown_pair", - "milliseconds": 1179, - "source": "local-ordinary-scaled" + "milliseconds": 1365, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests.Real_scheduler_role_cannot_read_payload_causality_or_inbox", - "milliseconds": 4788, - "source": "local-ordinary-scaled" + "milliseconds": 7382, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests.Recovery_preserves_attempt_budget_and_sets_database_time_backoff", - "milliseconds": 5186, - "source": "local-ordinary-scaled" + "milliseconds": 7331, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests.Replay_preserves_other_terminal_rows_differing_in_each_tuple_component", - "milliseconds": 1405, - "source": "local-ordinary-scaled" + "milliseconds": 1110, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests.Replay_refuses_nonadmitted_or_unfinished_state", - "milliseconds": 5221, - "source": "local-ordinary-scaled" + "milliseconds": 4894, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests.Replay_resets_only_exact_active_terminal_tuple_and_keeps_completed_sibling_inbox_and_stale_fences", - "milliseconds": 1151, - "source": "local-ordinary-scaled" + "milliseconds": 1834, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests.Sixth_failure_or_recovery_is_terminal_only_and_never_spends_a_seventh_claim", - "milliseconds": 1944, - "source": "local-ordinary-scaled" + "milliseconds": 2848, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests.Substitution_against_actual_subscriber_witness_rolls_back_both_writes", - "milliseconds": 9802, + "milliseconds": 13489, + "source": "p031-hosted-ordinary-5" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests.Terminal_claim_cannot_spend_an_execution_retry", + "milliseconds": 1337, + "source": "p031-hosted-ordinary-8" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests.Two_stores_acquire_one_tuple_once_and_siblings_spend_independent_budgets", + "milliseconds": 1317, + "source": "p031-hosted-ordinary-5" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests.Unchanged_row_lock_wait_cannot_use_pre_wait_lease_time", + "milliseconds": 7819, + "source": "p031-hosted-ordinary-8" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.A_durable_inbox_duplicate_completes_the_claim_without_constructing_or_classifying_the_handler", + "milliseconds": 1508, + "source": "p031-hosted-ordinary-6" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.A_lease_expiring_behind_an_unchanged_row_lock_is_rechecked_after_lock_acquisition", + "milliseconds": 1926, + "source": "p031-hosted-ordinary-10" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.A_real_MUST_audit_write_fault_rolls_back_every_effect_and_logs_only_bounded_diagnostics", + "milliseconds": 1401, + "source": "p031-hosted-ordinary-2" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Actual_delivery_owner_drains_saved_domain_facts_and_rolls_back_translation_failure", + "milliseconds": 2844, + "source": "p031-hosted-ordinary-2" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Closing_the_gate_while_a_callback_ignores_cancellation_prevents_a_late_commit", + "milliseconds": 1765, + "source": "p031-hosted-ordinary-10" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Durable_acceptance_does_not_wait_for_same_partition_handler_or_acknowledged_cleanup", + "milliseconds": 3169, + "source": "p031-hosted-ordinary-7" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Faults_roll_back_actual_attempted_work_and_a_fresh_delivery_scope_remains_usable", + "milliseconds": 9925, + "source": "p031-hosted-ordinary-1" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Final_ownership_loss_rolls_back_saved_business_inbox_outbox_and_success_audit", + "milliseconds": 2592, + "source": "p031-hosted-ordinary-0" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Integration_Event_Handler_Restores_Tenant_Context", + "milliseconds": 2181, + "source": "p031-hosted-ordinary-1" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Invalid_claim_token_or_platform_tenant_refuses_before_creating_any_application_scope", + "milliseconds": 7582, + "source": "p031-hosted-ordinary-7" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Invalid_metadata_or_unclassified_handler_refuses_before_business_construction", + "milliseconds": 9589, + "source": "p031-hosted-ordinary-6" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Lost_COMMIT_acknowledgement_retains_atomic_completion_and_never_repeats_business", + "milliseconds": 3018, + "source": "p031-hosted-ordinary-2" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Post_acknowledgement_hanging_scope_cleanup_retains_receipt_and_live_resource_until_observed_completion", + "milliseconds": 1214, + "source": "p031-hosted-ordinary-7" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Post_acknowledgement_scope_disposal_fault_retains_completion_and_blocks_gate_reuse", + "milliseconds": 1033, + "source": "p031-hosted-ordinary-10" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Retained_active_subscription_executes_despite_a_pending_sibling_and_pending_target_is_refused", + "milliseconds": 1550, + "source": "p031-hosted-ordinary-6" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Retained_envelope_read_failure_rolls_back_before_construction_and_fresh_scope_can_retry", + "milliseconds": 887, + "source": "p031-hosted-ordinary-10" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Acknowledged_commit_survives_hung_or_faulted_scope_cleanup_without_retry", + "milliseconds": 7163, "source": "local-ordinary-scaled" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests.Terminal_claim_cannot_spend_an_execution_retry", - "milliseconds": 1135, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Actual_API_registers_one_delivery_worker_with_shared_guarded_source_and_private_health", + "milliseconds": 880, + "source": "p031-hosted-ordinary-0" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Blocked_cancellation_callback_retains_actual_scope_and_shutdown_observes_one_shared_budget", + "milliseconds": 8437, + "source": "p031-hosted-ordinary-1" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Controlled_executor_reuse_refuses_without_disposing_the_original_live_control", + "milliseconds": 1324, + "source": "p031-hosted-ordinary-5" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Expired_claim_recovery_spends_no_execution_and_six_has_no_seventh_invocation", + "milliseconds": 4244, + "source": "p031-hosted-ordinary-8" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Failed_timeout_transition_still_closes_gate_and_ignored_token_cannot_commit_late", + "milliseconds": 3172, + "source": "p031-hosted-ordinary-3" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Faulting_cancellation_callback_is_observed_and_actual_scope_still_disposes", + "milliseconds": 5882, + "source": "local-ordinary-scaled" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Four_retained_scopes_saturate_capacity_and_release_unblocks_only_available_partitions", + "milliseconds": 22231, + "source": "pr38-b-ordinary-7" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Lost_sixth_COMMIT_acknowledgement_is_reconciled_from_durable_completion_without_seventh_execution", + "milliseconds": 1590, + "source": "p031-hosted-ordinary-11" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Siblings_have_independent_retries_and_Active_delivery_runs_beside_exact_Pending_and_privileged_holds", + "milliseconds": 1521, + "source": "p031-hosted-ordinary-7" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Successful_executions_do_not_force_scans_and_refresh_failure_keeps_the_previous_snapshot", + "milliseconds": 11768, + "source": "p031-hosted-ordinary-1" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Synchronous_handler_construction_cannot_monopolize_worker_wait_or_other_partitions", + "milliseconds": 2982, + "source": "p031-hosted-ordinary-10" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Terminal_audit_backlog_cannot_starve_normal_execution_or_expired_claim_recovery", + "milliseconds": 15048, + "source": "p031-hosted-ordinary-7" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Unclassified_handler_is_refused_before_construction_with_a_distinct_closed_descriptor", + "milliseconds": 1460, + "source": "p031-hosted-ordinary-5" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Worker_bounds_handler_faults_and_a_different_partition_keeps_progressing", + "milliseconds": 7327, + "source": "p031-hosted-ordinary-10" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.A_detached_source_preserves_its_saved_fact_without_hitchhiking_a_later_unsaved_fact", + "milliseconds": 4303, + "source": "p031-hosted-ordinary-1" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.A_disposed_child_activity_preserves_exact_save_origin_causation_and_causal_actor_until_commit", + "milliseconds": 954, + "source": "p031-hosted-ordinary-3" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.A_successful_owner_can_save_again_in_the_same_DI_scope_without_replaying_cleared_facts", + "milliseconds": 1305, + "source": "p031-hosted-ordinary-2" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.A_successful_save_poison_receipt_reaches_every_absorbing_ancestor", + "milliseconds": 209, + "source": "p031-hosted-ordinary-11" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.An_unchanged_source_receives_nothing_from_a_zero_save_or_another_sources_save", + "milliseconds": 1355, + "source": "p031-hosted-ordinary-6" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.Both_compositions_automatically_promote_a_successful_save_and_clear_on_refusal", + "milliseconds": 220, + "source": "p031-hosted-ordinary-8" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.Both_compositions_refuse_event_bearing_saves_without_an_enrolled_producer", + "milliseconds": 106, + "source": "p031-hosted-ordinary-0" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.Disposing_an_unfinished_scope_discards_collected_and_uncollected_source_facts", + "milliseconds": 123, + "source": "p031-hosted-ordinary-8" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.Event_257_rolls_back_the_whole_unit_even_when_its_overflow_is_absorbed", + "milliseconds": 267, + "source": "p031-hosted-ordinary-1" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.Exactly_256_successfully_saved_domain_events_can_complete_one_transaction", + "milliseconds": 2534, + "source": "p031-hosted-ordinary-1" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.Failed_or_canceled_saves_promote_nothing_and_a_retry_belongs_to_its_saving_invocation", + "milliseconds": 3341, + "source": "p031-hosted-ordinary-0" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.Owner_cancellation_or_a_dispatch_fault_clears_all_sources_and_refuses_poisoned_scope_reuse", + "milliseconds": 2584, + "source": "p031-hosted-ordinary-11" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.Owner_drain_does_not_rescan_a_source_for_an_unsaved_recursive_fact", + "milliseconds": 963, + "source": "p031-hosted-ordinary-3" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.Source_domain_outbox_and_MUST_audit_commit_together_or_rollback_together", + "milliseconds": 2159, + "source": "p031-hosted-ordinary-7" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.The_owner_drains_FIFO_across_sources_saves_delete_and_detach_without_duplicates", + "milliseconds": 1337, + "source": "p031-hosted-ordinary-5" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.A_compatible_alias_subset_is_completed_with_the_current_canonical_identity", + "milliseconds": 1062, + "source": "p031-hosted-ordinary-7" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.A_conflicting_later_copy_rolls_back_the_new_earlier_copy", + "milliseconds": 1614, + "source": "p031-hosted-ordinary-1" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.A_matching_existing_subset_is_completed_without_changing_its_copy", + "milliseconds": 1230, + "source": "p031-hosted-ordinary-4" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.A_publisher_waits_for_an_uncommitted_duplicate_then_reconciles_its_outcome", + "milliseconds": 2460, + "source": "p031-hosted-ordinary-6" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Accepted_copies_obey_the_actual_application_role_tenant_and_organization_scope", + "milliseconds": 1059, + "source": "p031-hosted-ordinary-7" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Alias_compatibility_never_accepts_a_different_contract_or_changed_payload", + "milliseconds": 3894, + "source": "p031-hosted-ordinary-0" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Any_immutable_envelope_collision_refuses_without_overwriting", + "milliseconds": 4739, + "source": "p031-hosted-ordinary-0" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Blocked_publication_does_not_leak_ambient_scope_or_block_another_tenant_partition", + "milliseconds": 1303, + "source": "p031-hosted-ordinary-4" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Cancellation_before_publication_writes_no_copies", + "milliseconds": 751, + "source": "p031-hosted-ordinary-10" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Cancellation_while_the_second_copy_waits_rolls_back_the_first_copy", + "milliseconds": 1025, + "source": "p031-hosted-ordinary-3" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Canonical_republication_preserves_compatible_alias_copies_and_their_scheduling_state", + "milliseconds": 1310, + "source": "p031-hosted-ordinary-5" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Dropped_commit_acknowledgement_leaves_durable_copies_and_republication_is_idempotent", + "milliseconds": 1495, + "source": "p031-hosted-ordinary-8" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Equivalent_json_with_different_object_key_order_is_an_identical_copy", + "milliseconds": 1281, + "source": "p031-hosted-ordinary-6" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Identical_republication_preserves_status_lease_and_row_version", + "milliseconds": 827, + "source": "p031-hosted-ordinary-10" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Integration_Event_Publication_Is_Durable_Acceptance", + "milliseconds": 1862, + "source": "p031-hosted-ordinary-1" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Publication_uses_a_fresh_transaction_and_restores_the_caller_ambient_context", + "milliseconds": 1278, + "source": "p031-hosted-ordinary-11" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Simultaneous_duplicate_publishers_commit_only_the_declared_tuple_copies", + "milliseconds": 1282, + "source": "p031-hosted-ordinary-9" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Stored_contract_field_collision_refuses_without_overwriting", + "milliseconds": 3781, + "source": "p031-hosted-ordinary-6" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Unknown_pending_and_retired_contracts_refuse_and_explicit_absence_is_validated", + "milliseconds": 1263, + "source": "p031-hosted-ordinary-2" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.A_parent_has_one_translation_per_locale_even_with_distinct_slugs", + "milliseconds": 37, + "source": "p031-hosted-ordinary-11" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Content_type_revision_is_positive", + "milliseconds": 20, + "source": "p031-hosted-ordinary-4" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Course_authoring_handle_is_unique_only_among_live_rows", + "milliseconds": 16, + "source": "p031-hosted-ordinary-6" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Course_level_pin_is_absent_or_complete_with_a_positive_revision", + "milliseconds": 76, + "source": "p031-hosted-ordinary-9" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Customization_pin_keys_have_their_own_100_character_storage_bound", + "milliseconds": 20, + "source": "p031-hosted-ordinary-0" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Lesson_sort_permits_zero_positive_values_and_ties_but_not_negative_values", + "milliseconds": 16, + "source": "p031-hosted-ordinary-10" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Localized_slug_namespace_is_independent_between_tenants_and_locales", + "milliseconds": 15, + "source": "p031-hosted-ordinary-0" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Localized_slug_uniqueness_spans_parents_and_organizations", + "milliseconds": 47, + "source": "p031-hosted-ordinary-3" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Publication_check_comparison_rejects_a_widened_applied_constraint", + "milliseconds": 48, + "source": "p031-hosted-ordinary-9" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Publication_columns_accept_both_lowercase_states_and_refuse_other_values", + "milliseconds": 67, + "source": "p031-hosted-ordinary-6" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Slug_storage_and_the_shared_predicate_agree_at_URL_boundaries", + "milliseconds": 170, + "source": "p031-hosted-ordinary-0" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Soft_deleting_the_parent_does_not_release_a_translated_slug", + "milliseconds": 69, + "source": "p031-hosted-ordinary-1" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Translated_body_is_a_JSON_object", + "milliseconds": 70, + "source": "p031-hosted-ordinary-4" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationIsolationTests.Education_Has_No_Unapproved_Column_Or_Public_Privileges", + "milliseconds": 41, + "source": "p031-hosted-ordinary-4" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationIsolationTests.Ignoring_Ef_Filters_Still_Reads_Only_The_Announced_Scope", + "milliseconds": 162, + "source": "p031-hosted-ordinary-4" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationIsolationTests.Insert_Policy_Independently_Requires_Exact_Tenant_And_Nullable_Organization", + "milliseconds": 5047, + "source": "p031-hosted-ordinary-5" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationIsolationTests.Organization_Changes_Reach_And_Fail_The_Immutable_Guard", + "milliseconds": 8260, + "source": "p031-hosted-ordinary-1" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationIsolationTests.Parent_Check_Cannot_Be_Shadowed_By_A_Temporary_Table", + "milliseconds": 3781, + "source": "p031-hosted-ordinary-6" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationIsolationTests.Parent_Check_Refuses_Missing_Hidden_And_Mismatched_Scopes_Uniformly", + "milliseconds": 30, + "source": "p031-hosted-ordinary-10" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationIsolationTests.Raw_Reads_Respect_Each_Tenant_Organization_And_Unresolved_Session", + "milliseconds": 145, + "source": "p031-hosted-ordinary-8" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationIsolationTests.Reporting_Reads_Never_Widen_Update_Or_Delete_Scope", + "milliseconds": 3743, + "source": "p031-hosted-ordinary-3" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationIsolationTests.Tenant_Composite_Foreign_Key_Refuses_A_Foreign_Parent_Independently", + "milliseconds": 2236, + "source": "p031-hosted-ordinary-0" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationIsolationTests.The_Privilege_Check_Detects_A_Column_Grant_Hidden_From_The_Table_Matrix", + "milliseconds": 61, + "source": "p031-hosted-ordinary-10" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationParentScopeTests.A_Conflicting_Temporary_Parent_Cannot_Hide_The_Valid_Public_Parent", + "milliseconds": 3710, + "source": "p031-hosted-ordinary-4" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationParentScopeTests.Reparenting_Requires_An_Existing_Parent_With_The_Same_Nullable_Scope", + "milliseconds": 3728, + "source": "p031-hosted-ordinary-5" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationParentScopeTests.The_Parent_Lookup_Locks_Before_The_Foreign_Key_Check", + "milliseconds": 3246, + "source": "p031-hosted-ordinary-7" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationParentScopeTests.The_Race_Proof_Rejects_An_Unlocked_Parent_Lookup_With_The_Foreign_Key_Intact", + "milliseconds": 4012, + "source": "p031-hosted-ordinary-2" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationPersistenceTests.AddingDifferentLocales_CompetesOnRootVersionAndLosingWriteLeavesNoSatellite", + "milliseconds": 2569, + "source": "p031-hosted-ordinary-4" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationPersistenceTests.CompositionRoot_ResolvesEducationOnTheOwningConnectionAndTransaction", + "milliseconds": 223, + "source": "p031-hosted-ordinary-9" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationPersistenceTests.PersistedGraphs_RoundTripPinsTranslationsAndContainedAuditWhileEachWriteTouchesOneRoot", + "milliseconds": 2875, + "source": "p031-hosted-ordinary-11" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.Every_Organization_Mirroring_Child_Has_A_Parent_Scope_Guard", + "milliseconds": 60, + "source": "p031-hosted-ordinary-8" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.Pattern_A_Content_Uses_Translation_Satellites", + "milliseconds": 20, + "source": "p031-hosted-ordinary-3" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.The_Identity_Parent_Guard_Rejects_A_Weakened_Applied_Function", + "milliseconds": 774, + "source": "p031-hosted-ordinary-7" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.The_Identity_Parent_Guard_Rejects_Inert_Trigger_Metadata", + "milliseconds": 387, + "source": "p031-hosted-ordinary-3" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.The_Identity_Parent_Guard_Requires_Both_Model_And_Applied_Relations", + "milliseconds": 708, + "source": "p031-hosted-ordinary-6" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.The_Parent_Guard_Rejects_A_New_Unclassified_Relation", + "milliseconds": 48, + "source": "p031-hosted-ordinary-7" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.The_Parent_Guard_Rejects_A_Weakened_Applied_Function", + "milliseconds": 420, + "source": "p031-hosted-ordinary-7" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.The_Parent_Guard_Rejects_Each_Missing_Trigger_And_Relation", + "milliseconds": 957, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests.Two_stores_acquire_one_tuple_once_and_siblings_spend_independent_budgets", - "milliseconds": 1127, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.The_Parent_Guard_Rejects_Inert_Trigger_Metadata", + "milliseconds": 442, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryDispatchStoreTests.Unchanged_row_lock_wait_cannot_use_pre_wait_lease_time", - "milliseconds": 9789, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.The_Pattern_A_Guard_Rejects_A_Missing_Satellite", + "milliseconds": 73, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.A_durable_inbox_duplicate_completes_the_claim_without_constructing_or_classifying_the_handler", - "milliseconds": 1160, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.The_Pattern_A_Guard_Rejects_A_Widened_Slug_Namespace", + "milliseconds": 164, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.A_lease_expiring_behind_an_unchanged_row_lock_is_rechecked_after_lock_acquisition", - "milliseconds": 3615, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.The_Pattern_A_Guard_Rejects_Localized_Shadow_Columns", + "milliseconds": 19, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.A_real_MUST_audit_write_fault_rolls_back_every_effect_and_logs_only_bounded_diagnostics", - "milliseconds": 1190, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.The_Pattern_A_Guard_Rejects_Misplaced_Applied_Columns", + "milliseconds": 547, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Actual_delivery_owner_drains_saved_domain_facts_and_rolls_back_translation_failure", - "milliseconds": 2478, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.The_Pattern_A_Guard_Rejects_Unmapped_Localized_CLR_Fields", + "milliseconds": 19, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Closing_the_gate_while_a_callback_ignores_cancellation_prevents_a_late_commit", - "milliseconds": 2360, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EducationWriterTests.An_outer_handler_absorbing_a_post_save_refusal_cannot_commit_the_dirty_or_later_root", + "milliseconds": 7301, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Durable_acceptance_does_not_wait_for_same_partition_handler_or_acknowledged_cleanup", - "milliseconds": 2464, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EducationWriterTests.Composed_writer_bounds_instances_before_lookup_and_preserves_state_on_oversize", + "milliseconds": 1511, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Faults_roll_back_actual_attempted_work_and_a_fresh_delivery_scope_remains_usable", - "milliseconds": 5441, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EducationWriterTests.Concurrent_publication_at_one_version_has_one_winner_and_one_must_success_audit", + "milliseconds": 1547, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Final_ownership_loss_rolls_back_saved_business_inbox_outbox_and_success_audit", - "milliseconds": 3677, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EducationWriterTests.Concurrent_translation_inserts_reserve_one_tenant_slug_and_roll_back_the_loser_stamp", + "milliseconds": 1575, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Integration_Event_Handler_Restores_Tenant_Context", - "milliseconds": 1220, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EducationWriterTests.Exact_active_bindings_and_existing_deprecated_pins_use_their_own_schema", + "milliseconds": 1269, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Invalid_claim_token_or_platform_tenant_refuses_before_creating_any_application_scope", - "milliseconds": 5305, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EducationWriterTests.Hidden_roots_are_not_found_and_visible_incompatible_scope_is_refused_before_mutation", + "milliseconds": 1624, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Invalid_metadata_or_unclassified_handler_refuses_before_business_construction", - "milliseconds": 9483, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EducationWriterTests.Locale_slug_lifecycle_and_stale_refusals_preserve_the_root_and_reserve_slugs_on_insert", + "milliseconds": 1279, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Lost_COMMIT_acknowledgement_retains_atomic_completion_and_never_repeats_business", - "milliseconds": 2508, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EducationWriterTests.Publication_requires_durable_must_audit_and_rolls_back_on_audit_failure", + "milliseconds": 1916, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Post_acknowledgement_hanging_scope_cleanup_retains_receipt_and_live_resource_until_observed_completion", - "milliseconds": 1206, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EducationWriterTests.Six_commands_preserve_independent_roots_explicit_policy_and_contained_audit_subjects", + "milliseconds": 1686, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Post_acknowledgement_scope_disposal_fault_retains_completion_and_blocks_gate_reuse", - "milliseconds": 1385, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EducationWriterTests.Slug_diagnostics_identify_only_visible_conflicting_roots", + "milliseconds": 3624, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Retained_active_subscription_executes_despite_a_pending_sibling_and_pending_target_is_refused", - "milliseconds": 1253, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EducationWriterTests.Unknown_education_unique_constraints_remain_infrastructure_faults", + "milliseconds": 2881, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryExecutionTests.Retained_envelope_read_failure_rolls_back_before_construction_and_fresh_scope_can_retry", - "milliseconds": 1133, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EntitlementExpiryReversalTests.A_projection_with_no_expiry_refuses_the_reversal_and_says_why", + "milliseconds": 259, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Acknowledged_commit_survives_hung_or_faulted_scope_cleanup_without_retry", - "milliseconds": 7163, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Acceptance_scope_proof_detects_an_isolated_read_hatch_in_with_check_mutant", + "milliseconds": 1264, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Actual_API_registers_one_delivery_worker_with_shared_guarded_source_and_private_health", - "milliseconds": 1142, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Actual_sql_refuses_privileges_outside_each_role_budget", + "milliseconds": 143, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Blocked_cancellation_callback_retains_actual_scope_and_shutdown_observes_one_shared_budget", - "milliseconds": 11384, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Application_acceptance_refuses_invalid_identity_without_repair", + "milliseconds": 44, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Controlled_executor_reuse_refuses_without_disposing_the_original_live_control", - "milliseconds": 1165, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Application_acceptance_requires_exact_organization_even_with_the_tenant_read_hatch", + "milliseconds": 2554, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Expired_claim_recovery_spends_no_execution_and_six_has_no_seventh_invocation", - "milliseconds": 3934, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Application_organization_reads_widen_only_with_the_tenant_hatch", + "milliseconds": 3492, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Failed_timeout_transition_still_closes_gate_and_ignored_token_cannot_commit_late", - "milliseconds": 5726, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Canonical_document_ddl_produces_the_same_applied_inventory_as_the_migration", + "milliseconds": 334, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Faulting_cancellation_callback_is_observed_and_actual_scope_still_disposes", - "milliseconds": 5882, + "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Composite_identity_deduplicates_each_subscription_and_tenant_independently", + "milliseconds": 31, "source": "local-ordinary-scaled" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Four_retained_scopes_saturate_capacity_and_release_unblocks_only_available_partitions", - "milliseconds": 20114, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Exact_column_grants_exclude_envelope_reads_completion_forgery_and_purge", + "milliseconds": 118, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Lost_sixth_COMMIT_acknowledgement_is_reconciled_from_durable_completion_without_seventh_execution", - "milliseconds": 1415, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Fenced_application_completion_writes_only_its_exact_organization_even_with_the_read_hatch", + "milliseconds": 1626, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Siblings_have_independent_retries_and_Active_delivery_runs_beside_exact_Pending_and_privileged_holds", - "milliseconds": 1652, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Fresh_down_reapply_preserves_the_producer_and_restores_the_complete_schema", + "milliseconds": 1383, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Successful_executions_do_not_force_scans_and_refresh_failure_keeps_the_previous_snapshot", - "milliseconds": 20491, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Immutable_inbox_guard_refuses_the_owner_and_a_removed_guard_is_a_failing_control", + "milliseconds": 2684, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Synchronous_handler_construction_cannot_monopolize_worker_wait_or_other_partitions", - "milliseconds": 6438, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Ledger_state_checks_preserve_valid_facts_and_refuse_invalid_combinations", + "milliseconds": 162, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Terminal_audit_backlog_cannot_starve_normal_execution_or_expired_claim_recovery", - "milliseconds": 23694, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Organization_immutability_is_enforced_even_when_the_owner_has_column_update_privilege", + "milliseconds": 15, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Unclassified_handler_is_refused_before_construction_with_a_distinct_closed_descriptor", - "milliseconds": 1256, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Organization_read_proof_detects_an_isolated_tenant_only_using_policy_mutant", + "milliseconds": 799, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DeliveryProcessorTests.Worker_bounds_handler_faults_and_a_different_partition_keeps_progressing", - "milliseconds": 11402, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Real_roles_accept_claim_complete_and_retain_inert_lease_provenance", + "milliseconds": 1288, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.A_detached_source_preserves_its_saved_fact_without_hitchhiking_a_later_unsaved_fact", - "milliseconds": 2083, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Restrictive_update_guard_stops_targeting_before_the_remaining_with_check_backstop", + "milliseconds": 2142, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.A_disposed_child_activity_preserves_exact_save_origin_causation_and_causal_actor_until_commit", - "milliseconds": 1051, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Scheduler_status_grants_allow_terminalization_and_targeted_replay_without_retention_dependencies", + "milliseconds": 1245, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.A_successful_owner_can_save_again_in_the_same_DI_scope_without_replaying_cleared_facts", - "milliseconds": 1016, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Scheduling_indexes_cover_eligibility_and_total_order_including_tied_event_ids", + "milliseconds": 983, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.A_successful_save_poison_receipt_reaches_every_absorbing_ancestor", - "milliseconds": 546, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Subscription_grammar_has_ascii_accepting_and_refusing_controls", + "milliseconds": 49, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.An_unchanged_source_receives_nothing_from_a_zero_save_or_another_sources_save", - "milliseconds": 1052, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.A_cancelled_tenant_flag_read_still_leaves_as_a_cancellation", + "milliseconds": 6, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.Both_compositions_automatically_promote_a_successful_save_and_clear_on_refusal", - "milliseconds": 238, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.A_flag_holding_a_rollout_percentage_answers_no_question", + "milliseconds": 63, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.Both_compositions_refuse_event_bearing_saves_without_an_enrolled_producer", - "milliseconds": 232, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.A_killswitch_can_only_narrow_and_never_grants", + "milliseconds": 2, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.Disposing_an_unfinished_scope_discards_collected_and_uncollected_source_facts", - "milliseconds": 184, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.A_killswitch_overrides_a_granted_plan_feature", + "milliseconds": 2, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.Event_257_rolls_back_the_whole_unit_even_when_its_overflow_is_absorbed", - "milliseconds": 384, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.A_limit_comes_from_the_projection_and_ignores_the_tenant_table", + "milliseconds": 15, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.Exactly_256_successfully_saved_domain_events_can_complete_one_transaction", - "milliseconds": 1201, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.A_limit_read_with_no_tenant_is_refused_rather_than_guessed", + "milliseconds": 3, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.Failed_or_canceled_saves_promote_nothing_and_a_retry_belongs_to_its_saving_invocation", - "milliseconds": 4128, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.A_plan_feature_comes_from_the_provider_and_never_from_the_tenant_table", + "milliseconds": 22, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.Owner_cancellation_or_a_dispatch_fault_clears_all_sources_and_refuses_poisoned_scope_reuse", - "milliseconds": 2390, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.A_request_with_no_tenant_is_refused_rather_than_guessed", + "milliseconds": 2, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.Owner_drain_does_not_rescan_a_source_for_an_unsaved_recursive_fact", - "milliseconds": 1025, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.A_resolved_context_that_names_no_real_tenant_is_refused", + "milliseconds": 5, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.Source_domain_outbox_and_MUST_audit_commit_together_or_rollback_together", - "milliseconds": 2291, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.A_tenant_flag_fails_closed_when_its_table_cannot_be_reached", + "milliseconds": 12, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DomainEventProductionTests.The_owner_drains_FIFO_across_sources_saves_delete_and_detach_without_duplicates", - "milliseconds": 1085, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.A_tenant_flag_row_is_honoured_when_it_is_a_JSON_boolean", + "milliseconds": 52, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.A_compatible_alias_subset_is_completed_with_the_current_canonical_identity", - "milliseconds": 897, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.An_absent_tenant_flag_row_resolves_to_the_catalog_default", + "milliseconds": 43, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.A_conflicting_later_copy_rolls_back_the_new_earlier_copy", - "milliseconds": 938, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.An_undeclared_key_is_refused_rather_than_resolved", + "milliseconds": 3, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.A_matching_existing_subset_is_completed_without_changing_its_copy", - "milliseconds": 860, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.An_undeclared_limit_key_is_refused_rather_than_read_as_unlimited", + "milliseconds": 4, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.A_publisher_waits_for_an_uncommitted_duplicate_then_reconciles_its_outcome", - "milliseconds": 1785, + "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.One_tenants_flags_are_never_answered_from_anothers", + "milliseconds": 199, "source": "local-ordinary-scaled" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Accepted_copies_obey_the_actual_application_role_tenant_and_organization_scope", - "milliseconds": 936, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.The_tenant_flags_read_names_its_tenant_where_row_security_would_not", + "milliseconds": 70, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Alias_compatibility_never_accepts_a_different_contract_or_changed_payload", - "milliseconds": 4420, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityAuthorityToolTests.Deployment_child_installs_once_verifies_repeat_and_refuses_rebind_or_app_credentials_without_values", + "milliseconds": 2174, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Any_immutable_envelope_collision_refuses_without_overwriting", - "milliseconds": 5411, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityBootstrapTests.API_composition_denies_seed_adoption_before_opening_any_global_owner", + "milliseconds": 33, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Blocked_publication_does_not_leak_ambient_scope_or_block_another_tenant_partition", - "milliseconds": 951, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityBootstrapTests.A_stalled_global_audit_INSERT_honors_its_deadline_or_caller_cancellation_and_reconciles", + "milliseconds": 10761, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Cancellation_before_publication_writes_no_copies", - "milliseconds": 825, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityBootstrapTests.A_waiting_creator_reads_the_committed_winner_after_the_real_subject_lock", + "milliseconds": 91, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Cancellation_while_the_second_copy_waits_rolls_back_the_first_copy", - "milliseconds": 879, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityBootstrapTests.Duplicate_non_success_is_proved_on_a_clean_transaction_without_a_User_witness", + "milliseconds": 583, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Canonical_republication_preserves_compatible_alias_copies_and_their_scheduling_state", - "milliseconds": 911, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityBootstrapTests.EF_constraint_failure_is_translated_without_retaining_the_provider_exception", + "milliseconds": 114, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Dropped_commit_acknowledgement_leaves_durable_copies_and_republication_is_idempotent", - "milliseconds": 891, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityBootstrapTests.Existing_seed_adoption_completes_without_intent_and_permits_same_scope_reuse", + "milliseconds": 118, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Equivalent_json_with_different_object_key_order_is_an_identical_copy", - "milliseconds": 880, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityBootstrapTests.Lookup_failure_or_cancellation_survives_awaited_cleanup_failure", + "milliseconds": 218, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Identical_republication_preserves_status_lease_and_row_version", - "milliseconds": 899, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityBootstrapTests.MUST_failure_rolls_back_User_and_preserves_failed_attempt_then_clean_twin_succeeds", + "milliseconds": 191, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Integration_Event_Publication_Is_Durable_Acceptance", - "milliseconds": 884, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityBootstrapTests.Original_success_evidence_requires_the_complete_captured_key_scope_source_target_and_outcome", + "milliseconds": 293, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Publication_uses_a_fresh_transaction_and_restores_the_caller_ambient_context", - "milliseconds": 927, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityBootstrapTests.Otherwise_normal_lookup_with_failed_cleanup_returns_a_bounded_storage_refusal", + "milliseconds": 49, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Simultaneous_duplicate_publishers_commit_only_the_declared_tuple_copies", - "milliseconds": 935, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityBootstrapTests.Precontext_binding_lookup_does_not_pin_common_coordinators_before_tenant_resolution", + "milliseconds": 599, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Stored_contract_field_collision_refuses_without_overwriting", - "milliseconds": 2744, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityBootstrapTests.Production_creation_and_existing_reads_use_one_binding_one_MUST_row_and_no_repair", + "milliseconds": 272, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.DurableEventAcceptanceTests.Unknown_pending_and_retired_contracts_refuse_and_explicit_absence_is_validated", - "milliseconds": 873, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityBootstrapTests.Qualification_refuses_missing_or_changed_anchor_without_installing_or_rebinding", + "milliseconds": 1392, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.A_parent_has_one_translation_per_locale_even_with_distinct_slugs", - "milliseconds": 17, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityBootstrapTests.Read_only_normalization_completes_then_a_tenant_owner_can_begin_in_the_same_scope", + "milliseconds": 148, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Content_type_revision_is_positive", - "milliseconds": 12, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityBootstrapTests.Real_lost_ack_and_unsent_COMMIT_remain_uncertain_without_asserting_a_User_outcome", + "milliseconds": 287, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Course_authoring_handle_is_unique_only_among_live_rows", - "milliseconds": 11, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityBootstrapTests.Reciprocal_guard_failure_is_known_precommit_failure_and_not_unknown_COMMIT", + "milliseconds": 163, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Course_level_pin_is_absent_or_complete_with_a_positive_revision", - "milliseconds": 54, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityBootstrapTests.Reenlisted_context_is_refused_before_snapshot_capture_and_a_fresh_owner_remains_usable", + "milliseconds": 167, + "source": "p031-hosted-ordinary-10" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityBootstrapTests.Resolved_tenant_context_cannot_read_or_adopt_even_an_existing_binding", + "milliseconds": 182, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Customization_pin_keys_have_their_own_100_character_storage_bound", - "milliseconds": 17, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityBootstrapTests.Signed_provider_and_authenticated_readback_facts_bind_the_preserved_actor_without_password_reuse", + "milliseconds": 59736, + "source": "pr38-a-ordinary-0" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Lesson_sort_permits_zero_positive_values_and_ties_but_not_negative_values", - "milliseconds": 7, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityBootstrapTests.Unavailable_duplicate_evidence_keeps_the_original_failure_and_marks_audit_health_unhealthy", + "milliseconds": 217, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Localized_slug_namespace_is_independent_between_tenants_and_locales", - "milliseconds": 15, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentitySchemaTests.Applied_census_has_fifty_five_tables_and_exactly_five_Identity_definers", + "milliseconds": 270, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Localized_slug_uniqueness_spans_parents_and_organizations", - "milliseconds": 34, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentitySchemaTests.Applied_function_bodies_signatures_privileges_and_trigger_callers_match_the_compiled_migration", + "milliseconds": 140, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Publication_check_comparison_rejects_a_widened_applied_constraint", - "milliseconds": 27, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentitySchemaTests.Applied_function_inspector_rejects_committed_widening_and_a_clean_twin_passes", + "milliseconds": 21958, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Publication_columns_accept_both_lowercase_states_and_refuse_other_values", - "milliseconds": 41, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentitySchemaTests.Applied_subject_lifecycle_CHECK_allows_nullable_Closing_and_bounds_retained_subjects", + "milliseconds": 58, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Slug_storage_and_the_shared_predicate_agree_at_URL_boundaries", - "milliseconds": 268, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentitySchemaTests.Authority_anchor_writes_require_the_deployment_owner_and_singleton_installation", + "milliseconds": 3181, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Soft_deleting_the_parent_does_not_release_a_translated_slug", - "milliseconds": 15, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentitySchemaTests.Compiled_function_reader_rejects_unsupported_replacements_and_a_clean_twin_passes", + "milliseconds": 94, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationConstraintTests.Translated_body_is_a_JSON_object", - "milliseconds": 60, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentitySchemaTests.Compiled_function_reader_uses_the_last_replacement_of_the_same_normalized_signature", + "milliseconds": 21, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationIsolationTests.Education_Has_No_Unapproved_Column_Or_Public_Privileges", - "milliseconds": 22, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentitySchemaTests.Database_digest_matches_the_network_order_unicode_subject_encoding", + "milliseconds": 12, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationIsolationTests.Ignoring_Ef_Filters_Still_Reads_Only_The_Announced_Scope", - "milliseconds": 153, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentitySchemaTests.Evidence_requires_exact_key_subject_target_source_outcome_and_success_relation", + "milliseconds": 51, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationIsolationTests.Insert_Policy_Independently_Requires_Exact_Tenant_And_Nullable_Organization", - "milliseconds": 3703, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentitySchemaTests.Global_Identity_Storage_Is_Subject_Confined", + "milliseconds": 762, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationIsolationTests.Organization_Changes_Reach_And_Fail_The_Immutable_Guard", - "milliseconds": 3512, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentitySchemaTests.Global_User_INSERT_refuses_wrong_or_absent_subject_scope", + "milliseconds": 3434, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationIsolationTests.Parent_Check_Cannot_Be_Shadowed_By_A_Temporary_Table", - "milliseconds": 2586, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentitySchemaTests.Global_audit_INSERT_refuses_malformed_attribution_and_a_valid_app_twin_commits", + "milliseconds": 382, + "source": "pr38-a-ordinary-8" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationIsolationTests.Parent_Check_Refuses_Missing_Hidden_And_Mismatched_Scopes_Uniformly", - "milliseconds": 69, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentitySchemaTests.Global_audit_WITH_CHECK_independently_refuses_missing_subject_and_detects_a_widened_policy", + "milliseconds": 2896, + "source": "pr38-a-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationIsolationTests.Raw_Reads_Respect_Each_Tenant_Organization_And_Unresolved_Session", - "milliseconds": 121, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentitySchemaTests.Global_creation_audit_cannot_be_inserted_through_owner_or_platform_credentials", + "milliseconds": 142, + "source": "pr38-b-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationIsolationTests.Reporting_Reads_Never_Widen_Update_Or_Delete_Scope", - "milliseconds": 3644, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentitySchemaTests.Global_grants_expose_only_self_select_initial_insert_and_exact_evidence", + "milliseconds": 103, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationIsolationTests.Tenant_Composite_Foreign_Key_Refuses_A_Foreign_Parent_Independently", - "milliseconds": 3003, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentitySchemaTests.Independent_app_probe_detects_a_committed_self_RLS_widening", + "milliseconds": 4735, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationIsolationTests.The_Privilege_Check_Detects_A_Column_Grant_Hidden_From_The_Table_Matrix", - "milliseconds": 43, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentitySchemaTests.Non_success_evidence_needs_no_User_and_cannot_satisfy_success", + "milliseconds": 93, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationParentScopeTests.A_Conflicting_Temporary_Parent_Cannot_Hide_The_Valid_Public_Parent", - "milliseconds": 3102, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentitySchemaTests.Owner_DELETE_probe_detects_guard_removal_while_app_delete_stays_denied", + "milliseconds": 7787, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationParentScopeTests.Reparenting_Requires_An_Existing_Parent_With_The_Same_Nullable_Scope", - "milliseconds": 3249, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentitySchemaTests.Owner_execution_cannot_remove_or_mutate_the_permanent_binding", + "milliseconds": 161, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationParentScopeTests.The_Parent_Lookup_Locks_Before_The_Foreign_Key_Check", - "milliseconds": 3243, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentitySchemaTests.Reciprocal_creation_requires_both_exact_success_witnesses", + "milliseconds": 155, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationParentScopeTests.The_Race_Proof_Rejects_An_Unlocked_Parent_Lookup_With_The_Foreign_Key_Intact", - "milliseconds": 3238, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityUnitOfWorkTests.A_creation_owner_without_final_constraint_validation_rolls_back_before_physical_commit", + "milliseconds": 55, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationPersistenceTests.AddingDifferentLocales_CompetesOnRootVersionAndLosingWriteLeavesNoSatellite", - "milliseconds": 2000, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityUnitOfWorkTests.A_later_generation_has_no_stale_global_enrollment_or_identity_session_authority", + "milliseconds": 23, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationPersistenceTests.CompositionRoot_ResolvesEducationOnTheOwningConnectionAndTransaction", - "milliseconds": 153, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityUnitOfWorkTests.Global_entry_cannot_join_an_ordinary_transaction", + "milliseconds": 27, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationPersistenceTests.PersistedGraphs_RoundTripPinsTranslationsAndContainedAuditWhileEachWriteTouchesOneRoot", - "milliseconds": 2040, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityUnitOfWorkTests.Only_the_exact_enrolled_context_can_issue_commands_and_validation_seals_it_before_commit", + "milliseconds": 28, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.Every_Organization_Mirroring_Child_Has_A_Parent_Scope_Guard", - "milliseconds": 20, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityUnitOfWorkTests.Ordinary_entries_cannot_join_or_retarget_a_global_owner", + "milliseconds": 84, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.Pattern_A_Content_Uses_Translation_Satellites", - "milliseconds": 15, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.GlobalIdentityUnitOfWorkTests.Read_only_global_owner_announces_only_self_authority_and_clears_unrelated_session_values", + "milliseconds": 34, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.The_Parent_Guard_Rejects_A_New_Unclassified_Relation", - "milliseconds": 44, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.A_closed_process_gate_refuses_before_any_core_server_is_announced", + "milliseconds": 1043, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.The_Parent_Guard_Rejects_A_Weakened_Applied_Function", - "milliseconds": 425, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.A_native_admission_preserves_private_tokens_on_local_drain_and_retains_host_cancellation_callbacks", + "milliseconds": 1413, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.The_Parent_Guard_Rejects_Each_Missing_Trigger_And_Relation", - "milliseconds": 1650, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.A_real_generation_becomes_ready_runs_only_closed_wakeups_and_joins_after_local_drain", + "milliseconds": 1283, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.The_Parent_Guard_Rejects_Inert_Trigger_Metadata", - "milliseconds": 388, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.A_stopped_closed_invocation_refuses_before_routing_an_actually_eligible_job", + "milliseconds": 1794, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.The_Pattern_A_Guard_Rejects_A_Missing_Satellite", - "milliseconds": 47, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.A_throwing_read_scope_stays_strongly_owned_after_wrapper_return_and_prevents_replacement", + "milliseconds": 1636, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.The_Pattern_A_Guard_Rejects_A_Widened_Slug_Namespace", - "milliseconds": 116, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.Actual_bound_routing_or_scope_cleanup_outlives_stock_join_and_blocks_replacement", + "milliseconds": 13897, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.The_Pattern_A_Guard_Rejects_Localized_Shadow_Columns", - "milliseconds": 19, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.Actual_worker_routing_that_resumes_after_local_drain_cannot_admit_a_business_attempt", + "milliseconds": 2986, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.The_Pattern_A_Guard_Rejects_Misplaced_Applied_Columns", - "milliseconds": 415, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.Four_retained_framework_entries_refuse_native_app_starts_without_spending_attempts", + "milliseconds": 1994, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationStructureTests.The_Pattern_A_Guard_Rejects_Unmapped_Localized_CLR_Fields", - "milliseconds": 1, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.Local_control_drain_preserves_other_real_pools_and_the_independent_shared_heartbeat", + "milliseconds": 2455, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationWriterTests.An_outer_handler_absorbing_a_post_save_refusal_cannot_commit_the_dirty_or_later_root", - "milliseconds": 6785, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.Manual_owner_heartbeat_contains_a_synthetic_clock_fault_until_actual_child_join", + "milliseconds": 1406, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationWriterTests.Composed_writer_bounds_instances_before_lookup_and_preserves_state_on_oversize", - "milliseconds": 1320, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.Metadata_observation_distinguishes_unobserved_from_confirmed_zero_and_tracks_actual_heartbeat_success", + "milliseconds": 880, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationWriterTests.Concurrent_publication_at_one_version_has_one_winner_and_one_must_success_audit", - "milliseconds": 1275, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.Real_announcement_SQL_permission_refusal_is_nonfatal_and_joins_its_outer_owner", + "milliseconds": 1387, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationWriterTests.Concurrent_translation_inserts_reserve_one_tenant_slug_and_roll_back_the_loser_stamp", - "milliseconds": 1359, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.Real_missing_metadata_SQL_via_manual_owner_heartbeat_preserves_a_healthy_pool", + "milliseconds": 2008, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationWriterTests.Exact_active_bindings_and_existing_deprecated_pins_use_their_own_schema", - "milliseconds": 1729, + "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.Real_swallowed_fetched_renewal_failure_stays_unhealthy_until_actual_storage_recovery", + "milliseconds": 10542, "source": "local-ordinary-scaled" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationWriterTests.Hidden_roots_are_not_found_and_visible_incompatible_scope_is_refused_before_mutation", - "milliseconds": 2279, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.Stop_before_start_owns_positive_no_Core_cleanup_and_forbids_late_start", + "milliseconds": 1351, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationWriterTests.Locale_slug_lifecycle_and_stale_refusals_preserve_the_root_and_reserve_slugs_on_insert", - "milliseconds": 1836, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.Synthetic_startup_timer_failure_drains_before_any_Core_construction", + "milliseconds": 1340, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationWriterTests.Publication_requires_durable_must_audit_and_rolls_back_on_audit_failure", - "milliseconds": 2542, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfirePoolOwnerTests.A_closed_global_gate_at_the_backoff_deadline_prevents_replacement", + "milliseconds": 2267, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationWriterTests.Six_commands_preserve_independent_roots_explicit_policy_and_contained_audit_subjects", - "milliseconds": 1491, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfirePoolOwnerTests.A_pool_replaces_only_after_actual_cleanup_and_backoff_then_runs_a_real_wakeup", + "milliseconds": 3295, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationWriterTests.Slug_diagnostics_identify_only_visible_conflicting_roots", - "milliseconds": 2656, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfirePoolOwnerTests.Host_stop_during_backoff_cancels_the_timer_and_never_constructs_a_replacement", + "milliseconds": 1167, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EducationWriterTests.Unknown_education_unique_constraints_remain_infrastructure_faults", - "milliseconds": 2485, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfirePoolOwnerTests.Prevalidation_fault_stays_retained_and_stop_consumes_only_the_callers_existing_budget", + "milliseconds": 929, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EntitlementExpiryReversalTests.A_projection_with_no_expiry_refuses_the_reversal_and_says_why", - "milliseconds": 249, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfirePoolOwnerTests.Startup_stall_remains_closed_after_the_actual_late_cleanup_joins", + "milliseconds": 1508, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Acceptance_scope_proof_detects_an_isolated_read_hatch_in_with_check_mutant", - "milliseconds": 1103, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfirePoolOwnerTests.Stop_before_start_positively_completes_without_constructing_any_generation", + "milliseconds": 1461, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Actual_sql_refuses_privileges_outside_each_role_budget", - "milliseconds": 103, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.A_valid_newer_capability_queue_survives_bootstrap_on_an_older_topology", + "milliseconds": 268, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Application_acceptance_refuses_invalid_identity_without_repair", - "milliseconds": 50, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Bootstrap_constructs_real_stock_storage_only_after_exact_schema_guards_and_acl_verification", + "milliseconds": 835, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Application_acceptance_requires_exact_organization_even_with_the_tenant_read_hatch", - "milliseconds": 2201, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Bootstrap_refuses_disabled_or_excessive_idle_startup_deadline_and_accepts_the_guarded_source", + "milliseconds": 728, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Application_organization_reads_widen_only_with_the_tenant_hatch", - "milliseconds": 2071, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Bootstrap_refuses_extra_durable_metadata_even_if_an_owner_reenables_the_guard_after_a_dirty_write", + "milliseconds": 764, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Canonical_document_ddl_produces_the_same_applied_inventory_as_the_migration", - "milliseconds": 368, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Bootstrap_uses_write_predicates_to_refuse_committed_metadata_drift_in_every_vendor_store", + "milliseconds": 105833, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Composite_identity_deduplicates_each_subscription_and_tenant_independently", - "milliseconds": 31, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Direct_vendor_writes_cannot_store_extra_fields_or_arbitrary_metadata", + "milliseconds": 1050, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Exact_column_grants_exclude_envelope_reads_completion_forgery_and_purge", - "milliseconds": 189, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Exact_function_body_drift_refuses_even_when_the_trigger_is_still_enabled", + "milliseconds": 289, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Fenced_application_completion_writes_only_its_exact_organization_even_with_the_read_hatch", - "milliseconds": 2066, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Guarded_source_reaps_idle_and_aborted_transactions_then_reopens_a_healthy_connection", + "milliseconds": 10269, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Fresh_down_reapply_preserves_the_producer_and_restores_the_complete_schema", - "milliseconds": 1660, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Hangfire_Invocations_And_Diagnostics_Are_Closed", + "milliseconds": 330, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Immutable_inbox_guard_refuses_the_owner_and_a_removed_guard_is_a_failing_control", - "milliseconds": 3353, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Queued_schedule_guard_reverses_and_reapplies_on_an_already_migrated_store", + "milliseconds": 4637, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Ledger_state_checks_preserve_valid_facts_and_refuse_invalid_combinations", - "milliseconds": 137, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Real_stock_counter_aggregator_commandTimeout_zero_obeys_server_sql_and_lock_deadlines_only", + "milliseconds": 5394, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Organization_immutability_is_enforced_even_when_the_owner_has_column_update_privilege", - "milliseconds": 11, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Server_metadata_accepts_four_declared_shape_queues_and_refuses_more_than_sixtyfour", + "milliseconds": 71, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Organization_read_proof_detects_an_isolated_tenant_only_using_policy_mutant", - "milliseconds": 1211, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Server_queue_metadata_refuses_nonstring_null_and_invalid_tokens", + "milliseconds": 172, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Real_roles_accept_claim_complete_and_retain_inert_lease_provenance", - "milliseconds": 1026, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Startup_sql_lock_and_idle_deadlines_survive_reset_and_warm_pool_reuse_with_unlimited_command_timeout", + "milliseconds": 5144, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Restrictive_update_guard_stops_targeting_before_the_remaining_with_check_backstop", - "milliseconds": 2329, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.State_guard_redacts_raw_reason_exception_and_result_below_all_filters", + "milliseconds": 113, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Scheduler_status_grants_allow_terminalization_and_targeted_replay_without_retention_dependencies", - "milliseconds": 1016, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Stock_schema_shape_drift_refuses_before_provider_construction_and_restoration_reopens_storage", + "milliseconds": 9055, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Scheduling_indexes_cover_eligibility_and_total_order_including_tied_event_ids", - "milliseconds": 1035, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Synchronous_vendor_and_bootstrap_calls_join_the_actual_async_acquisition_without_context_dispatch", + "milliseconds": 166, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests.Subscription_grammar_has_ascii_accepting_and_refusing_controls", - "milliseconds": 111, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Synchronous_vendor_factory_keeps_the_guard_on_every_new_physical_connection", + "milliseconds": 175, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.A_cancelled_tenant_flag_read_still_leaves_as_a_cancellation", - "milliseconds": 3, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Version_guard_and_acl_drift_refuse_before_real_storage_construction", + "milliseconds": 4131, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.A_flag_holding_a_rollout_percentage_answers_no_question", - "milliseconds": 50, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HostResolutionTests.A_Cancelled_Caller_Still_Leaves_The_Answer_Published", + "milliseconds": 138, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.A_killswitch_can_only_narrow_and_never_grants", - "milliseconds": 1, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HostResolutionTests.A_Read_Only_Transaction_Admits_The_Announcement_And_Refuses_A_Write", + "milliseconds": 20, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.A_killswitch_overrides_a_granted_plan_feature", - "milliseconds": 2, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HostResolutionTests.A_Row_With_Both_Flags_Set_Resolves", + "milliseconds": 40, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.A_limit_comes_from_the_projection_and_ignores_the_tenant_table", - "milliseconds": 13, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HostResolutionTests.A_Second_Lookup_Of_A_Mapped_Host_Does_Not_Reach_The_Database", + "milliseconds": 28, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.A_limit_read_with_no_tenant_is_refused_rather_than_guessed", - "milliseconds": 3, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HostResolutionTests.A_Second_Lookup_Of_An_Unmapped_Host_Does_Not_Reach_The_Database", + "milliseconds": 34, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.A_plan_feature_comes_from_the_provider_and_never_from_the_tenant_table", - "milliseconds": 48, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HostResolutionTests.An_Unmapped_Host_Resolves_To_Nothing", + "milliseconds": 23, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.A_request_with_no_tenant_is_refused_rather_than_guessed", - "milliseconds": 2, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HostResolutionTests.Both_Flags_Gate_The_Answer", + "milliseconds": 98, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.A_resolved_context_that_names_no_real_tenant_is_refused", - "milliseconds": 3, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HostResolutionTests.Concurrent_First_Lookups_Of_One_Host_Open_One_Connection", + "milliseconds": 39, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.A_tenant_flag_fails_closed_when_its_table_cannot_be_reached", - "milliseconds": 7, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HostResolutionTests.Host_Resolves_With_No_Tenant_Context_Under_Rls", + "milliseconds": 39, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.A_tenant_flag_row_is_honoured_when_it_is_a_JSON_boolean", - "milliseconds": 41, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HostResolutionTests.Invalidation_Clears_The_Positive_Entry_Not_Only_The_Negative_One", + "milliseconds": 97, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.An_absent_tenant_flag_row_resolves_to_the_catalog_default", - "milliseconds": 35, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.HostResolutionTests.Twelve_Waiters_On_One_Cold_Host_Publish_One_Answer", + "milliseconds": 42, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.An_undeclared_key_is_refused_rather_than_resolved", - "milliseconds": 3, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityCommandQualificationTests.Actual_seed_commands_measure_local_observation_cost_and_pool_occupancy_with_a_real_membership_wait", + "milliseconds": 7272, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.An_undeclared_limit_key_is_refused_rather_than_read_as_unlimited", - "milliseconds": 2, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityDiagnosticSinkTests.Actual_global_binding_save_keeps_its_fixed_boundary_and_replaces_pre_adapter_EF_failure_output", + "milliseconds": 373, + "source": "pr38-b-ordinary-5" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.One_tenants_flags_are_never_answered_from_anothers", - "milliseconds": 199, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityDiagnosticSinkTests.Actual_profile_provider_failure_reaches_source_and_never_reaches_serialized_diagnostic_sinks", + "milliseconds": 389, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.FeatureFlagsTests.The_tenant_flags_read_names_its_tenant_where_row_security_would_not", - "milliseconds": 69, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityDiagnosticSinkTests.Actual_profile_validation_drops_attempted_values_and_emits_fixed_nonempty_response", + "milliseconds": 50, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.A_closed_process_gate_refuses_before_any_core_server_is_announced", - "milliseconds": 1316, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityDiagnosticSinkTests.Another_modules_EF_save_failure_event_remains_enabled", + "milliseconds": 116, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.A_native_admission_preserves_private_tokens_on_local_drain_and_retains_host_cancellation_callbacks", - "milliseconds": 1698, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityDiagnosticSinkTests.Overlapping_compositions_protect_every_Identity_span_without_changing_actual_callers", + "milliseconds": 136, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.A_real_generation_becomes_ready_runs_only_closed_wakeups_and_joins_after_local_drain", - "milliseconds": 1595, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Actual_User_fence_orders_Membership_against_a_committing_closure_and_freshly_reads_status", + "milliseconds": 29761, + "source": "pr38-df-1-ordinary-6" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.A_stopped_closed_invocation_refuses_before_routing_an_actually_eligible_job", - "milliseconds": 1428, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Actual_admission_requires_own_backend_exclusive_single_bigint_User_fence", + "milliseconds": 92, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.A_throwing_read_scope_stays_strongly_owned_after_wrapper_return_and_prevents_replacement", - "milliseconds": 1555, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Admission_parent_correction_preserves_its_definer_boundary_and_converges_with_the_fresh_chain", + "milliseconds": 5997, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.Actual_bound_routing_or_scope_cleanup_outlives_stock_join_and_blocks_replacement", - "milliseconds": 26535, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Assignment_addition_serializes_with_Membership_Revoke_and_the_predecessor_exposes_the_race", + "milliseconds": 9197, + "source": "pr38-b-ordinary-0" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.Actual_worker_routing_that_resumes_after_local_drain_cannot_admit_a_business_attempt", - "milliseconds": 1629, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Competing_actual_first_admin_commands_recheck_history_after_the_tenant_wait_and_commit_exactly_one_graph", + "milliseconds": 4073, + "source": "pr38-a-ordinary-4" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.Four_retained_framework_entries_refuse_native_app_starts_without_spending_attempts", - "milliseconds": 1953, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Competing_administrator_retirements_wait_for_commit_then_preserve_the_last_admin", + "milliseconds": 4275, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.Local_control_drain_preserves_other_real_pools_and_the_independent_shared_heartbeat", - "milliseconds": 3587, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Complete_child_trigger_stack_has_one_parent_scope_refusal", + "milliseconds": 343, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.Manual_owner_heartbeat_contains_a_synthetic_clock_fault_until_actual_child_join", - "milliseconds": 1462, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Complete_second_admin_graph_requires_preheld_exclusive_tenant_mode", + "milliseconds": 58, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.Metadata_observation_distinguishes_unobserved_from_confirmed_zero_and_tracks_actual_heartbeat_success", - "milliseconds": 1300, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Contextual_WITH_CHECK_rejects_foreign_writes_and_its_dirty_twin_admits_them", + "milliseconds": 13550, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.Real_announcement_SQL_permission_refusal_is_nonfatal_and_joins_its_outer_owner", - "milliseconds": 1337, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Contextual_guards_refuse_incompatible_snapshot_isolation", + "milliseconds": 116, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.Real_missing_metadata_SQL_via_manual_owner_heartbeat_preserves_a_healthy_pool", - "milliseconds": 1776, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Contextual_whole_act_save_restores_EF_default_and_every_failure_poisons_the_owner", + "milliseconds": 711, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.Real_swallowed_fetched_renewal_failure_stays_unhealthy_until_actual_storage_recovery", - "milliseconds": 10542, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Direct_admission_function_returns_the_same_false_for_known_and_unknown_users", + "milliseconds": 15, + "source": "pr38-a-ordinary-3" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.Stop_before_start_owns_positive_no_Core_cleanup_and_forbids_late_start", - "milliseconds": 1306, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Every_assignment_addition_including_empty_role_requires_User_but_profile_and_removal_do_not", + "milliseconds": 38, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireGenerationTests.Synthetic_startup_timer_failure_drains_before_any_Core_construction", - "milliseconds": 1259, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Final_administrator_changes_are_refused_by_complete_graph_preflight", + "milliseconds": 124, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfirePoolOwnerTests.A_closed_global_gate_at_the_backoff_deadline_prevents_replacement", - "milliseconds": 1324, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Initial_Role_exception_admits_only_exact_fresh_graph_and_refuses_committed_repairs", + "milliseconds": 21, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfirePoolOwnerTests.A_pool_replaces_only_after_actual_cleanup_and_backoff_then_runs_a_real_wakeup", - "milliseconds": 1493, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Last_administrator_guard_requires_global_eligibility_not_only_an_active_membership", + "milliseconds": 5853, + "source": "pr38-a-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfirePoolOwnerTests.Host_stop_during_backoff_cancels_the_timer_and_never_constructs_a_replacement", - "milliseconds": 1264, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.NULL_parent_mirror_and_role_capability_are_checked_independently_of_RLS", + "milliseconds": 35, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfirePoolOwnerTests.Prevalidation_fault_stays_retained_and_stop_consumes_only_the_callers_existing_budget", - "milliseconds": 1279, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Parent_mirror_correction_replaces_only_its_function_and_reapplies_the_fresh_chain_exactly", + "milliseconds": 2509, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfirePoolOwnerTests.Startup_stall_remains_closed_after_the_actual_late_cleanup_joins", - "milliseconds": 1309, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Populated_graphs_are_isolated_by_actual_app_RLS_and_parameterized_EF_scope", + "milliseconds": 134, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfirePoolOwnerTests.Stop_before_start_positively_completes_without_constructing_any_generation", - "milliseconds": 1276, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Post_acquisition_row_timeout_is_a_fixed_conflict_and_the_seed_handler_refuses_without_partial_profile", + "milliseconds": 12197, + "source": "pr38-b-ordinary-8" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.A_valid_newer_capability_queue_survives_bootstrap_on_an_older_topology", - "milliseconds": 239, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Reactivation_requires_User_fence_and_revoked_history_remains_in_the_EF_model", + "milliseconds": 706, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Bootstrap_constructs_real_stock_storage_only_after_exact_schema_guards_and_acl_verification", - "milliseconds": 174, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Real_lock_timeout_or_cancellation_releases_transaction_without_partial_graph", + "milliseconds": 413, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Bootstrap_refuses_disabled_or_excessive_idle_startup_deadline_and_accepts_the_guarded_source", - "milliseconds": 595, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Restrictive_org_write_policy_filters_rows_before_independent_guards_and_its_dirty_twin_reaches_them", + "milliseconds": 8629, + "source": "pr38-a-ordinary-1" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Bootstrap_refuses_extra_durable_metadata_even_if_an_owner_reenables_the_guard_after_a_dirty_write", - "milliseconds": 267, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Revocation_is_terminal_and_rejoin_uses_a_new_identity_with_NULL_scope_uniqueness", + "milliseconds": 70, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Bootstrap_uses_write_predicates_to_refuse_committed_metadata_drift_in_every_vendor_store", - "milliseconds": 51418, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.SQL_and_CSharp_User_and_Tenant_keys_agree_in_both_signed_ranges", + "milliseconds": 31, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Direct_vendor_writes_cannot_store_extra_fields_or_arbitrary_metadata", - "milliseconds": 382, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Session_fence_demonstrates_observation_limit_and_transaction_fence_ends_on_rollback", + "milliseconds": 71, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Exact_function_body_drift_refuses_even_when_the_trigger_is_still_enabled", - "milliseconds": 143, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Shared_writers_coexist_but_exclusive_writer_waits_until_real_commit", + "milliseconds": 90, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Guarded_source_reaps_idle_and_aborted_transactions_then_reopens_a_healthy_connection", - "milliseconds": 22916, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMembershipTests.Unknown_target_refuses_before_FK_with_same_fixed_target_diagnostic", + "milliseconds": 17, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Hangfire_Invocations_And_Diagnostics_Are_Closed", - "milliseconds": 334, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMutationLockTests.Actual_global_subject_acquisition_emits_a_positive_finite_measurement_and_releases_on_rollback", + "milliseconds": 65, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Queued_schedule_guard_reverses_and_reapplies_on_an_already_migrated_store", - "milliseconds": 1908, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMutationLockTests.Actual_helper_waits_for_the_user_owner_and_a_separate_postwait_statement_observes_its_commit", + "milliseconds": 46, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Real_stock_counter_aggregator_commandTimeout_zero_obeys_server_sql_and_lock_deadlines_only", - "milliseconds": 11614, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMutationLockTests.An_acquired_shared_plan_never_upgrades_or_adds_a_late_user", + "milliseconds": 94, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Server_metadata_accepts_four_declared_shape_queues_and_refuses_more_than_sixtyfour", + "method": "LearnStack.Tests.Integration.Database.IdentityMutationLockTests.Complete_plan_holds_actual_exclusive_user_then_required_tenant_mode_and_releases_at_transaction_end", "milliseconds": 53, - "source": "local-ordinary-scaled" + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Server_queue_metadata_refuses_nonstring_null_and_invalid_tokens", - "milliseconds": 113, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMutationLockTests.Missing_or_incompatible_owner_refuses_before_any_advisory_hold", + "milliseconds": 131, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Startup_sql_lock_and_idle_deadlines_survive_reset_and_warm_pool_reuse_with_unlimited_command_timeout", - "milliseconds": 11386, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMutationLockTests.Profile_or_removal_plan_has_no_user_hold_and_cannot_upgrade_or_reuse_a_generation", + "milliseconds": 45, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.State_guard_redacts_raw_reason_exception_and_result_below_all_filters", - "milliseconds": 43, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMutationLockTests.Separate_shared_helpers_coexist_exclusive_waits_and_repeat_upgrade_refusals_emit_one_fixed_fault", + "milliseconds": 89, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Stock_schema_shape_drift_refuses_before_provider_construction_and_restoration_reopens_storage", - "milliseconds": 3547, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityMutationLockTests.Waiting_helper_timeout_or_cancellation_rolls_back_releases_and_reuses_the_physical_pool_connection", + "milliseconds": 2125, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HangfireStorageTests.Version_guard_and_acl_drift_refuse_before_real_storage_construction", - "milliseconds": 1783, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityReadDiagnosticSinkTests.Actual_contextual_read_ports_drop_provider_payloads_before_the_existing_diagnostic_sinks", + "milliseconds": 8729, + "source": "pr38-b-ordinary-1" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HostResolutionTests.A_Cancelled_Caller_Still_Leaves_The_Answer_Published", - "milliseconds": 275, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityReadDiagnosticSinkTests.Current_read_ports_preserve_cancellation_and_programming_failures", + "milliseconds": 46, + "source": "pr38-b-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HostResolutionTests.A_Read_Only_Transaction_Admits_The_Announcement_And_Refuses_A_Write", - "milliseconds": 31, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityScopeLifecycleTests.Actual_server_isolation_cannot_be_replaced_by_the_drivers_cached_mode", + "milliseconds": 27, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HostResolutionTests.A_Row_With_Both_Flags_Set_Resolves", - "milliseconds": 29, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityScopeLifecycleTests.Missing_or_foreign_scope_facts_are_closed_and_cannot_retarget_the_announcement", + "milliseconds": 39, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HostResolutionTests.A_Second_Lookup_Of_A_Mapped_Host_Does_Not_Reach_The_Database", - "milliseconds": 24, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityScopeLifecycleTests.Missing_tenant_and_unannounced_owner_cannot_produce_live_facts", + "milliseconds": 37, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HostResolutionTests.A_Second_Lookup_Of_An_Unmapped_Host_Does_Not_Reach_The_Database", - "milliseconds": 28, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityScopeLifecycleTests.Organization_belonging_is_separate_from_current_work_eligibility", + "milliseconds": 105, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HostResolutionTests.An_Unmapped_Host_Resolves_To_Nothing", - "milliseconds": 27, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentityScopeLifecycleTests.Tenant_facts_use_fresh_real_status_and_absent_org_has_no_organization_facts", + "milliseconds": 262, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HostResolutionTests.Both_Flags_Gate_The_Answer", - "milliseconds": 109, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentitySeederTests.A_mismatched_deployment_anchor_refuses_before_any_binding_or_contextual_mutation", + "milliseconds": 74, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HostResolutionTests.Concurrent_First_Lookups_Of_One_Host_Open_One_Connection", - "milliseconds": 28, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentitySeederTests.A_nonactive_membership_stops_remaining_acts_and_is_never_recreated", + "milliseconds": 25107, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HostResolutionTests.Host_Resolves_With_No_Tenant_Context_Under_Rls", - "milliseconds": 24, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentitySeederTests.Central_MUST_failure_rolls_back_only_the_failed_graph_and_clean_rerun_resumes", + "milliseconds": 36695, + "source": "pr38-df-2-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HostResolutionTests.Invalidation_Clears_The_Positive_Entry_Not_Only_The_Negative_One", - "milliseconds": 31, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentitySeederTests.Edited_or_upgraded_initial_grants_refuse_without_repair_or_additional_audit", + "milliseconds": 10344, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.HostResolutionTests.Twelve_Waiters_On_One_Cold_Host_Publish_One_Answer", - "milliseconds": 27, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.IdentitySeederTests.Four_actual_provider_bindings_sixteen_templates_and_four_scoped_memberships_are_exact_and_reruns_write_nothing", + "milliseconds": 11227, + "source": "p031-hosted-ordinary-11" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.IdentitySeederTests.Interrupted_committed_acts_resume_only_missing_declarations", + "milliseconds": 30360, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.InboxGuardTests.A_committed_claim_is_false_on_duplicate_but_distinct_tuples_are_independent", - "milliseconds": 949, - "source": "local-ordinary-scaled" + "milliseconds": 798, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.InboxGuardTests.Concurrent_claim_waits_on_uniqueness_and_observes_first_transaction_outcome", - "milliseconds": 2150, - "source": "local-ordinary-scaled" + "milliseconds": 2434, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.InboxGuardTests.Default_empty_and_platform_tenants_refuse_before_SQL_and_completed_frame_cannot_claim", - "milliseconds": 939, - "source": "local-ordinary-scaled" + "milliseconds": 1268, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.InboxGuardTests.Empty_event_identity_refuses_before_SQL_and_recorded_at_is_database_owned", - "milliseconds": 987, - "source": "local-ordinary-scaled" + "milliseconds": 1204, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.InboxGuardTests.Guard_refuses_missing_wrong_or_nonwritable_announcement_before_inserting", - "milliseconds": 1044, - "source": "local-ordinary-scaled" + "milliseconds": 782, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.InboxGuardTests.Invalid_subscription_identity_refuses_before_SQL", - "milliseconds": 6021, - "source": "local-ordinary-scaled" + "milliseconds": 6940, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.KillswitchOverlayTests.A_cancelled_read_is_not_swallowed_as_an_outage", - "milliseconds": 3, - "source": "local-ordinary-scaled" + "milliseconds": 6, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.KillswitchOverlayTests.A_flipped_switch_reads_as_disabled_through_the_policy", - "milliseconds": 28, - "source": "local-ordinary-scaled" + "milliseconds": 29, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.KillswitchOverlayTests.A_read_failure_resolves_to_enabled_rather_than_disabling_everything", - "milliseconds": 5, - "source": "local-ordinary-scaled" + "milliseconds": 14, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.KillswitchOverlayTests.A_switch_the_registry_does_not_declare_resolves_to_enabled", - "milliseconds": 1, - "source": "local-ordinary-scaled" + "milliseconds": 4, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.KillswitchOverlayTests.A_switch_with_no_row_reads_as_enabled", - "milliseconds": 19, - "source": "local-ordinary-scaled" + "milliseconds": 34, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.KillswitchOverlayTests.An_unflipped_switch_reads_as_enabled", - "milliseconds": 27, - "source": "local-ordinary-scaled" + "milliseconds": 20, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.KillswitchOverlayTests.The_whole_set_is_one_cache_entry", - "milliseconds": 23, - "source": "local-ordinary-scaled" + "milliseconds": 31, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.MigrationChainCoverageTests.Every_Migration_Chain_On_Disk_Is_Applied_By_The_Fixtures", - "milliseconds": 65, - "source": "local-ordinary-scaled" + "milliseconds": 61, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.MigrationRollbackTests.EveryChainReversesToAnEmptySchema", - "milliseconds": 1989, - "source": "local-ordinary-scaled" + "milliseconds": 2792, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OrgScopeMigrationTests.OrgScopeCorrection_PopulatedUpgradeDownAndReapply_PreservesRowsAndRestoresDefinitions", - "milliseconds": 878, - "source": "local-ordinary-scaled" + "milliseconds": 782, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OrgScopeSchemaTests.A_Reused_Connection_Does_Not_Keep_The_Previous_Organization", - "milliseconds": 131, - "source": "local-ordinary-scaled" + "milliseconds": 132, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OrgScopeSchemaTests.An_Insert_Requires_The_Exact_Organization_Scope", - "milliseconds": 125, - "source": "local-ordinary-scaled" + "milliseconds": 112, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OrgScopeSchemaTests.Every_OrgScoped_Table_Has_An_Organization_Immutability_Guard", - "milliseconds": 13, - "source": "local-ordinary-scaled" + "milliseconds": 49, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OrgScopeSchemaTests.Every_TenantOwned_Foreign_Key_Includes_TenantId", - "milliseconds": 14, - "source": "local-ordinary-scaled" + "milliseconds": 22, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OrgScopeSchemaTests.The_Audit_Append_Only_Guard_Independently_Refuses_An_Organization_Change", - "milliseconds": 1081, - "source": "local-ordinary-scaled" + "milliseconds": 1165, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OrgScopeSchemaTests.The_Organization_Guard_Rejects_A_Missing_Guard_On_Each_Existing_Table", - "milliseconds": 41, - "source": "local-ordinary-scaled" + "milliseconds": 82, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OrgScopeSchemaTests.The_Organization_Guard_Rejects_A_New_Unguarded_Table_And_Inert_Triggers", - "milliseconds": 70, - "source": "local-ordinary-scaled" + "milliseconds": 105, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OrgScopeSchemaTests.The_Shared_Immutability_Function_Works_On_A_Table_With_No_Id_Column", - "milliseconds": 1125, - "source": "local-ordinary-scaled" + "milliseconds": 1253, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OrgScopeSchemaTests.The_Tenant_Foreign_Key_Guard_Detects_Missing_And_Mispaired_Tenant_Columns", - "milliseconds": 37, - "source": "local-ordinary-scaled" + "milliseconds": 59, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OrgScopeSchemaTests.The_Tenant_Foreign_Key_Guard_Does_Not_Exempt_The_Self_Keyed_Directions", - "milliseconds": 23, - "source": "local-ordinary-scaled" + "milliseconds": 27, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OrganizationScopeValidatorTests.A_Soft_Deleted_Organization_Does_Not_Belong", - "milliseconds": 32, - "source": "local-ordinary-scaled" + "milliseconds": 35, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.OrganizationScopeValidatorTests.An_Organization_Of_The_Tenant_Belongs_To_It", - "milliseconds": 25, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.OrganizationScopeValidatorTests.An_Organization_Of_The_Tenant_Belongs_To_It", + "milliseconds": 21, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OrganizationScopeValidatorTests.Another_Tenants_Organization_Does_Not", - "milliseconds": 22, - "source": "local-ordinary-scaled" + "milliseconds": 29, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OrganizationScopeValidatorTests.Each_Call_Leaves_No_Setting_Behind_On_The_Pooled_Connection", - "milliseconds": 25, - "source": "local-ordinary-scaled" + "milliseconds": 53, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OrganizationScopeValidatorTests.The_Validators_Own_Statement_Sequence_Cannot_Write", - "milliseconds": 28, - "source": "local-ordinary-scaled" + "milliseconds": 63, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OrganizationScopeValidatorTests.Without_The_Announcement_The_Row_Is_Invisible", - "milliseconds": 24, - "source": "local-ordinary-scaled" + "milliseconds": 33, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchMigrationTests.Audit_grant_has_its_own_chain_and_is_removed_by_down_then_reapplied", - "milliseconds": 1141, - "source": "local-ordinary-scaled" + "milliseconds": 953, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchMigrationTests.Dispatcher_state_checks_have_accepting_and_refusing_controls", - "milliseconds": 40, - "source": "local-ordinary-scaled" + "milliseconds": 161, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchMigrationTests.Invalid_legacy_identity_refuses_migration_without_repair", - "milliseconds": 1739, - "source": "local-ordinary-scaled" + "milliseconds": 1574, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchMigrationTests.Legacy_facts_survive_up_down_reapply_and_diagnostics_are_redacted_across_tenants", - "milliseconds": 1444, - "source": "local-ordinary-scaled" + "milliseconds": 1472, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchMigrationTests.Outbox_role_has_no_audit_read_mutation_or_business_access", - "milliseconds": 23, - "source": "local-ordinary-scaled" + "milliseconds": 44, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchMigrationTests.Recovery_index_covers_expired_and_exhausted_selection_without_scanning_pending_backlog", - "milliseconds": 3777, - "source": "local-ordinary-scaled" + "milliseconds": 4660, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.A_live_success_commits_processed_state_and_clears_its_lease_once", - "milliseconds": 1013, - "source": "local-ordinary-scaled" + "milliseconds": 1327, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.A_lost_COMMIT_response_and_failed_reconciliation_preserve_both_failures_without_duplicate_audit", - "milliseconds": 1053, - "source": "local-ordinary-scaled" + "milliseconds": 2340, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.A_lost_physical_COMMIT_response_reconciles_durable_terminal_state_without_duplicate_audit", - "milliseconds": 1057, - "source": "local-ordinary-scaled" + "milliseconds": 1584, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.A_terminal_request_before_six_attempts_cannot_be_claimed_for_publication", - "milliseconds": 3301, - "source": "local-ordinary-scaled" + "milliseconds": 3092, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.A_witness_from_a_committed_terminal_transaction_cannot_be_reused_on_a_later_real_transition", - "milliseconds": 1039, - "source": "local-ordinary-scaled" + "milliseconds": 2051, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.An_intentionally_unsubscribed_contract_remains_eligible_for_explicit_acknowledgement", - "milliseconds": 918, - "source": "local-ordinary-scaled" + "milliseconds": 1341, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.Committed_failures_schedule_the_five_database_time_backoffs_without_sleeping", - "milliseconds": 5176, - "source": "local-ordinary-scaled" + "milliseconds": 5150, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.Concurrent_stores_claim_distinct_rows_without_owning_a_batch", - "milliseconds": 1011, - "source": "local-ordinary-scaled" + "milliseconds": 1486, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.Delayed_failure_allows_later_work_on_the_same_partition_to_overtake", - "milliseconds": 1216, - "source": "local-ordinary-scaled" + "milliseconds": 1436, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.Empty_and_future_occurrence_snapshots_never_report_negative_eligible_age", - "milliseconds": 1049, - "source": "local-ordinary-scaled" + "milliseconds": 1262, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.Exhausted_unleased_legacy_work_is_terminal_only_without_an_extra_attempt", - "milliseconds": 1007, - "source": "local-ordinary-scaled" + "milliseconds": 1366, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.Expired_claims_recover_into_backoff_without_spending_another_attempt", - "milliseconds": 5196, - "source": "local-ordinary-scaled" + "milliseconds": 7326, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.Expired_terminal_acquisition_loses_its_fence_before_and_after_fresh_terminal_reacquisition", - "milliseconds": 1217, - "source": "local-ordinary-scaled" + "milliseconds": 1456, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.Expiry_alone_refuses_every_transition_without_changing_state", - "milliseconds": 3285, - "source": "local-ordinary-scaled" + "milliseconds": 2527, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.Failed_or_crashed_sixth_claim_requests_terminalization_and_never_claims_a_seventh", - "milliseconds": 2466, - "source": "local-ordinary-scaled" + "milliseconds": 2144, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.Locally_blocked_partitions_exclude_normal_recovery_and_terminal_acquisition", - "milliseconds": 1071, - "source": "local-ordinary-scaled" + "milliseconds": 849, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.Queue_snapshot_counts_every_pending_state_but_ages_only_publish_eligible_work", - "milliseconds": 1172, - "source": "local-ordinary-scaled" + "milliseconds": 1643, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.Real_TenantCreated_contracts_and_aliases_are_held_before_any_payload_validation", - "milliseconds": 4980, - "source": "local-ordinary-scaled" + "milliseconds": 3844, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.Recovery_by_the_same_store_replaces_the_token_and_fences_every_stale_transition", - "milliseconds": 3021, - "source": "local-ordinary-scaled" + "milliseconds": 4056, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.Refused_audit_rolls_back_the_terminal_update_and_retains_the_request_for_audited_retry", - "milliseconds": 1153, - "source": "local-ordinary-scaled" + "milliseconds": 2149, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.Selection_orders_by_availability_then_occurrence_then_ID_regardless_of_insert_order", - "milliseconds": 1079, - "source": "local-ordinary-scaled" + "milliseconds": 1480, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.Stored_routing_corruption_requests_terminal_without_acknowledging_the_fact", - "milliseconds": 4020, - "source": "local-ordinary-scaled" + "milliseconds": 3481, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.Subscriber_terminal_operation_is_declared_as_MUST_security_event", - "milliseconds": 854, - "source": "local-ordinary-scaled" + "milliseconds": 1163, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.Substituting_a_draft_or_transaction_against_the_actual_UPDATE_witness_rolls_back_both_writes", - "milliseconds": 7175, - "source": "local-ordinary-scaled" + "milliseconds": 9339, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.Terminal_audit_keeps_valid_trace_for_absent_causal_values_but_replaces_it_for_empty_values", - "milliseconds": 1910, - "source": "local-ordinary-scaled" + "milliseconds": 1683, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.Terminal_audit_uses_the_stored_tenant_organization_and_validated_causal_metadata", - "milliseconds": 2084, - "source": "local-ordinary-scaled" + "milliseconds": 2271, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.Two_independent_stores_contend_for_one_committed_live_lease", - "milliseconds": 953, - "source": "local-ordinary-scaled" + "milliseconds": 1273, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatchStoreTests.Wrong_claim_kind_refuses_before_changing_the_row_or_audit", - "milliseconds": 4647, - "source": "local-ordinary-scaled" + "milliseconds": 6280, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatcherRoleGuardTests.A_startup_role_switch_cannot_change_the_dispatcher_current_role", - "milliseconds": 203, - "source": "local-ordinary-scaled" + "milliseconds": 209, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatcherRoleGuardTests.App_membership_in_the_dispatcher_is_refused_directly_and_transitively_then_restoration_connects", - "milliseconds": 870, - "source": "local-ordinary-scaled" + "milliseconds": 1315, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatcherRoleGuardTests.Every_physical_connection_refuses_an_invalid_attribute_and_accepts_its_restoration", - "milliseconds": 1846, - "source": "local-ordinary-scaled" + "milliseconds": 1265, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatcherRoleGuardTests.Foreign_membership_is_refused_directly_and_through_a_bridge_then_restoration_connects", - "milliseconds": 599, - "source": "local-ordinary-scaled" + "milliseconds": 836, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxDispatcherRoleGuardTests.The_actual_outbox_role_connects_with_its_exact_bounded_attributes", - "milliseconds": 37, - "source": "local-ordinary-scaled" + "milliseconds": 261, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProcessorTests.A_failed_terminal_audit_reports_unhealthy_while_the_actual_healthz_remains_live", - "milliseconds": 1199, - "source": "local-ordinary-scaled" + "milliseconds": 1546, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProcessorTests.A_poison_first_row_terminalizes_with_MUST_audit_and_following_acceptance_progresses", - "milliseconds": 1400, - "source": "local-ordinary-scaled" + "milliseconds": 1848, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProcessorTests.A_real_unwrapped_publication_acknowledges_retained_delivery_without_business_construction", - "milliseconds": 1139, - "source": "local-ordinary-scaled" + "milliseconds": 902, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProcessorTests.Actual_host_startup_rejects_invalid_credentials_without_provider_or_secret_text", - "milliseconds": 4457, - "source": "local-ordinary-scaled" + "milliseconds": 8188, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", @@ -6492,44 +8119,44 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProcessorTests.Four_retained_callbacks_stop_all_acquisition_and_releasing_one_restores_capacity", - "milliseconds": 6588, - "source": "local-ordinary-scaled" + "milliseconds": 3942, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProcessorTests.Publication_failure_persists_a_closed_descriptor_and_allows_following_work", - "milliseconds": 1331, - "source": "local-ordinary-scaled" + "milliseconds": 1519, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProcessorTests.Real_provisioning_rows_remain_Pending_across_hosted_polls_without_construction_or_mutation", - "milliseconds": 1310, - "source": "local-ordinary-scaled" + "milliseconds": 1723, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProcessorTests.Shutdown_uses_one_finite_wait_for_all_four_retained_callbacks", - "milliseconds": 6125, - "source": "local-ordinary-scaled" + "milliseconds": 3111, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProcessorTests.Successful_claims_keep_the_snapshot_until_its_interval_and_refresh_at_the_boundary", - "milliseconds": 1488, - "source": "local-ordinary-scaled" + "milliseconds": 1120, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProcessorTests.Terminal_audit_backlog_cannot_starve_normal_publication_or_expired_claim_recovery", - "milliseconds": 22989, - "source": "local-ordinary-scaled" + "milliseconds": 17424, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProcessorTests.The_actual_API_registers_exactly_one_worker_and_boots_its_guarded_source", - "milliseconds": 1003, - "source": "local-ordinary-scaled" + "milliseconds": 1301, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", @@ -6540,410 +8167,410 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProcessorTests.Timeout_persists_failure_and_holds_the_partition_until_actual_callback_scope_cleanup", - "milliseconds": 2495, - "source": "local-ordinary-scaled" + "milliseconds": 2224, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProcessorTests.Two_independent_actual_processors_cannot_publish_or_claim_one_live_lease_twice", - "milliseconds": 1573, - "source": "local-ordinary-scaled" + "milliseconds": 1784, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProducerTests.A_duplicate_EventId_poisons_the_unit_without_creating_a_child_receipt", - "milliseconds": 62, - "source": "local-ordinary-scaled" + "milliseconds": 90, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProducerTests.A_raw_transaction_cannot_authorize_outbox_production_even_when_announced_or_joined", - "milliseconds": 86, - "source": "local-ordinary-scaled" + "milliseconds": 81, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProducerTests.A_real_MUST_audit_INSERT_failure_rolls_back_positively_observed_business_and_outbox_rows", - "milliseconds": 813, - "source": "local-ordinary-scaled" + "milliseconds": 820, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProducerTests.A_real_nested_command_keeps_its_MUST_intent_until_the_outbox_owner_commits", - "milliseconds": 824, - "source": "local-ordinary-scaled" + "milliseconds": 1044, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProducerTests.A_retained_producer_frame_refuses_a_reused_transaction_object_with_a_later_generation", - "milliseconds": 32, - "source": "local-ordinary-scaled" + "milliseconds": 41, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProducerTests.A_successful_owner_can_produce_in_a_later_generation_of_the_same_DI_scope", - "milliseconds": 806, - "source": "local-ordinary-scaled" + "milliseconds": 1240, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProducerTests.A_system_execution_preserves_only_its_separate_causal_human", - "milliseconds": 45, - "source": "local-ordinary-scaled" + "milliseconds": 120, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProducerTests.Actual_INSERT_receipts_prevent_an_absorbed_direct_or_descendant_refusal_from_committing", - "milliseconds": 70, - "source": "local-ordinary-scaled" + "milliseconds": 81, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProducerTests.An_HTTP_request_commits_the_enqueuing_trace_announced_scope_and_exact_partition", - "milliseconds": 3272, - "source": "local-ordinary-scaled" + "milliseconds": 1421, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProducerTests.An_organization_marked_event_requires_the_announced_organization", - "milliseconds": 33, - "source": "local-ordinary-scaled" + "milliseconds": 53, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProducerTests.An_outbox_cannot_borrow_a_producer_enrolled_on_another_unit_of_work", - "milliseconds": 45, - "source": "local-ordinary-scaled" + "milliseconds": 57, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProducerTests.Both_roots_insert_the_complete_runtime_event_before_business_and_MUST_audit_commit", - "milliseconds": 1798, - "source": "local-ordinary-scaled" + "milliseconds": 3822, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProducerTests.Cancellation_or_fault_after_observed_business_and_outbox_writes_rolls_both_back", - "milliseconds": 65, - "source": "local-ordinary-scaled" + "milliseconds": 67, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProducerTests.Enqueue_and_owner_completion_never_publish_to_the_transport", - "milliseconds": 924, - "source": "local-ordinary-scaled" + "milliseconds": 957, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProducerTests.Enqueue_refuses_an_unusable_event_tenant_or_transaction_before_INSERT", - "milliseconds": 103, - "source": "local-ordinary-scaled" + "milliseconds": 161, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProducerTests.Provisioning_uses_the_SQL_announcement_while_the_ambient_context_stays_unresolved", - "milliseconds": 28, - "source": "local-ordinary-scaled" + "milliseconds": 34, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.OutboxProducerTests.The_complete_canonical_UTF8_payload_has_an_inclusive_256_KiB_limit", - "milliseconds": 183, - "source": "local-ordinary-scaled" + "milliseconds": 205, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.P02d2FoundationTests.A_disabled_legacy_default_refuses_an_enabled_locale_independently_of_default_count", - "milliseconds": 246, - "source": "local-ordinary-scaled" + "milliseconds": 425, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.P02d2FoundationTests.Every_seed_query_runs_on_the_composed_pipeline_and_hides_foreign_or_sibling_roots", - "milliseconds": 200, - "source": "local-ordinary-scaled" + "milliseconds": 328, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.P02d2FoundationTests.Exact_reads_distinguish_new_bindings_from_pins_and_preserve_stored_descriptor_order", - "milliseconds": 879, - "source": "local-ordinary-scaled" + "milliseconds": 1323, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.P02d2FoundationTests.Locale_and_exact_definition_reads_use_the_same_announced_connection_and_do_not_fall_back", - "milliseconds": 57, - "source": "local-ordinary-scaled" + "milliseconds": 81, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformAdminScopeTests.A_Correctly_Named_Role_That_Lost_Bypass_Is_Refused_On_Connect", - "milliseconds": 155, - "source": "local-ordinary-scaled" + "milliseconds": 93, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformAdminScopeTests.A_Credential_Naming_Another_Role_Is_Refused_Before_Any_Connection", "milliseconds": 2, - "source": "local-ordinary-scaled" + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformAdminScopeTests.A_Faulted_Commit_Returns_The_Connection_And_Is_Left_Indeterminate", - "milliseconds": 76, - "source": "local-ordinary-scaled" + "milliseconds": 118, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformAdminScopeTests.A_Resolved_Handle_Cannot_Be_Used_Again", - "milliseconds": 32, - "source": "local-ordinary-scaled" + "milliseconds": 39, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformAdminScopeTests.A_Role_Promoted_To_Superuser_Is_Refused_On_Connect", - "milliseconds": 104, - "source": "local-ordinary-scaled" + "milliseconds": 62, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformAdminScopeTests.An_Abandoned_Handle_On_A_Dead_Connection_Still_Returns_It", - "milliseconds": 74, - "source": "local-ordinary-scaled" + "milliseconds": 125, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformAdminScopeTests.An_Absent_Credential_Names_The_Key_Rather_Than_Degrading", - "milliseconds": 1, - "source": "local-ordinary-scaled" + "milliseconds": 2, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformAdminScopeTests.An_Entry_Stays_On_The_Record_Whatever_The_Work_Then_Does", - "milliseconds": 74, - "source": "local-ordinary-scaled" + "milliseconds": 202, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformAdminScopeTests.An_Entry_That_Cannot_Be_Recorded_Is_Not_Entered", - "milliseconds": 40, - "source": "local-ordinary-scaled" + "milliseconds": 38, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformAdminScopeTests.Committing_Persists_And_Disposal_Leaves_It_Alone", - "milliseconds": 31, - "source": "local-ordinary-scaled" + "milliseconds": 44, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformAdminScopeTests.Disposing_Without_Committing_Rolls_Back", - "milliseconds": 35, - "source": "local-ordinary-scaled" + "milliseconds": 42, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformAdminScopeTests.Entry_Is_On_The_Record_Before_The_Operation_Runs", - "milliseconds": 33, - "source": "local-ordinary-scaled" + "milliseconds": 53, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformAdminScopeTests.Entry_Is_Recorded_At_Warning_With_The_Reason_And_The_Caller", - "milliseconds": 25, - "source": "local-ordinary-scaled" + "milliseconds": 48, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformAdminScopeTests.The_Scope_Connects_As_The_Platform_Role_On_Its_Own_Connection", - "milliseconds": 67, - "source": "local-ordinary-scaled" + "milliseconds": 72, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformAdminScopeTests.The_Scope_Sees_What_An_Application_Connection_Cannot", - "milliseconds": 46, - "source": "local-ordinary-scaled" + "milliseconds": 60, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformAdminScopeTests.Two_Concurrent_Entries_Get_Independent_Connections", - "milliseconds": 49, - "source": "local-ordinary-scaled" + "milliseconds": 57, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformSchemaTests.EachChainHasItsOwnHistoryTable", - "milliseconds": 4, - "source": "local-ordinary-scaled" + "milliseconds": 15, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformSchemaTests.TheApplicationRoleCanOnlyEnqueue", - "milliseconds": 6, - "source": "local-ordinary-scaled" + "milliseconds": 11, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformSchemaTests.TheDispatcherHoldsExactlyTheEightStatusColumnUpdateGrant", - "milliseconds": 17, - "source": "local-ordinary-scaled" + "milliseconds": 37, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformSchemaTests.TheDispatcherReadsEveryTenantWithNoTenantContext", - "milliseconds": 11, - "source": "local-ordinary-scaled" + "milliseconds": 8, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformSchemaTests.TheIdempotencyBodyCapIsEnforcedByTheDatabase", - "milliseconds": 17, - "source": "local-ordinary-scaled" + "milliseconds": 21, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformSchemaTests.TheIdempotencyClosedSetsAreEnforcedByTheDatabase", - "milliseconds": 16, - "source": "local-ordinary-scaled" + "milliseconds": 22, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformSchemaTests.TheIdempotencyOutcomeShapeMatchesItsState", - "milliseconds": 9, - "source": "local-ordinary-scaled" + "milliseconds": 23, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PlatformSchemaTests.TheOutboxIdDefaultsToAVersion7Uuid", - "milliseconds": 4, - "source": "local-ordinary-scaled" + "milliseconds": 11, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PoolHangfireStorageParityTests.Real_extended_reads_writes_and_unsupported_features_match_the_guarded_provider", - "milliseconds": 1484, - "source": "local-ordinary-scaled" + "milliseconds": 1686, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PoolHangfireStorageParityTests.Real_lifecycle_lock_and_fetched_job_keep_stock_semantics_through_actual_disposal", - "milliseconds": 1098, - "source": "local-ordinary-scaled" + "milliseconds": 1271, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PoolHangfireStorageParityTests.Real_storage_keeps_features_extended_casts_monitoring_and_frozen_component_instances", - "milliseconds": 930, - "source": "local-ordinary-scaled" + "milliseconds": 892, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.ProducerExecutionTests.A_direct_owner_constructs_its_handler_after_admission_and_writes_one_correct_MUST_row", - "milliseconds": 802, - "source": "local-ordinary-scaled" + "milliseconds": 1220, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.ProducerExecutionTests.A_leaked_frame_refuses_completion_with_a_failed_not_indeterminate_audit", - "milliseconds": 1630, - "source": "local-ordinary-scaled" + "milliseconds": 2554, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.ProducerExecutionTests.A_no_listener_boundary_has_a_W3C_trace_and_cleans_every_exit", - "milliseconds": 83, - "source": "local-ordinary-scaled" + "milliseconds": 126, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.ProducerExecutionTests.A_raw_announced_transaction_and_its_joiner_cannot_authorize_production", - "milliseconds": 43, - "source": "local-ordinary-scaled" + "milliseconds": 45, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.ProducerExecutionTests.A_real_direct_MUST_audit_failure_rolls_back_a_positively_observed_business_write", - "milliseconds": 805, - "source": "local-ordinary-scaled" + "milliseconds": 1295, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.ProducerExecutionTests.A_stale_owner_cannot_confer_production_authority_on_a_new_transaction_joiner", - "milliseconds": 24, - "source": "local-ordinary-scaled" + "milliseconds": 22, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.ProducerExecutionTests.An_Off_direct_owner_preserves_nested_command_intents_and_clears_only_after_commit", - "milliseconds": 814, - "source": "local-ordinary-scaled" + "milliseconds": 1002, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.ProducerExecutionTests.An_absorbed_producer_refusal_rolls_back_direct_and_descendant_work", - "milliseconds": 94, - "source": "local-ordinary-scaled" + "milliseconds": 119, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.ProducerExecutionTests.An_event_free_absorbed_refusal_can_commit_its_observed_mutation", - "milliseconds": 787, - "source": "local-ordinary-scaled" + "milliseconds": 941, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.ProducerExecutionTests.An_unregistered_direct_owner_is_refused_before_its_handler_factory_runs", - "milliseconds": 4, - "source": "local-ordinary-scaled" + "milliseconds": 8, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.ProducerExecutionTests.Both_compositions_reconcile_an_independent_scope_inside_another_audit_execution", - "milliseconds": 1758, - "source": "local-ordinary-scaled" + "milliseconds": 2556, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicAdmissionRenderingTests.Native_admission_preserves_wire_failures_request_lifetimes_and_browser_fallback", - "milliseconds": 78185, - "source": "local-ordinary-scaled" + "milliseconds": 63199, + "source": "pr38-df-1-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationHttpTests.Absent_level_and_nullable_summary_stay_null_in_the_actual_wire_contract", - "milliseconds": 210, - "source": "local-ordinary-scaled" + "milliseconds": 224, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationHttpTests.Catalog_and_outline_seek_pages_are_forward_only_and_binding_survives_limit_changes", - "milliseconds": 484, - "source": "local-ordinary-scaled" + "milliseconds": 600, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationHttpTests.Catalog_is_exact_locale_host_scoped_and_only_marketing_with_no_normal_audit", - "milliseconds": 454, - "source": "local-ordinary-scaled" + "milliseconds": 225, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationHttpTests.Course_and_lesson_use_exact_translations_and_real_alternate_url_pairs", - "milliseconds": 263, - "source": "local-ordinary-scaled" + "milliseconds": 294, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationHttpTests.Course_draft_branch_foreign_and_unknown_are_uniformly_hidden", - "milliseconds": 927, - "source": "local-ordinary-scaled" + "milliseconds": 481, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationHttpTests.Deleted_catalog_and_outline_anchors_continue_by_seek_and_restart_uses_current_rows", - "milliseconds": 312, - "source": "local-ordinary-scaled" + "milliseconds": 304, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", @@ -6954,14 +8581,14 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationHttpTests.Disabled_locale_and_empty_enabled_set_are_unsupported_even_after_a_successful_read", - "milliseconds": 255, - "source": "local-ordinary-scaled" + "milliseconds": 195, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationHttpTests.Enabled_untranslated_locale_returns_empty_catalog_and_hidden_details_without_fallback", - "milliseconds": 273, - "source": "local-ordinary-scaled" + "milliseconds": 151, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", @@ -6972,38 +8599,38 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationHttpTests.Get_head_and_conditional_requests_share_status_no_store_and_head_has_no_body", - "milliseconds": 1588, - "source": "local-ordinary-scaled" + "milliseconds": 635, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationHttpTests.Lesson_masks_draft_parent_draft_restricted_scope_wrong_parent_and_foreign_rows", - "milliseconds": 1718, - "source": "local-ordinary-scaled" + "milliseconds": 728, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationHttpTests.Malformed_cursor_unicode_is_a_bounded_400_before_data_access", - "milliseconds": 1123, - "source": "local-ordinary-scaled" + "milliseconds": 515, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationHttpTests.Missing_exact_translation_never_uses_default_content_or_advertises_disabled_alternates", - "milliseconds": 502, - "source": "local-ordinary-scaled" + "milliseconds": 308, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationHttpTests.Organization_host_never_serves_a_sibling_organization", - "milliseconds": 789, - "source": "local-ordinary-scaled" + "milliseconds": 485, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationHttpTests.Out_of_band_body_shape_is_bounded_and_raw_or_unknown_payload_never_escapes", - "milliseconds": 654, - "source": "local-ordinary-scaled" + "milliseconds": 542, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", @@ -7014,128 +8641,128 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationHttpTests.Query_shape_refusals_happen_before_configuration_or_data_read", - "milliseconds": 2573, - "source": "local-ordinary-scaled" + "milliseconds": 766, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationHttpTests.Restricted_course_has_marketing_but_no_inventory_and_nonexistent_lesson_is_same_refusal", - "milliseconds": 265, - "source": "local-ordinary-scaled" + "milliseconds": 209, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationHttpTests.Seeded_public_http_measurement_records_first_and_warm_requests_without_a_production_p95_claim", - "milliseconds": 1484, - "source": "local-ordinary-scaled" + "milliseconds": 1405, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationHttpTests.Source_eligibility_is_fresh_after_success_and_warmed_definition_cache", - "milliseconds": 1307, - "source": "local-ordinary-scaled" + "milliseconds": 930, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationHttpTests.Well_formed_unsupported_locale_is_400_and_headers_do_not_replace_explicit_locale", - "milliseconds": 691, - "source": "local-ordinary-scaled" + "milliseconds": 325, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationStoreTests.Claim_narrowing_cannot_make_a_tenant_host_publish_organization_rows", - "milliseconds": 10, - "source": "local-ordinary-scaled" + "milliseconds": 102, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationStoreTests.Equal_timestamp_and_sort_anchors_use_postgresql_uuid_tiebreaking", - "milliseconds": 27, - "source": "local-ordinary-scaled" + "milliseconds": 90, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationStoreTests.Public_port_refuses_missing_provenance_or_read_transaction_before_data_sql", - "milliseconds": 63, - "source": "local-ordinary-scaled" + "milliseconds": 98, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationStoreTests.Source_queries_project_no_body_before_eligibility_and_real_app_role_plans_are_recorded", - "milliseconds": 33, - "source": "local-ordinary-scaled" + "milliseconds": 90, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicEducationStoreTests.Tenant_scope_hatch_cannot_widen_the_public_hosts_explicit_predicates", - "milliseconds": 25, - "source": "local-ordinary-scaled" + "milliseconds": 82, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicLocalLaunchTests.Demo_API_runtime_rejects_a_foreign_user_secret_only_with_profile_isolation", - "milliseconds": 7592, - "source": "local-ordinary-scaled" + "milliseconds": 24128, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicLocalLaunchTests.Public_local_API_launcher_serves_seeded_reads_without_a_PlatformAdmin_credential", - "milliseconds": 24475, - "source": "local-ordinary-scaled" + "milliseconds": 62144, + "source": "pr38-df-2-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicLocaleEvolutionHttpTests.Organization_branding_writer_is_refused_with_denied_audit_and_mapped_host_keeps_tenant_palette", - "milliseconds": 5668, - "source": "local-ordinary-scaled" + "milliseconds": 10599, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicLocaleEvolutionHttpTests.Public_host_locale_and_organization_contracts_hold_together_with_exact_request_connection_translation_scope", - "milliseconds": 6377, - "source": "local-ordinary-scaled" + "milliseconds": 8312, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicLocaleEvolutionHttpTests.Third_locale_authored_through_api_commands_serves_exact_new_urls_without_changing_existing_responses_or_migrations", - "milliseconds": 7071, - "source": "local-ordinary-scaled" + "milliseconds": 8205, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicReadTransactionTests.Cancelled_handler_rolls_back_and_pooled_next_scope_is_writable", - "milliseconds": 38, - "source": "local-ordinary-scaled" + "milliseconds": 58, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicReadTransactionTests.Mixed_mode_refusal_poisons_an_outer_owner_even_when_absorbed", - "milliseconds": 39, - "source": "local-ordinary-scaled" + "milliseconds": 63, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicReadTransactionTests.Partial_read_only_setup_failure_cleans_up_before_begin_throws", - "milliseconds": 42, - "source": "local-ordinary-scaled" + "milliseconds": 145, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicReadTransactionTests.PublicSurface_Transactions_Refuse_Writes", - "milliseconds": 140, - "source": "local-ordinary-scaled" + "milliseconds": 241, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicReadTransactionTests.Read_only_mode_is_active_at_begin_return_and_resets_after_success", - "milliseconds": 42, - "source": "local-ordinary-scaled" + "milliseconds": 56, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicReadTransactionTests.Setup_failure_after_server_mode_activation_cleans_up_before_begin_returns", - "milliseconds": 54, - "source": "local-ordinary-scaled" + "milliseconds": 79, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", @@ -7146,8 +8773,8 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicServerRenderingTests.Production_rendering_is_host_isolated_fresh_and_private_through_the_real_public_API", - "milliseconds": 144446, - "source": "local-ordinary-scaled" + "milliseconds": 160701, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", @@ -7158,44 +8785,44 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicSiteHttpTests.Disposed_public_test_clients_release_their_database_pools", - "milliseconds": 620, - "source": "local-ordinary-scaled" + "milliseconds": 312, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicSiteHttpTests.Effective_entitlement_changes_attribution_only", - "milliseconds": 860, - "source": "local-ordinary-scaled" + "milliseconds": 388, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicSiteHttpTests.Head_success_validation_routing_and_exception_responses_are_bodyless_no_store", - "milliseconds": 455, - "source": "local-ordinary-scaled" + "milliseconds": 247, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicSiteHttpTests.Invalid_default_or_stored_tag_is_dependency_unavailable_without_default_guessing", - "milliseconds": 503, - "source": "local-ordinary-scaled" + "milliseconds": 319, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicSiteHttpTests.Invalid_deleted_or_absent_theme_uses_null_whole_value", - "milliseconds": 675, - "source": "local-ordinary-scaled" + "milliseconds": 285, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicSiteHttpTests.Live_mapping_does_not_serve_an_inactive_tenant", - "milliseconds": 750, - "source": "local-ordinary-scaled" + "milliseconds": 487, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicSiteHttpTests.Locale_display_order_uses_sort_then_ordinal_canonical_tag", - "milliseconds": 202, - "source": "local-ordinary-scaled" + "milliseconds": 131, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", @@ -7206,14 +8833,14 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicSiteHttpTests.Organization_host_checks_the_mapped_organization_live_state", - "milliseconds": 847, - "source": "local-ordinary-scaled" + "milliseconds": 513, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicSiteHttpTests.Production_public_endpoint_inventory_is_exact_get_and_head", - "milliseconds": 3, - "source": "local-ordinary-scaled" + "milliseconds": 5, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", @@ -7224,392 +8851,398 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicSiteHttpTests.Site_rejects_every_query_parameter_before_loading_configuration", - "milliseconds": 606, - "source": "local-ordinary-scaled" + "milliseconds": 260, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicSiteHttpTests.Unknown_and_platform_hosts_keep_their_generic_refusals", - "milliseconds": 727, - "source": "local-ordinary-scaled" + "milliseconds": 269, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.PublicSiteHttpTests.Valid_empty_or_all_disabled_configuration_hides_site", - "milliseconds": 470, - "source": "local-ordinary-scaled" + "milliseconds": 309, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.SeederTests.A_conflict_that_is_not_a_uniqueness_refusal_still_stops_the_run", - "milliseconds": 142, - "source": "local-ordinary-scaled" + "milliseconds": 215, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.SeederTests.A_failure_that_is_not_a_conflict_stops_the_run", - "milliseconds": 31, - "source": "local-ordinary-scaled" + "milliseconds": 25, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.SeederTests.A_host_naming_another_tenants_organization_is_refused_not_crashed", - "milliseconds": 4621, - "source": "local-ordinary-scaled" + "milliseconds": 6040, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.SeederTests.A_live_built_in_with_a_different_semantic_shape_is_refused_before_any_writer", - "milliseconds": 3379, - "source": "local-ordinary-scaled" + "milliseconds": 5995, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.SeederTests.A_seed_host_another_tenant_already_holds_stops_the_run", - "milliseconds": 192, - "source": "local-ordinary-scaled" + "milliseconds": 255, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.SeederTests.An_authored_definition_whose_id_another_tenant_holds_stops_the_run", - "milliseconds": 4600, - "source": "local-ordinary-scaled" + "milliseconds": 7661, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.SeederTests.An_organization_whose_id_another_tenant_holds_stops_the_run", - "milliseconds": 1934, - "source": "local-ordinary-scaled" + "milliseconds": 2648, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.SeederTests.Built_in_verification_refuses_a_different_active_revision_without_retiring_or_rebinding_it", - "milliseconds": 1362, - "source": "local-ordinary-scaled" + "milliseconds": 1802, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.SeederTests.Complete_inventory_has_exact_states_pins_translations_and_null_or_exact_write_scope", - "milliseconds": 4971, - "source": "local-ordinary-scaled" + "milliseconds": 6774, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.SeederTests.Completed_seed_mismatch_fails_without_mutating_any_existing_row_or_audit", - "milliseconds": 92093, - "source": "local-ordinary-scaled" + "milliseconds": 128893, + "source": "pr38-df-2-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.SeederTests.Concurrent_seeds_prove_a_real_provisioning_race_and_converge_without_duplicates", - "milliseconds": 7472, - "source": "local-ordinary-scaled" + "milliseconds": 9845, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.SeederTests.Concurrent_translation_writers_recheck_the_completed_act_after_a_real_non_provisioning_race", - "milliseconds": 2867, - "source": "local-ordinary-scaled" + "milliseconds": 3773, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.SeederTests.Every_seeded_tenant_starts_with_a_live_content_type_and_level_taxonomy", - "milliseconds": 4400, - "source": "local-ordinary-scaled" + "milliseconds": 6559, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.SeederTests.Interrupted_authoring_resumes_without_rewriting_completed_acts", - "milliseconds": 12881, - "source": "local-ordinary-scaled" + "milliseconds": 21002, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.SeederTests.Matching_built_ins_with_independently_generated_ids_are_preserved_without_any_writer", - "milliseconds": 353, - "source": "local-ordinary-scaled" + "milliseconds": 420, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.SeederTests.Preserved_built_in_history_without_an_active_default_refuses_without_business_mutation", - "milliseconds": 3289, - "source": "local-ordinary-scaled" + "milliseconds": 3393, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.SeederTests.Running_the_seed_twice_changes_nothing_and_still_succeeds", - "milliseconds": 5810, - "source": "local-ordinary-scaled" + "milliseconds": 6553, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.SeederTests.Seeder_process_returns_zero_on_repeat_and_nonzero_on_mismatch", - "milliseconds": 14434, - "source": "local-ordinary-scaled" + "milliseconds": 18399, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.SeederTests.Semantic_json_property_order_does_not_turn_a_completed_act_into_a_write", - "milliseconds": 5208, - "source": "local-ordinary-scaled" + "milliseconds": 6631, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.SeederTests.The_built_ins_are_the_tenant_s_own_rows_and_not_shared", - "milliseconds": 4745, - "source": "local-ordinary-scaled" + "milliseconds": 6475, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.SeederTests.The_seed_writes_two_tenants_each_with_two_organizations_and_one_host", - "milliseconds": 4409, - "source": "local-ordinary-scaled" + "milliseconds": 5284, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.SeederTests.The_two_host_rows_exercise_both_live_classifications", - "milliseconds": 5019, - "source": "local-ordinary-scaled" + "milliseconds": 5912, + "source": "p031-hosted-ordinary-4" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.StorageRelationCensusTests.Catalogue_discovers_each_persistent_relation_kind", + "milliseconds": 269, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.ASoftDeletedDomainReleasesItsHostToAnotherTenant", - "milliseconds": 9, - "source": "local-ordinary-scaled" + "milliseconds": 13, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.An_Entitlement_With_No_Scheduled_Expiry_Persists_As_Null", - "milliseconds": 5, - "source": "local-ordinary-scaled" + "milliseconds": 7, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.An_Organization_Scoped_Session_Cannot_Write_A_Tenant_Wide_Row", - "milliseconds": 1610, - "source": "local-ordinary-scaled" + "milliseconds": 2476, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.App_Role_Cannot_Enumerate_Host_Map", - "milliseconds": 3, - "source": "local-ordinary-scaled" + "milliseconds": 11, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.App_Role_Cannot_Enumerate_Tenants", - "milliseconds": 4, - "source": "local-ordinary-scaled" + "milliseconds": 13, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.EveryMappedIdentifierIsSnakeCase", - "milliseconds": 6, - "source": "local-ordinary-scaled" + "milliseconds": 20, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.EveryTableEnablesAndForcesRowLevelSecurity", - "milliseconds": 30, - "source": "local-ordinary-scaled" + "milliseconds": 26, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.Every_Foreign_Key_Has_A_Supporting_Index", - "milliseconds": 93, - "source": "local-ordinary-scaled" + "milliseconds": 15, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.Every_WithCheck_Policy_Has_A_Foreign_Write_Case", - "milliseconds": 17, - "source": "local-ordinary-scaled" + "milliseconds": 36, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.Exactly_One_Policy_In_The_Schema_Reads_Unconditionally", - "milliseconds": 6, - "source": "local-ordinary-scaled" + "milliseconds": 12, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.NoTableCarriesTwoPermissivePoliciesForOneCommand", - "milliseconds": 5, - "source": "local-ordinary-scaled" + "milliseconds": 25, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.Org_X_cannot_read_Org_Y_within_TenantA", - "milliseconds": 3, - "source": "local-ordinary-scaled" + "milliseconds": 7, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.OrganizationIdIsImmutableAfterInsert", - "milliseconds": 4, - "source": "local-ordinary-scaled" + "milliseconds": 13, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.Owner_Write_With_Foreign_TenantId_Is_Rejected_By_WithCheck", - "milliseconds": 4, - "source": "local-ordinary-scaled" + "milliseconds": 19, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.Reassigning_An_Owned_Row_To_Another_Tenant_Is_Rejected", - "milliseconds": 14, - "source": "local-ordinary-scaled" + "milliseconds": 22, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.TenantWide_Row_Of_TenantB_Is_Invisible_To_TenantA", - "milliseconds": 4, - "source": "local-ordinary-scaled" + "milliseconds": 12, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.Tenant_A_Cannot_Repoint_Tenant_B_Host", - "milliseconds": 8, - "source": "local-ordinary-scaled" + "milliseconds": 19, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.Tenant_A_cannot_read_Tenant_B_data", - "milliseconds": 96, - "source": "local-ordinary-scaled" + "milliseconds": 65, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.TheGrantMatrixIsExactlyWhatTheMigrationsWrote", - "milliseconds": 48, - "source": "local-ordinary-scaled" + "milliseconds": 62, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.TheOwnerIsDeniedOnThePlatformScopedTable", - "milliseconds": 8, - "source": "local-ordinary-scaled" + "milliseconds": 14, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.TheResolvingHostAdmitsExactlyItsOwnRowBeforeAnyTenantContext", - "milliseconds": 4, - "source": "local-ordinary-scaled" + "milliseconds": 9, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.TheTenantScopeHatchWidensReadsAndNeitherWrite", - "milliseconds": 6, - "source": "local-ordinary-scaled" + "milliseconds": 17, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.The_table_class_sweep_rejects_unknown_tables_including_history_lookalikes", - "milliseconds": 89, - "source": "local-ordinary-scaled" + "milliseconds": 72, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.Unsetting_tenant_context_returns_zero_rows_through_RLS", - "milliseconds": 75, - "source": "local-ordinary-scaled" + "milliseconds": 80, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancySchemaTests.Write_With_Foreign_TenantId_Is_Rejected_By_WithCheck", - "milliseconds": 5395, - "source": "local-ordinary-scaled" + "milliseconds": 8880, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancyWriterTests.A_failed_must_audit_rolls_back_the_already_saved_branding_root", - "milliseconds": 846, - "source": "local-ordinary-scaled" + "milliseconds": 1262, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancyWriterTests.Branding_is_create_or_exact_replace_only_and_cannot_touch_foreign_or_generic_settings", - "milliseconds": 1054, - "source": "local-ordinary-scaled" + "milliseconds": 1646, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancyWriterTests.Branding_refuses_missing_or_deleted_tenants_before_setting_access", - "milliseconds": 4078, - "source": "local-ordinary-scaled" + "milliseconds": 5474, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancyWriterTests.Concurrent_locale_changes_commit_only_one_exact_root_version", - "milliseconds": 2443, - "source": "local-ordinary-scaled" + "milliseconds": 3062, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancyWriterTests.Concurrent_palette_creates_leave_one_setting_and_one_successful_audit", - "milliseconds": 952, - "source": "local-ordinary-scaled" + "milliseconds": 1407, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancyWriterTests.Concurrent_palette_replacements_cannot_mix_colors_or_commit_two_successful_versions", - "milliseconds": 979, - "source": "local-ordinary-scaled" + "milliseconds": 1401, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancyWriterTests.Disabled_legacy_default_is_not_implicitly_repaired_by_either_locale_writer", - "milliseconds": 951, - "source": "local-ordinary-scaled" + "milliseconds": 1085, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancyWriterTests.Enabled_without_default_is_refused_by_writers_before_root_or_navigation_mutation", - "milliseconds": 960, - "source": "local-ordinary-scaled" + "milliseconds": 1378, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancyWriterTests.Locale_commands_promote_first_enabled_then_switch_existing_and_new_defaults_atomically", - "milliseconds": 1111, - "source": "local-ordinary-scaled" + "milliseconds": 1608, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancyWriterTests.Locale_writers_use_the_current_tenant_and_never_change_foreign_locales", - "milliseconds": 1042, - "source": "local-ordinary-scaled" + "milliseconds": 1161, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancyWriterTests.Second_default_save_failure_rolls_back_the_first_clear_and_root_stamp_from_a_fresh_scope", - "milliseconds": 1061, - "source": "local-ordinary-scaled" + "milliseconds": 1026, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancyWriterTests.Soft_deleted_tenants_are_not_write_targets_and_live_lookup_keeps_locales_and_flags", - "milliseconds": 991, - "source": "local-ordinary-scaled" + "milliseconds": 937, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancyWriterTests.Unknown_unique_constraints_remain_database_faults_and_roll_back", - "milliseconds": 1916, - "source": "local-ordinary-scaled" + "milliseconds": 2911, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenancyWriterTests.Whole_json_value_is_redacted_in_the_capture_and_durable_setting_audit", - "milliseconds": 797, - "source": "local-ordinary-scaled" + "milliseconds": 909, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantAssertionAuditTests.An_anonymous_burst_lands_one_row_however_long_the_run_is", - "milliseconds": 40, - "source": "local-ordinary-scaled" + "milliseconds": 27, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", @@ -7617,281 +9250,377 @@ "milliseconds": 25, "source": "local-ordinary-scaled" }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.TenantAssertionAuditTests.An_authenticated_mismatch_lands_an_attributed_tenant_wide_row", + "milliseconds": 74, + "source": "p031-hosted-ordinary-3" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.TenantAuthenticationRejectionAuditTests.An_unavailable_audit_source_preserves_refusal_and_row_14_never_touches_it", + "milliseconds": 1032, + "source": "p031-hosted-ordinary-6" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.TenantAuthenticationRejectionAuditTests.Organization_host_disagreement_persists_host_scope_as_metadata_in_a_tenant_wide_row", + "milliseconds": 504, + "source": "p031-hosted-ordinary-5" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.TenantAuthenticationRejectionAuditTests.Real_token_membership_denials_persist_only_row_7_without_announcing_an_unconfirmed_tenant", + "milliseconds": 825, + "source": "p031-hosted-ordinary-2" + }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantContextGuardTests.A_Nested_Frame_Inherits_The_Announcement", - "milliseconds": 25, - "source": "local-ordinary-scaled" + "milliseconds": 37, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantContextGuardTests.A_Save_Reports_The_Guard_Through_The_Wrapper_EF_Puts_Round_It", - "milliseconds": 23, - "source": "local-ordinary-scaled" + "milliseconds": 29, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantContextGuardTests.A_Scalar_Command_Is_Guarded_Too", - "milliseconds": 25, - "source": "local-ordinary-scaled" + "milliseconds": 34, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantContextGuardTests.A_Second_Transaction_Does_Not_Inherit_The_First_Ones_Announcement", - "milliseconds": 22, - "source": "local-ordinary-scaled" + "milliseconds": 40, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantContextGuardTests.A_Synchronous_Read_Is_Guarded_Too", - "milliseconds": 30, - "source": "local-ordinary-scaled" + "milliseconds": 47, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantContextGuardTests.An_Announced_Transaction_Is_Let_Through", - "milliseconds": 38, - "source": "local-ordinary-scaled" + "milliseconds": 70, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantContextGuardTests.An_Announcement_Vouches_For_Its_Own_Transaction_And_No_Other", - "milliseconds": 38, - "source": "local-ordinary-scaled" + "milliseconds": 30, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantContextGuardTests.An_Unannounced_Raw_Sql_Write_Throws_Too", - "milliseconds": 32, - "source": "local-ordinary-scaled" + "milliseconds": 23, + "source": "p031-hosted-ordinary-8" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.TenantContextGuardTests.An_Unannounced_Read_Throws_Instead_Of_Returning_Nothing", + "milliseconds": 29, + "source": "p031-hosted-ordinary-8" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.TenantContextGuardTests.Without_The_Guard_An_Unannounced_Read_Is_Silent_And_Empty", + "milliseconds": 19, + "source": "p031-hosted-ordinary-10" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.TenantCreatedProducerTests.Provisioning_business_outbox_and_both_MUST_rows_share_one_commit", + "milliseconds": 5208, + "source": "p031-hosted-ordinary-6" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.TenantExistingBindingAdmissionTests.Actorless_and_equal_evidence_resolve_the_stored_actor_before_the_real_tenant_read", + "milliseconds": 8088, + "source": "p031-hosted-ordinary-1" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.TenantExistingBindingAdmissionTests.Actual_host_startup_requires_the_installed_authority_exact_configuration_and_application_role", + "milliseconds": 5769, + "source": "p031-hosted-ordinary-0" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.TenantExistingBindingAdmissionTests.Actual_store_permission_fault_is_uniform_401_with_a_fixed_private_diagnostic_and_recovers", + "milliseconds": 6466, + "source": "p031-hosted-ordinary-8" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.TenantExistingBindingAdmissionTests.Anonymous_and_earlier_refusals_do_no_binding_work_and_exhausted_subject_quota_precedes_SQL", + "milliseconds": 5220, + "source": "p031-hosted-ordinary-10" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.TenantExistingBindingAdmissionTests.Committed_nonadmitting_or_collision_state_is_rechecked_without_an_identity_cache", + "milliseconds": 18485, + "source": "pr38-a-ordinary-7" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.TenantExistingBindingAdmissionTests.Completed_binding_returns_the_connector_before_its_HTTP_scope_dispatches_tenant_work", + "milliseconds": 7996, + "source": "pr38-b-ordinary-0" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.TenantExistingBindingAdmissionTests.Identity_FromSql_failures_keep_a_fixed_read_signal_for_sync_and_async_commands", + "milliseconds": 109, + "source": "p031-hosted-ordinary-11" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.TenantExistingBindingAdmissionTests.Real_blocked_lookup_cancellation_releases_the_owner_and_reuses_one_clean_physical_connector", + "milliseconds": 7663, + "source": "p031-hosted-ordinary-4" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.Database.TenantExistingBindingAdmissionTests.Sibling_query_failure_preserves_its_existing_EF_iteration_event_and_span_description", + "milliseconds": 89, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.TenantContextGuardTests.An_Unannounced_Read_Throws_Instead_Of_Returning_Nothing", - "milliseconds": 22, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.TenantExistingBindingAdmissionTests.Small_real_HTTP_sample_reports_lookup_plan_statement_cost_and_bounded_concurrent_pool_occupancy", + "milliseconds": 9262, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.TenantContextGuardTests.Without_The_Guard_An_Unannounced_Read_Is_Silent_And_Empty", - "milliseconds": 22, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.TenantExistingBindingAdmissionTests.Unknown_and_conflicting_bindings_refuse_even_public_reads_without_allocation_or_adoption", + "milliseconds": 7631, + "source": "pr38-a-ordinary-10" }, { "assembly": "learnstack.tests.integration", - "method": "LearnStack.Tests.Integration.Database.TenantCreatedProducerTests.Provisioning_business_outbox_and_both_MUST_rows_share_one_commit", - "milliseconds": 3643, - "source": "local-ordinary-scaled" + "method": "LearnStack.Tests.Integration.Database.TenantExistingBindingAdmissionTests.Value_bearing_binding_read_failure_has_fixed_HTTP_diagnostics_and_recovers_with_exact_RLS_cleanup", + "milliseconds": 7800, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantIsolationHttpTests.An_unresolved_request_reads_no_customization", - "milliseconds": 46, - "source": "local-ordinary-scaled" + "milliseconds": 2585, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantIsolationHttpTests.Org_X_cannot_read_Org_Y_within_TenantA", - "milliseconds": 15, - "source": "local-ordinary-scaled" + "milliseconds": 1659, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantIsolationHttpTests.TenantWide_Row_Of_TenantB_Is_Invisible_To_TenantA", - "milliseconds": 21, - "source": "local-ordinary-scaled" + "milliseconds": 1265, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantIsolationHttpTests.Tenant_A_cannot_read_Tenant_B_customizations", - "milliseconds": 91, - "source": "local-ordinary-scaled" + "milliseconds": 465, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantIsolationHttpTests.Tenant_A_cannot_read_Tenant_B_data", - "milliseconds": 33, - "source": "local-ordinary-scaled" + "milliseconds": 908, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantIsolationHttpTests.The_policy_holds_the_customization_tables_without_the_filter", - "milliseconds": 36, - "source": "local-ordinary-scaled" + "milliseconds": 192, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantIsolationHttpTests.Unsetting_tenant_context_returns_zero_rows_through_RLS", - "milliseconds": 479, - "source": "local-ordinary-scaled" + "milliseconds": 2600, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantIsolationHttpTests.Write_With_Foreign_TenantId_Is_Rejected_By_WithCheck", - "milliseconds": 67, - "source": "local-ordinary-scaled" + "milliseconds": 1092, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantLocaleDefaultTests.A_Non_Default_Locale_Is_Not_Constrained", - "milliseconds": 28, - "source": "local-ordinary-scaled" + "milliseconds": 27, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantLocaleDefaultTests.A_Second_Default_For_One_Tenant_Is_Refused", - "milliseconds": 22, - "source": "local-ordinary-scaled" + "milliseconds": 29, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantLocaleDefaultTests.Clearing_The_Incumbent_First_Is_What_Makes_A_Swap_Possible", "milliseconds": 30, - "source": "local-ordinary-scaled" + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantLocaleDefaultTests.Promoting_A_Default_Through_The_Aggregate_Survives_The_Index", - "milliseconds": 50, - "source": "local-ordinary-scaled" + "milliseconds": 67, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantLocaleEnabledMigrationTests.Invalid_legacy_default_blocks_migration_without_repair_and_valid_rows_survive_down_reapply", - "milliseconds": 470, - "source": "local-ordinary-scaled" + "milliseconds": 303, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantProvisioningTests.A_name_already_taken_is_an_answer_rather_than_a_crash", - "milliseconds": 124, - "source": "local-ordinary-scaled" + "milliseconds": 162, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantProvisioningTests.A_provisioning_that_fails_part_way_commits_nothing", - "milliseconds": 38, - "source": "local-ordinary-scaled" + "milliseconds": 49, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantProvisioningTests.A_refused_write_does_not_ride_along_on_the_next_save", - "milliseconds": 31, - "source": "local-ordinary-scaled" + "milliseconds": 42, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantProvisioningTests.A_request_that_does_not_provision_still_fails_closed_when_unresolved", - "milliseconds": 25, - "source": "local-ordinary-scaled" + "milliseconds": 46, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantProvisioningTests.A_resolved_caller_cannot_provision_a_tenant_it_did_not_authenticate_for", - "milliseconds": 38, - "source": "local-ordinary-scaled" + "milliseconds": 31, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantProvisioningTests.Provisioning_commits_the_tenant_its_default_organization_and_the_assignment", - "milliseconds": 34, - "source": "local-ordinary-scaled" + "milliseconds": 60, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantProvisioningTests.The_announcement_confines_the_transaction_to_the_tenant_being_created", - "milliseconds": 28, - "source": "local-ordinary-scaled" + "milliseconds": 44, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantProvisioningTests.The_announcement_does_not_survive_the_commit", - "milliseconds": 33, - "source": "local-ordinary-scaled" + "milliseconds": 53, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantProvisioningTests.Updating_a_detached_aggregate_is_refused_rather_than_guessed_at", - "milliseconds": 27, - "source": "local-ordinary-scaled" + "milliseconds": 53, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantSettingsAccessorTests.Branding_registration_stays_tenant_wide_and_returns_a_complete_validated_palette", - "milliseconds": 38, - "source": "local-ordinary-scaled" + "milliseconds": 60, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantSettingsAccessorTests.Malformed_key_values_are_refused_and_a_detached_context_is_not_admitted", - "milliseconds": 38, - "source": "local-ordinary-scaled" + "milliseconds": 52, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantSettingsAccessorTests.Missing_announcement_and_cancellation_are_loud_before_a_settings_query", - "milliseconds": 22, - "source": "local-ordinary-scaled" + "milliseconds": 19, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantSettingsAccessorTests.Non_shape_parser_failures_remain_loud", - "milliseconds": 68, - "source": "local-ordinary-scaled" + "milliseconds": 84, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantSettingsAccessorTests.Organization_scope_selects_only_its_own_override_even_with_the_tenant_hatch", - "milliseconds": 74, - "source": "local-ordinary-scaled" + "milliseconds": 104, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantSettingsAccessorTests.Override_is_a_whole_value_and_invalid_selected_data_is_not_tenant_fallback", - "milliseconds": 31, - "source": "local-ordinary-scaled" + "milliseconds": 53, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantSettingsAccessorTests.Reads_are_uncached_observe_saved_changes_and_exclude_soft_deleted_rows", - "milliseconds": 38, - "source": "local-ordinary-scaled" + "milliseconds": 61, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantSettingsAccessorTests.Registered_reads_keep_tenant_data_separate", - "milliseconds": 50, - "source": "local-ordinary-scaled" + "milliseconds": 80, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TenantSettingsAccessorTests.Shape_exceptions_refuse_the_selected_override_without_tenant_fallback", - "milliseconds": 107, - "source": "local-ordinary-scaled" + "milliseconds": 88, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TrustedVisitorHttpTests.Bad_authenticated_metadata_spends_fallback_quota_and_never_reaches_lookup", - "milliseconds": 1765, - "source": "local-ordinary-scaled" + "milliseconds": 1025, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TrustedVisitorHttpTests.Direct_and_hop_calls_share_one_canonical_IP_budget_across_hosts_and_header_spellings", - "milliseconds": 786, - "source": "local-ordinary-scaled" + "milliseconds": 817, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TrustedVisitorHttpTests.Known_visitor_refusals_preserve_all_remaining_peer_permits_before_lookup", - "milliseconds": 810, - "source": "local-ordinary-scaled" + "milliseconds": 1732, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TrustedVisitorHttpTests.One_visitor_cannot_exhaust_another_or_multiply_quota_by_novel_hosts", - "milliseconds": 411, - "source": "local-ordinary-scaled" + "milliseconds": 243, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", @@ -7902,26 +9631,26 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TrustedVisitorHttpTests.Repeated_raw_secret_headers_spend_the_exhausted_direct_fallback_budget", - "milliseconds": 497, - "source": "local-ordinary-scaled" + "milliseconds": 145, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TrustedVisitorHttpTests.Repeated_raw_visitor_headers_are_refused_before_lookup", - "milliseconds": 385, - "source": "local-ordinary-scaled" + "milliseconds": 119, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TrustedVisitorHttpTests.Trusted_hop_Problem_Details_preserves_the_incoming_W3C_trace_identifier", - "milliseconds": 273, - "source": "local-ordinary-scaled" + "milliseconds": 104, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.TrustedVisitorHttpTests.Trusted_socket_requests_keep_API_host_resolution_and_real_application_role_reads", - "milliseconds": 264, - "source": "local-ordinary-scaled" + "milliseconds": 124, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", @@ -7932,302 +9661,302 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkCommitCleanupTests.Acknowledged_commit_precedes_a_disposal_fault_and_remains_durable", - "milliseconds": 778, - "source": "local-ordinary-scaled" + "milliseconds": 789, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkCommitCleanupTests.Hanging_cleanup_remains_owned_after_acknowledged_commit", - "milliseconds": 771, - "source": "local-ordinary-scaled" + "milliseconds": 961, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkCommitCleanupTests.Reuse_cleans_the_previous_commit_and_a_stale_frame_cannot_clean_the_next_one", - "milliseconds": 790, - "source": "local-ordinary-scaled" + "milliseconds": 1223, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkCommitCleanupTests.Unknown_commit_preserves_its_primary_exception_when_disposal_also_fails", - "milliseconds": 757, - "source": "local-ordinary-scaled" + "milliseconds": 1178, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.A_committed_unit_survives_the_scope", - "milliseconds": 22, - "source": "local-ordinary-scaled" + "milliseconds": 40, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.A_context_follows_the_accessor_after_it_was_built", - "milliseconds": 21, - "source": "local-ordinary-scaled" + "milliseconds": 35, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.A_context_resolved_outside_the_transaction_fails_loudly", - "milliseconds": 3, - "source": "local-ordinary-scaled" + "milliseconds": 4, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.A_failed_announcement_never_retains_producer_authority", - "milliseconds": 69, - "source": "local-ordinary-scaled" + "milliseconds": 90, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.A_frame_left_over_from_a_committed_unit_does_not_touch_the_next_one", - "milliseconds": 46, - "source": "local-ordinary-scaled" + "milliseconds": 64, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.A_leaked_inner_frame_makes_the_outer_completion_throw", - "milliseconds": 19, - "source": "local-ordinary-scaled" + "milliseconds": 28, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.A_module_context_enlists_in_the_ambient_transaction", - "milliseconds": 34, - "source": "local-ordinary-scaled" + "milliseconds": 36, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.A_nested_failure_makes_the_outer_commit_impossible", - "milliseconds": 23, - "source": "local-ordinary-scaled" + "milliseconds": 25, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.A_nested_frame_joins_and_its_commit_is_not_a_commit", - "milliseconds": 19, - "source": "local-ordinary-scaled" + "milliseconds": 27, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.A_reset_tenant_context_reads_nothing_rather_than_everything", - "milliseconds": 21, - "source": "local-ordinary-scaled" + "milliseconds": 33, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.A_resolved_context_becomes_the_session_variables", - "milliseconds": 20, - "source": "local-ordinary-scaled" + "milliseconds": 19, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.A_resolved_context_holding_an_all_zero_tenant_id_still_writes_the_empty_string", - "milliseconds": 27, - "source": "local-ordinary-scaled" + "milliseconds": 38, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.A_resolved_context_holding_an_uninitialized_id_still_writes_the_empty_string", - "milliseconds": 22, - "source": "local-ordinary-scaled" + "milliseconds": 38, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.A_terminal_boundary_discards_the_announcement_snapshot", - "milliseconds": 68, - "source": "local-ordinary-scaled" + "milliseconds": 107, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.An_abandoned_transaction_after_a_committed_one_is_just_rolled_back", - "milliseconds": 31, - "source": "local-ordinary-scaled" + "milliseconds": 40, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.An_absorbed_inner_failure_still_commits_the_outer_work", - "milliseconds": 31, - "source": "local-ordinary-scaled" + "milliseconds": 46, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.An_announcement_without_a_usable_tenant_supplies_no_producer_snapshot", - "milliseconds": 72, - "source": "local-ordinary-scaled" + "milliseconds": 109, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.An_unresolved_context_leaves_every_tenant_owned_table_empty", - "milliseconds": 34, - "source": "local-ordinary-scaled" + "milliseconds": 59, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.Disposing_a_frame_out_of_order_collapses_the_whole_unit", - "milliseconds": 20, - "source": "local-ordinary-scaled" + "milliseconds": 33, + "source": "p031-hosted-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.Disposing_with_a_live_transaction_rolls_it_back", - "milliseconds": 22, - "source": "local-ordinary-scaled" + "milliseconds": 28, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.Failed_transaction_setup_cannot_reuse_a_committed_announcement", - "milliseconds": 41, - "source": "local-ordinary-scaled" + "milliseconds": 69, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.MarkRollbackOnly_outlives_the_transaction_it_marked", - "milliseconds": 16, - "source": "local-ordinary-scaled" + "milliseconds": 3, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.Only_the_announced_transaction_can_read_the_owners_snapshot", - "milliseconds": 24, - "source": "local-ordinary-scaled" + "milliseconds": 34, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.Reusing_a_transaction_object_requires_a_new_announcement_and_generation", - "milliseconds": 28, - "source": "local-ordinary-scaled" + "milliseconds": 34, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.The_announcement_snapshot_records_the_scope_sent_to_Postgres", - "milliseconds": 23, - "source": "local-ordinary-scaled" + "milliseconds": 31, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.The_announcement_snapshot_uses_the_normalized_organization", - "milliseconds": 53, - "source": "local-ordinary-scaled" + "milliseconds": 47, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.The_data_source_refuses_a_runtime_role_that_can_reach_one", - "milliseconds": 272, - "source": "local-ordinary-scaled" + "milliseconds": 93, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.The_data_source_refuses_a_runtime_role_that_was_granted_bypass", - "milliseconds": 341, - "source": "local-ordinary-scaled" + "milliseconds": 176, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.The_ordinary_setter_refuses_the_platform_sentinel", - "milliseconds": 18, - "source": "local-ordinary-scaled" + "milliseconds": 22, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.The_organization_filter_admits_tenant_wide_rows_and_the_caller_own", - "milliseconds": 28, - "source": "local-ordinary-scaled" + "milliseconds": 37, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.The_provisioning_setter_announces_a_real_tenant", - "milliseconds": 20, - "source": "local-ordinary-scaled" + "milliseconds": 16, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.The_provisioning_setter_refuses_the_platform_sentinel", - "milliseconds": 20, - "source": "local-ordinary-scaled" + "milliseconds": 30, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.The_provisioning_snapshot_uses_the_new_tenant_without_resolving_the_context", - "milliseconds": 22, - "source": "local-ordinary-scaled" + "milliseconds": 29, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.The_runtime_role_does_not_bypass_row_security", - "milliseconds": 4, - "source": "local-ordinary-scaled" + "milliseconds": 10, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.The_session_variables_do_not_survive_the_transaction_that_set_them", - "milliseconds": 24, - "source": "local-ordinary-scaled" + "milliseconds": 33, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.The_uninitialized_id_fixture_really_is_uninitialized", "milliseconds": 1, - "source": "local-ordinary-scaled" + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.UnitOfWorkTests.Two_contexts_under_two_tenants_each_see_only_their_own_rows", - "milliseconds": 42, - "source": "local-ordinary-scaled" + "milliseconds": 59, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.WriteStoreConflictTests.A_stale_concurrency_token_becomes_the_port_s_concurrency_type", - "milliseconds": 49, - "source": "local-ordinary-scaled" + "milliseconds": 47, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.Database.WriteStoreConflictTests.A_uniqueness_violation_still_becomes_the_port_s_conflict_type", - "milliseconds": 29, - "source": "local-ordinary-scaled" + "milliseconds": 27, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantBffSessionTests.Early_parent_disposal_joins_and_removes_its_private_native_tree", - "milliseconds": 7368, - "source": "local-bff-lifecycle-r2-20261024" + "milliseconds": 10360, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantBffSessionTests.Enabled_native_startup_and_shutdown_make_no_provider_or_API_connection", - "milliseconds": 6595, - "source": "local-bff-lifecycle-r2-20261024" + "milliseconds": 16860, + "source": "p031-hosted-ordinary-3" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantBffSessionTests.Native_https_browser_stores_host_cookies_and_revalidates_logout_history_with_a_live_counter_control", - "milliseconds": 32915, - "source": "local-bff-lifecycle-r2-20261024" + "milliseconds": 51066, + "source": "pr38-a-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantBffSessionTests.Nonzero_native_shutdown_is_rejected_instead_of_publishing_success", - "milliseconds": 6539, - "source": "local-bff-lifecycle-r2-20261024" + "milliseconds": 12115, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantBffSessionTests.Parent_EOF_during_held_build_joins_acquisition_and_removes_its_private_tree", - "milliseconds": 972, - "source": "local-bff-lifecycle-r2-20261024" + "milliseconds": 2604, + "source": "p031-hosted-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantBffSessionTests.Reconciled_warm_realm_serves_both_native_hosts_with_real_refresh_logout_and_persisted_events", - "milliseconds": 79261, - "source": "local-bff-lifecycle-r2-20261024" + "milliseconds": 134938, + "source": "pr38-a-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmApiTests.A_genuine_Hub_issuer_token_is_rejected_without_changing_the_operator_or_Hub_client", - "milliseconds": 3665, - "source": "p02b6-local-api" + "milliseconds": 976, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", @@ -8235,29 +9964,35 @@ "milliseconds": 7662, "source": "p02b6-local-api" }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmApiTests.A_known_real_provider_subject_without_actor_evidence_uses_the_stored_application_actor", + "milliseconds": 1083, + "source": "p031-hosted-ordinary-2" + }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmApiTests.A_real_claimless_actor_retains_HostOnly_attribution_without_protected_read_authority", - "milliseconds": 2945, - "source": "p02b6-local-api" + "milliseconds": 827, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmApiTests.A_real_provider_organization_disagreement_refuses_and_records_the_trusted_host_organization", - "milliseconds": 3045, - "source": "p02b6-local-api" + "milliseconds": 1783, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmApiTests.Anonymous_public_reads_and_masked_account_refusals_do_not_contact_an_unavailable_identity_endpoint", - "milliseconds": 3048, - "source": "p02b6-local-api" + "milliseconds": 7515, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmApiTests.Every_seed_persona_reads_its_actual_account_site_under_the_matching_host_scope", - "milliseconds": 6681, - "source": "p02b6-local-api" + "milliseconds": 2055, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", @@ -8268,14 +10003,26 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmApiTests.Real_cross_tenant_tokens_refuse_before_configuration_and_audit_the_defended_host", - "milliseconds": 2684, - "source": "p02b6-local-api" + "milliseconds": 1590, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmApiTests.The_real_backchannel_accepts_only_the_owned_CA_and_preserves_all_transport_bounds", - "milliseconds": 2615, - "source": "p02b6-local-api" + "milliseconds": 1090, + "source": "p031-hosted-ordinary-8" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmEventTests.Fresh_provider_stores_real_login_code_refresh_and_refresh_error_events", + "milliseconds": 1971, + "source": "p031-hosted-ordinary-1" + }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmEventTests.Warm_empty_default_policy_converges_preserves_custom_selection_and_refuses_existing_indefinite_history", + "milliseconds": 59045, + "source": "pr38-df-2-ordinary-5" }, { "assembly": "learnstack.tests.integration", @@ -8292,104 +10039,104 @@ { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmIssuanceTests.Actual_signed_tokens_detect_live_mapper_scope_audience_scalar_and_lifespan_mutants", - "milliseconds": 42829, - "source": "p02b6-local-profile" + "milliseconds": 65493, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmIssuanceTests.Authorization_refuses_a_missing_or_plain_challenge", - "milliseconds": 59, - "source": "p02b6-local-profile" + "milliseconds": 354, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmIssuanceTests.Authorization_refuses_an_unregistered_callback", - "milliseconds": 592, - "source": "p02b6-local-profile" + "milliseconds": 852, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmIssuanceTests.Code_exchange_refuses_a_missing_or_wrong_client_secret", - "milliseconds": 244, - "source": "p02b6-local-profile" + "milliseconds": 1400, + "source": "p031-hosted-ordinary-6" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmIssuanceTests.Code_exchange_refuses_a_missing_or_wrong_verifier", - "milliseconds": 610, - "source": "p02b6-local-profile" + "milliseconds": 2206, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmIssuanceTests.Fixture_HTTPS_requires_its_owned_certificate_authority", - "milliseconds": 563, - "source": "p02b6-local-profile" + "milliseconds": 1115, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmIssuanceTests.Fresh_import_issues_the_API_profile_for_all_four_declared_identities", - "milliseconds": 1203, - "source": "p02b6-local-profile" + "milliseconds": 2659, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmIssuanceTests.Late_session_refresh_is_clamped_while_the_configured_access_lifespan_remains_exactly_900", - "milliseconds": 43202, - "source": "p02b6-local-profile" + "milliseconds": 54308, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmIssuanceTests.Live_import_has_exact_lifespan_callbacks_and_confidential_PKCE_configuration", - "milliseconds": 178, - "source": "p02b6-local-profile" + "milliseconds": 1048, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmIssuanceTests.Tenant_password_grant_stays_disabled", - "milliseconds": 17, - "source": "p02b6-local-profile" + "milliseconds": 36, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmProfileProtectionTests.Ordinary_registration_works_and_injected_authority_never_becomes_new_account_data", - "milliseconds": 2161, - "source": "p02b6-local-profile" + "milliseconds": 7153, + "source": "p031-hosted-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmProfileProtectionTests.Same_seed_account_can_edit_ordinary_profile_but_cannot_see_write_or_delete_authority", - "milliseconds": 1789, - "source": "p02b6-local-profile" + "milliseconds": 3831, + "source": "p031-hosted-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmProfileProtectionTests.User_editable_profile_counterfactual_breaks_the_same_protection_predicate", - "milliseconds": 2261, - "source": "p02b6-local-profile" + "milliseconds": 5890, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmReconciliationTests.Committed_fresh_import_is_already_converged_and_repeated_runs_have_zero_writes", - "milliseconds": 12843, - "source": "p02b6-local-account" + "milliseconds": 10077, + "source": "p031-hosted-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmReconciliationTests.Group_carried_identity_requires_a_no_write_refusal", - "milliseconds": 222936, - "source": "p02b6-local-account" + "milliseconds": 103719, + "source": "pr38-df-2-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmReconciliationTests.Hidden_historical_actor_conflict_is_revealed_after_preparation_without_any_ordinary_write", - "milliseconds": 47653, - "source": "adr68-local-preparation" + "milliseconds": 59650, + "source": "p031-hosted-ordinary-9" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmReconciliationTests.Hidden_stored_identity_refuses_before_ordinary_writes_and_preserves_the_conflicting_actor", - "milliseconds": 102474, - "source": "adr68-local-preparation" + "milliseconds": 88801, + "source": "pr38-df-2-ordinary-9" }, { "assembly": "learnstack.tests.integration", @@ -8397,107 +10144,113 @@ "milliseconds": 55935, "source": "adr68-local-mapper-correction" }, + { + "assembly": "learnstack.tests.integration", + "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmReconciliationTests.Historical_stock_upgrade_prepares_once_and_counts_the_named_event_policy_write", + "milliseconds": 93442, + "source": "pr38-b-ordinary-5" + }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmReconciliationTests.Identity_mapper_secret_and_duplicate_lookup_conflicts_refuse_before_the_first_write", - "milliseconds": 95073, - "source": "p02b6-local-account" + "milliseconds": 110473, + "source": "pr38-df-2-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmReconciliationTests.Interrupted_historical_preparation_counts_the_dispatched_write_and_requires_an_explicit_resume", - "milliseconds": 111989, - "source": "adr68-local-preparation" + "milliseconds": 123103, + "source": "pr38-df-1-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmReconciliationTests.Legacy_upgrade_resumes_durable_partial_writes_and_preserves_accounts_and_unrelated_state", - "milliseconds": 250858, - "source": "p02b6-local-account" + "milliseconds": 68827, + "source": "pr38-a-ordinary-0" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmReconciliationTests.Missing_protected_definitions_do_not_allow_preparation_before_an_independent_secret_conflict", - "milliseconds": 49365, - "source": "adr68-local-preparation" + "milliseconds": 49327, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmReconciliationTests.Missing_protected_definitions_do_not_allow_preparation_for_a_customized_stock_scope_lookalike", - "milliseconds": 46986, - "source": "adr68-local-preparation" + "milliseconds": 63258, + "source": "pr38-df-1-ordinary-10" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmReconciliationTests.Partial_admin_view_only_definition_is_preserved_by_preparation_then_normalized_by_a_distinct_ordinary_write", - "milliseconds": 55312, - "source": "adr68-local-mapper-correction" + "milliseconds": 75591, + "source": "pr38-df-2-ordinary-5" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmReconciliationTests.Projected_identity_profile_configuration_refuses_before_any_pending_write", - "milliseconds": 93561, - "source": "adr68-local-preparation" + "milliseconds": 83193, + "source": "pr38-b-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmReconciliationTests.Readback_failure_is_nonzero_and_a_new_explicit_pass_verifies_the_committed_result", - "milliseconds": 64288, - "source": "p02b6-local-account" + "milliseconds": 57775, + "source": "p031-hosted-ordinary-4" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmReconciliationTests.Retained_cached_organization_groups_do_not_override_strict_user_identity", - "milliseconds": 54861, - "source": "p02b6-local-account" + "milliseconds": 67245, + "source": "pr38-df-1-ordinary-8" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmReconciliationTests.Uninterrupted_legacy_upgrade_preserves_nonmanifest_actor_and_account_state", - "milliseconds": 58888, - "source": "p02b6-local-account" + "milliseconds": 57569, + "source": "pr38-a-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmReconciliationTests.Unrelated_nested_groups_converge_and_preserve_membership_and_strict_token_identity", - "milliseconds": 50216, - "source": "p02b6-local-account" + "milliseconds": 67568, + "source": "p031-hosted-ordinary-2" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmSelfServiceTests.Effective_inherited_capability_and_a_compatible_existing_mapper_need_no_redundant_additions", - "milliseconds": 123811, - "source": "p02b6-local-account" + "milliseconds": 111616, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmSelfServiceTests.Explicit_fresh_builtins_preserve_stock_bootstrap_and_add_only_the_approved_mapper_and_four_grants", - "milliseconds": 45264, - "source": "p02b6-local-account" + "milliseconds": 57761, + "source": "p031-hosted-ordinary-7" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmSelfServiceTests.Shared_mapper_restores_an_already_eligible_nonmanifest_account_without_changing_its_data_or_grants", - "milliseconds": 49972, - "source": "p02b6-local-account" + "milliseconds": 58242, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmSelfServiceTests.Unsafe_account_customization_refuses_before_any_pending_write_and_preserves_the_customization", - "milliseconds": 246337, - "source": "adr68-local-mapper-correction" + "milliseconds": 283875, + "source": "p031-hosted-ordinary-1" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmStockBaselineTests.Historical_24705a7a_bootstrap_matches_the_fixed_26_6_2_scope_role_and_mapper_baseline", - "milliseconds": 98022, - "source": "adr68-hosted-baseline-ordinary-1" + "milliseconds": 84034, + "source": "pr38-a-ordinary-11" }, { "assembly": "learnstack.tests.integration", "method": "LearnStack.Tests.Integration.TenancyIdentity.TenantRealmStockBaselineTests.Historical_stock_ordinary_reconciliation_detaches_only_three_console_edges_and_then_writes_zero", - "milliseconds": 102868, - "source": "adr68-hosted-baseline-ordinary-4" + "milliseconds": 146023, + "source": "pr38-b-ordinary-5" } ], "sharedFixtureClasses": [ @@ -8556,10 +10309,21 @@ "LearnStack.Tests.Integration.Database.EntitlementExpiryReversalTests", "LearnStack.Tests.Integration.Database.EventDeliveryMigrationTests", "LearnStack.Tests.Integration.Database.FeatureFlagsTests", + "LearnStack.Tests.Integration.Database.GlobalIdentityAuthorityToolTests", + "LearnStack.Tests.Integration.Database.GlobalIdentityBootstrapTests", + "LearnStack.Tests.Integration.Database.GlobalIdentitySchemaTests", + "LearnStack.Tests.Integration.Database.GlobalIdentityUnitOfWorkTests", "LearnStack.Tests.Integration.Database.HangfireGenerationTests", "LearnStack.Tests.Integration.Database.HangfirePoolOwnerTests", "LearnStack.Tests.Integration.Database.HangfireStorageTests", "LearnStack.Tests.Integration.Database.HostResolutionTests", + "LearnStack.Tests.Integration.Database.IdentityCommandQualificationTests", + "LearnStack.Tests.Integration.Database.IdentityDiagnosticSinkTests", + "LearnStack.Tests.Integration.Database.IdentityMembershipTests", + "LearnStack.Tests.Integration.Database.IdentityMutationLockTests", + "LearnStack.Tests.Integration.Database.IdentityReadDiagnosticSinkTests", + "LearnStack.Tests.Integration.Database.IdentityScopeLifecycleTests", + "LearnStack.Tests.Integration.Database.IdentitySeederTests", "LearnStack.Tests.Integration.Database.InboxGuardTests", "LearnStack.Tests.Integration.Database.KillswitchOverlayTests", "LearnStack.Tests.Integration.Database.MigrationRollbackTests", @@ -8592,6 +10356,7 @@ "LearnStack.Tests.Integration.Database.TenantAuthenticationRejectionAuditTests", "LearnStack.Tests.Integration.Database.TenantContextGuardTests", "LearnStack.Tests.Integration.Database.TenantCreatedProducerTests", + "LearnStack.Tests.Integration.Database.TenantExistingBindingAdmissionTests", "LearnStack.Tests.Integration.Database.TenantIsolationHttpTests", "LearnStack.Tests.Integration.Database.TenantLocaleDefaultTests", "LearnStack.Tests.Integration.Database.TenantLocaleEnabledMigrationTests", diff --git a/scripts/ci-test-shards.py b/scripts/ci-test-shards.py index 835dcaad0..2722d0693 100644 --- a/scripts/ci-test-shards.py +++ b/scripts/ci-test-shards.py @@ -400,7 +400,9 @@ def owners(value): def main(): - if len(sys.argv) != 2 or sys.argv[1] not in ('topology', 'prepare-fixtures', 'aggregate-backend', 'aggregate-integration'): + action = sys.argv[1] if len(sys.argv) > 1 else None + if (action not in ('topology', 'prepare-fixtures', 'aggregate-backend', 'aggregate-integration') + or len(sys.argv) != (3 if action == 'prepare-fixtures' else 2)): print('{"protocol":1,"error":"mode_refused"}') return 1 result = None @@ -413,7 +415,7 @@ def main(): print('{"protocol":1,"topology":"complete"}') return 0 if sys.argv[1] == 'prepare-fixtures': - return result.prepare_fixture_images() + return result.prepare_fixture_images(sys.argv[2]) return result.aggregate(sys.argv[1].removeprefix('aggregate-')) except Exception as failure: # Known owners expose only closed refusals. An unexpected import/parser diff --git a/scripts/connection-string.awk b/scripts/connection-string.awk index 810db1ba6..f618ee488 100644 --- a/scripts/connection-string.awk +++ b/scripts/connection-string.awk @@ -122,13 +122,17 @@ END { count = split_fields(input, fields) if (field == "user") { + matches = 0 for (i = 1; i <= count; i++) { if (normalize_key(fields[i]) in user) { - print unquote(fields[i]) "\n" - exit + matches++ + value = unquote(fields[i]) } } - + # Npgsql may resolve a later alias differently from a first-match check. + # Refuse the ambiguity without printing any part of the credential. + if (matches > 1) exit 2 + if (matches == 1) print value "\n" exit } diff --git a/scripts/demo-process.d.mts b/scripts/demo-process.d.mts index 374620d5d..86839276c 100644 --- a/scripts/demo-process.d.mts +++ b/scripts/demo-process.d.mts @@ -1,4 +1,4 @@ -import type { ChildProcess } from 'node:child_process'; +import type { ChildProcess } from "node:child_process"; export function installDemoCancellation(cancel: () => void): () => void; export class DemoCommandError extends Error { constructor( @@ -6,12 +6,26 @@ export class DemoCommandError extends Error { cause?: unknown, status?: { code: number | null; signal: string | null }, outcome?: { - reason?: 'exit' | 'deadline' | 'cancelled' | 'spawn' | 'output' | 'cleanup' | 'unknown'; - origin?: 'command' | 'daemon'; + reason?: + | "exit" + | "deadline" + | "cancelled" + | "spawn" + | "output" + | "cleanup" + | "unknown"; + origin?: "command" | "daemon"; }, ); - readonly reason: 'exit' | 'deadline' | 'cancelled' | 'spawn' | 'output' | 'cleanup' | 'unknown'; - readonly origin: 'command' | 'daemon'; + readonly reason: + | "exit" + | "deadline" + | "cancelled" + | "spawn" + | "output" + | "cleanup" + | "unknown"; + readonly origin: "command" | "daemon"; readonly exitCode: number | null; readonly signalCode: string | null; } @@ -21,7 +35,7 @@ interface Options { label?: string; capture?: boolean; timeout?: number; - observe?: (chunk: Buffer, stream: 'stdout' | 'stderr') => void; + observe?: (chunk: Buffer, stream: "stdout" | "stderr") => void; } interface Running { child: ChildProcess; @@ -29,8 +43,12 @@ interface Running { exit: Promise<{ code: number | null; signal: string | null }>; /** Every daemon leader exit is unexpected, independently of stream closure. */ nativeExit: Promise<{ code: number | null; signal: string | null }>; - refusal: Promise<{ cause: unknown; reason: 'spawn' | 'output' }>; - result(): { output: string; failed?: Error; failureReason?: 'spawn' | 'output' }; + refusal: Promise<{ cause: unknown; reason: "spawn" | "output" }>; + result(): { + output: string; + failed?: Error; + failureReason?: "spawn" | "output"; + }; } export class DemoProcesses { constructor(signal: AbortSignal); @@ -39,5 +57,12 @@ export class DemoProcesses { start(command: string, args: string[], options?: Options): Running; daemon(command: string, args: string[], options: Options): Running; run(command: string, args: string[], options?: Options): Promise; + /** Bounded private stdin; the owned child is joined before this call completes. */ + runPrivateInput( + command: string, + args: string[], + privateInput: string, + options?: Options, + ): Promise; dispose(): Promise; } diff --git a/scripts/demo-process.mjs b/scripts/demo-process.mjs index 9e054d538..429515f7b 100644 --- a/scripts/demo-process.mjs +++ b/scripts/demo-process.mjs @@ -67,6 +67,9 @@ export class DemoProcesses { if (this.#failed) throw this.#failed; } start(command, args, { cwd, env, label, observe = () => {}, capture = false } = {}) { + return this.#start(command, args, { cwd, env, label, observe, capture }); + } + #start(command, args, { cwd, env, label, observe = () => {}, capture = false } = {}, privateInput) { this.assertActive(); let child; try { @@ -74,7 +77,7 @@ export class DemoProcesses { cwd, env, detached: process.platform !== 'win32', - stdio: ['ignore', 'pipe', 'pipe'], + stdio: [privateInput === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'], }); } catch (cause) { throw new DemoCommandError(label ?? command, cause, undefined, { reason: 'spawn' }); @@ -95,6 +98,12 @@ export class DemoProcesses { // dispose still owns a failed stop; do not create an unhandled rejection. void stopTestChild(child).catch(() => {}); }; + if (privateInput !== undefined) { + // One bounded write and EOF. Never inherit a terminal or retain the value + // in the child handle/result; an early pipe refusal fails the owned act. + child.stdin.once('error', refuseOutput); + child.stdin.end(privateInput); + } for (const stream of [child.stdout, child.stderr]) { stream.once('error', refuseOutput); stream.on('data', (chunk) => { @@ -170,7 +179,16 @@ export class DemoProcesses { return running; } async run(command, args, options = {}) { - const running = this.start(command, args, options); + return this.#run(this.start(command, args, options), command, options); + } + /** Private one-shot handoff; bounded before spawn and never part of argv/results. */ + async runPrivateInput(command, args, privateInput, options = {}) { + if (typeof privateInput !== 'string' || Buffer.byteLength(privateInput) > 8192 + || privateInput.includes('\0')) + throw new DemoCommandError(options.label ?? command, undefined, undefined, { reason: 'output' }); + return this.#run(this.#start(command, args, options, privateInput), command, options); + } + async #run(running, command, options) { const timeout = AbortSignal.timeout(options.timeout ?? 180000); const signal = AbortSignal.any([this.#signal, timeout]); let cancelled; diff --git a/scripts/demo.mjs b/scripts/demo.mjs index 3cf1e187d..03af7da77 100644 --- a/scripts/demo.mjs +++ b/scripts/demo.mjs @@ -23,7 +23,7 @@ import { apiCompletionObserver } from './demo-observation.mjs'; import { publicSeederEnvironment, validateDemoDatabaseConfiguration } from './demo-database.mjs'; import { demoSource } from './demo-source.mjs'; import { RealmError, realmFailureNotice } from './development-realm-errors.mjs'; -import { readRealmEnvironmentFile, realmEnvironment, validateLocalDockerContext } from './development-realm-owner.mjs'; +import { readRealmEnvironmentFile, realmEnvironment, seedAuthorityEnvironment, validateLocalDockerContext } from './development-realm-owner.mjs'; import { reconcileDevelopmentRealm } from './reconcile-development-realm.mjs'; const appRoot = join(repositoryRoot, 'frontend/apps/web'); @@ -354,6 +354,7 @@ export async function startDemo(mode) { } const privateSource = await readRealmEnvironmentFile(rootEnv); realmEnvironment(privateSource); + const identityEnvironment = seedAuthorityEnvironment(privateSource); const rawValues = parseLocalEnvironment(privateSource); for (const [key, value] of Object.entries(rawValues)) if (process.env[key] !== undefined && process.env[key] !== value) @@ -434,6 +435,7 @@ export async function startDemo(mode) { LEARNSTACK_COMPOSE_ENV_FILE: selected.file, LEARNSTACK_COMPOSE_MODE: selected.mode, ConnectionStrings__Migration: rawValues.ConnectionStrings__Migration, + ...identityEnvironment, }, timeout: 300000, }); @@ -443,7 +445,7 @@ export async function startDemo(mode) { env: publicSeederEnvironment(rawValues.ConnectionStrings__Default), timeout: 180000, }); - await reconcileDevelopmentRealm({ selected, signal: controller.signal }); + await reconcileDevelopmentRealm({ selected, signal: controller.signal, seedIdentityFoundation: true }); if (mode === 'ci') { await compose(['stop', 'keycloak'], { timeout: 20000 }); const rows = await compose(['ps', '--status', 'running', '--format', '{{.Service}}'], { diff --git a/scripts/development-realm-core.mjs b/scripts/development-realm-core.mjs index 7b41b0481..c36868192 100644 --- a/scripts/development-realm-core.mjs +++ b/scripts/development-realm-core.mjs @@ -7,7 +7,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, manifest, desired, signal, ca, transport = realmRequest }) { + webSecret, manifest, desired, signal, ca, transport = realmRequest, afterVerified }) { let base; try { base = new URL(baseUrl); } catch { refuse('preflight', 'configuration'); } @@ -123,6 +123,13 @@ export async function reconcileRealm({ baseUrl, expectedIssuer, adminUsername, a await plan.verify(); const remaining = await buildRealmPlan({ admin, desired, manifest, webSecret }); if (remaining.actions.length !== 0) refuse(stage, 'readback_conflict'); + if (afterVerified) { + stage = 'identity'; + if (active.aborted) refuse(stage, signal?.aborted ? 'cancelled' : 'deadline'); + await afterVerified(Object.freeze({ version: 1, issuer: expectedIssuer, + users: remaining.providerSubjects() })); + if (active.aborted) refuse(stage, signal?.aborted ? 'cancelled' : 'deadline'); + } return Object.freeze({ mutations, ...(preparationDispatched ? { preparationDispatched: true } : {}) }); } catch (error) { if (error instanceof RealmError) { @@ -130,7 +137,7 @@ export async function reconcileRealm({ baseUrl, expectedIssuer, adminUsername, a throw new RealmError(error.stage, error.reason, true); throw error; } - throw new RealmError(stage, 'response', preparationDispatched); + throw new RealmError(stage, stage === 'identity' ? 'seed_refused' : 'response', preparationDispatched); } } diff --git a/scripts/development-realm-core.test.mjs b/scripts/development-realm-core.test.mjs index 77f31a7f7..8eadd2c4c 100644 --- a/scripts/development-realm-core.test.mjs +++ b/scripts/development-realm-core.test.mjs @@ -64,6 +64,52 @@ const memoryInput = transport => ({ baseUrl: 'http://localhost:8080/', adminPassword: privateCanary, webSecret: secret, desired: structuredClone(desired), manifest: structuredClone(manifest), transport }); +test('the private handoff receives exact Admin subjects only after final authenticated readback', async () => { + const state = provider(); + const recording = providerTransport(state); + let handed; + const result = await reconcileRealm({ ...memoryInput(recording.transport), afterVerified: witness => { + assert.ok(recording.requests.filter(request => request.path === '/admin/realms/learnstack/' && !request.method).length >= 3); + assert.equal(witness.issuer, 'http://localhost:8080/realms/learnstack'); + assert.equal(witness.version, 1); + assert.equal(witness.users.length, 4); + assert.deepEqual(witness.users.map(user => user.actorId), manifest.users.map(user => user.userId)); + for (let index = 0; index < 4; index++) { + const actual = state.state.users.find(user => user.username === manifest.users[index].username); + assert.equal(witness.users[index].opaqueSub, actual.id); + } + assert.equal(Object.isFrozen(witness), true); + assert.equal(Object.isFrozen(witness.users), true); + handed = witness; + } }); + assert.ok(handed); + assert.deepEqual(result, { mutations: 0 }); + assert.ok(!JSON.stringify(result).includes('opaqueSub')); +}); + +test('an unsuccessful final readback never dispatches the private identity consumer', async () => { + const state = provider(); + const recording = providerTransport(state); + let reads = 0, dispatched = false; + const transport = async (url, options) => { + const result = await recording.transport(url, options); + if (url.pathname === '/admin/realms/learnstack/' && !options.method && ++reads === 3) + return { ...result, bytes: Buffer.from(JSON.stringify({ ...JSON.parse(result.bytes), accessTokenLifespan: 1800 })) }; + return result; + }; + await assert.rejects(reconcileRealm({ ...memoryInput(transport), afterVerified: () => { dispatched = true; } }), + refusal('readback', 'readback_conflict')); + assert.equal(dispatched, false); +}); + +test('a private consumer failure is closed and never exposes provider facts in public results', async () => { + const state = provider(); + const recording = providerTransport(state); + await assert.rejects(reconcileRealm({ ...memoryInput(recording.transport), afterVerified: witness => { + throw new Error(witness.users[0].opaqueSub + privateCanary); + } }), refusal('identity', 'seed_refused')); +}); + test('the actual core applies one mutation, verifies full state, and makes an explicit next pass read only', async () => { const state = provider(); state.state.realm.accessTokenLifespan = 1800; const recording = providerTransport(state); diff --git a/scripts/development-realm-errors.mjs b/scripts/development-realm-errors.mjs index ed549619a..11de7e6ea 100644 --- a/scripts/development-realm-errors.mjs +++ b/scripts/development-realm-errors.mjs @@ -1,12 +1,12 @@ const stages = new Set([ 'preflight', 'discovery', 'authentication', 'version', 'manifest', 'lock', - 'plan', 'prepare', 'apply', 'readback', 'cleanup', + 'plan', 'prepare', 'apply', 'readback', 'identity', 'cleanup', ]); const reasons = new Set([ 'configuration', 'identity_conflict', 'mapper_conflict', 'secret_conflict', 'unsupported', 'response', 'status', 'redirect', 'deadline', 'cancelled', 'transport', 'lock_busy', 'body_limit', 'readback_conflict', 'cleanup', - 'missing_web_secret', 'private_file', 'event_policy_conflict', + 'missing_web_secret', 'private_file', 'event_policy_conflict', 'seed_refused', ]); /** Neither upstream objects nor arbitrary caller text can become a diagnostic. */ diff --git a/scripts/development-realm-owner.mjs b/scripts/development-realm-owner.mjs index 30a3c6e8f..0c7d21175 100644 --- a/scripts/development-realm-owner.mjs +++ b/scripts/development-realm-owner.mjs @@ -47,6 +47,23 @@ export function realmEnvironment(source, ambient = process.env) { return Object.freeze(Object.fromEntries(privateKeys.map((key) => [key, values[key]]))); } +/** Require the selected deployment's explicit immutable pair before migrations. */ +export function seedAuthorityEnvironment(source, ambient = process.env) { + const values = parseEnv(source); + const keys = ['Identity__AuthorityId', 'Authentication__Tenant__Issuer']; + for (const key of keys) { + if ([...source.matchAll(new RegExp(`^${key}=`, 'gm'))].length !== 1 + || [...source.matchAll(new RegExp(`^[ \\t]*(?:export[ \\t]+)?${key}[ \\t]*=`, 'gm'))].length !== 1 + || !values[key] || (ambient[key] !== undefined && ambient[key] !== values[key])) + refuse('preflight', 'configuration'); + } + if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(values.Identity__AuthorityId) + || values.Identity__AuthorityId === '00000000-0000-0000-0000-000000000000' + || values.Authentication__Tenant__Issuer !== 'http://localhost:8080/realms/learnstack') + refuse('preflight', 'configuration'); + return Object.freeze(Object.fromEntries(keys.map(key => [key, values[key]]))); +} + /** One exclusive local owner, never reclaimed from age or a guessed process state. */ export async function acquireRealmLock(identity, directory = join(tmpdir(), `learnstack-realm-${process.getuid()}`)) { if (typeof identity !== 'string' || !identity || Buffer.byteLength(identity) > 4096) diff --git a/scripts/development-realm-owner.test.mjs b/scripts/development-realm-owner.test.mjs index 9d58a5996..587e47ca5 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, readRealmEnvironmentFile, realmEnvironment, validateLocalDockerContext, validateRealmTarget, + acquireRealmLock, readRealmEnvironmentFile, realmEnvironment, seedAuthorityEnvironment, validateLocalDockerContext, validateRealmTarget, } from './development-realm-owner.mjs'; const keys = ['KEYCLOAK_ADMIN', 'KEYCLOAK_ADMIN_PASSWORD', 'KEYCLOAK_WEB_CLIENT_SECRET']; @@ -20,6 +20,29 @@ const values = { KEYCLOAK_WEB_CLIENT_SECRET: 'synthetic-private-web-secret-82b1', }; const source = keys.map((key) => `${key}=${values[key]}`).join('\n'); +const authoritySource = 'Identity__AuthorityId=01930000-0000-7000-8000-000000009001\nAuthentication__Tenant__Issuer=http://localhost:8080/realms/learnstack\n'; + +test('seed authority is an explicit exact selected pair and never a generated fallback', () => { + assert.deepEqual(seedAuthorityEnvironment(authoritySource, {}), { + Identity__AuthorityId: '01930000-0000-7000-8000-000000009001', + Authentication__Tenant__Issuer: 'http://localhost:8080/realms/learnstack', + }); + assert.throws(() => seedAuthorityEnvironment('', {}), refusal()); + assert.throws(() => seedAuthorityEnvironment(authoritySource, { Identity__AuthorityId: values.KEYCLOAK_ADMIN_PASSWORD }), refusal()); +}); + +for (const change of [ + value => value.replace(/^Identity__AuthorityId=.*\n/, ''), + value => value.replace(/Authentication__Tenant__Issuer=.*\n/, ''), + value => value.replace('01930000-0000-7000-8000-000000009001', '00000000-0000-0000-0000-000000000000'), + value => value.replace('localhost', '127.0.0.1'), + value => value + 'Identity__AuthorityId=01930000-0000-7000-8000-000000009001\n', + value => value + 'export Authentication__Tenant__Issuer=http://localhost:8080/realms/learnstack\n', +]) { + test(`seed authority refuses missing, conflicting, alias or duplicate configuration ${change.toString()}`, () => { + assert.throws(() => seedAuthorityEnvironment(change(authoritySource), {}), refusal()); + }); +} function refusal(stage = 'preflight', reason = 'configuration') { return (error) => { diff --git a/scripts/development-realm-plan.mjs b/scripts/development-realm-plan.mjs index dc4d2afe4..a03147352 100644 --- a/scripts/development-realm-plan.mjs +++ b/scripts/development-realm-plan.mjs @@ -696,7 +696,16 @@ async function assemblePlan({ admin, desired, manifest, webSecret, before, event if (preparationOnly) return; - return { actions, verify: async () => { + return { actions, + // This credential-free projection is internal to the lock owner. It comes + // from authenticated Admin reads, not usernames, email or token claims. + providerSubjects: () => Object.freeze(manifest.users.map(declaration => { + const subject = before.candidates.get(declaration.username)?.user.id; + if (typeof subject !== 'string' || !subject.trim() || subject.length > 255) + refuse('readback', 'identity_conflict'); + return Object.freeze({ actorId: declaration.userId, opaqueSub: subject }); + })), + verify: async () => { await events.verify(); const after = await snapshot(admin, desired, manifest, 'readback'); await account.verify(after.candidates); diff --git a/scripts/migrate.mjs b/scripts/migrate.mjs new file mode 100644 index 000000000..4461877fa --- /dev/null +++ b/scripts/migrate.mjs @@ -0,0 +1,118 @@ +import { execFileSync, spawnSync } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import { basename, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { parseEnv } from 'node:util'; +import { composeProcessEnvironment, readComposeEnvironmentFile } from './compose.mjs'; +import { publicSeederEnvironment } from './demo-database.mjs'; +import { RealmError, realmFailureNotice } from './development-realm-errors.mjs'; + +const connectionKey = 'ConnectionStrings__Migration'; +const identityKeys = ['Identity__AuthorityId', 'Authentication__Tenant__Issuer']; +const keys = [connectionKey, ...identityKeys]; +class MigrationConfigurationError extends Error {} +const configurationFailure = () => new MigrationConfigurationError('Migration configuration refused: use one source for ConnectionStrings__Migration and the complete identity authority pair, or omit both identity keys for schema-only migration. No migration was attempted.'); + +function fileConfiguration(path) { + if (!existsSync(path)) return {}; + const source = readComposeEnvironmentFile(path); + if (source.includes('\0')) throw configurationFailure(); + const parsed = parseEnv(source); + for (const key of keys) { + const canonical = [...source.matchAll(new RegExp(`^${key}=`, 'gm'))].length; + const assignments = [...source.matchAll(new RegExp(`^[ \\t]*(?:export[ \\t]+)?${key}[ \\t]*=`, 'gm'))].length; + if (canonical !== assignments || canonical > 1 || (canonical === 1 && !parsed[key])) + throw configurationFailure(); + } + return Object.fromEntries(keys.filter(key => parsed[key] !== undefined).map(key => [key, parsed[key]])); +} + +/** A migration credential and its optional immutable registration are one deployment selection. */ +export function migrationConfiguration(environment = process.env, root = process.cwd()) { + const ambient = Object.fromEntries(keys.filter(key => environment[key] !== undefined + && (key !== connectionKey || environment[key] !== '')) + .map(key => [key, environment[key]])); + let selected; + if (Object.keys(ambient).length !== 0) { + const hasIdentity = identityKeys.some(key => ambient[key] !== undefined); + if (!ambient[connectionKey] || (hasIdentity && !identityKeys.every(key => ambient[key]))) + throw configurationFailure(); + // Complete ambient deployment input needs no file. Schema-only ambient input + // must not silently inherit (or silently discard) a file's authority pair. + if (!hasIdentity) { + const file = fileConfiguration(resolve(root, environment.LEARNSTACK_COMPOSE_ENV_FILE ?? '.env')); + if (identityKeys.some(key => file[key] !== undefined)) throw configurationFailure(); + } + selected = ambient; + } else { + selected = fileConfiguration(resolve(root, environment.LEARNSTACK_COMPOSE_ENV_FILE ?? '.env')); + } + if (!selected[connectionKey] || (identityKeys.some(key => selected[key]) && !identityKeys.every(key => selected[key])) + || keys.some(key => selected[key] !== undefined && (!selected[key].trim() || /[\r\n\0]/.test(selected[key])))) + throw configurationFailure(); + return Object.freeze(selected); +} + +function validateRole(connection, root, environment) { + let role; + try { + role = execFileSync('awk', ['-f', join(root, 'scripts/connection-string.awk'), '-v', 'field=user'], { + input: connection, encoding: 'utf8', env: publicSeederEnvironment(undefined, environment), + stdio: ['pipe', 'pipe', 'pipe'], timeout: 5000, maxBuffer: 2048, + }).trim(); + } catch { throw configurationFailure(); } + if (role !== 'learnstack_migration') { + const named = /^[a-z_][a-z0-9_]*$/.test(role) ? role : ''; + throw new MigrationConfigurationError(`ConnectionStrings__Migration names Username='${named}', not learnstack_migration. Use the Npgsql key/value form; no migration was attempted.`); + } +} + +function run(args, cwd, env, quiet = false) { + const result = spawnSync('dotnet', args, { cwd, env, stdio: ['ignore', quiet ? 'ignore' : 'inherit', 'inherit'] }); + return result.error || result.signal ? 1 : result.status ?? 1; +} + +/** Make owns the ordered project list; each child receives only its own credential. */ +export function migrate(projects, environment = process.env, root = process.cwd()) { + // Preserve the credential-role refusal before reading any unrelated file. + if (environment[connectionKey]) validateRole(environment[connectionKey], root, environment); + const configuration = migrationConfiguration(environment, root); + validateRole(configuration[connectionKey], root, environment); + const prerequisites = { ...publicSeederEnvironment(undefined, environment), ...composeProcessEnvironment(environment) }; + for (const key of ['LEARNSTACK_COMPOSE_PROJECT', 'LEARNSTACK_COMPOSE_ENV_FILE', 'LEARNSTACK_COMPOSE_MODE']) + if (environment[key] !== undefined) prerequisites[key] = environment[key]; + const backend = join(root, 'backend'); + for (const [args, quiet] of [ + [['tool', 'restore'], true], + [['build', 'src/LearnStack.Api', '--configuration', 'Release', '--nologo'], false], + ...(configuration.Identity__AuthorityId + ? [[['build', 'src/LearnStack.Tools.IdentityAuthorityInstaller', '--configuration', 'Release', '--nologo'], false]] : []), + ]) { + const status = run(args, backend, prerequisites, quiet); + if (status !== 0) return status; + } + let failed = 0; + const chains = [...new Set(projects)].filter(project => existsSync(join(root, project, 'Persistence/Migrations'))); + for (const project of chains) { + console.log(`==> ${basename(project)}`); + if (run(['ef', 'database', 'update', '--project', '../' + project, + '--startup-project', 'src/LearnStack.Api', '--configuration', 'Release', '--no-build'], + backend, { ...prerequisites, [connectionKey]: configuration[connectionKey] }) !== 0) failed = 1; + } + if (chains.length === 0) console.log('No project carries Persistence/Migrations yet.'); + if (!failed && configuration.Identity__AuthorityId) + failed = run(['backend/src/LearnStack.Tools.IdentityAuthorityInstaller/bin/Release/net10.0/LearnStack.Tools.IdentityAuthorityInstaller.dll'], + root, { ...publicSeederEnvironment(undefined, environment), ...configuration }); + return failed; +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + try { process.exitCode = migrate(process.argv.slice(2)); } + catch (error) { + // Keep closed setup guidance without exposing private reader/provider details. + const message = error instanceof RealmError ? realmFailureNotice(error) + : error instanceof MigrationConfigurationError ? error.message : configurationFailure().message; + console.error(message); + process.exitCode = 1; + } +} diff --git a/scripts/public-runtime.mjs b/scripts/public-runtime.mjs index 869dbbfc7..3ae4cd22d 100644 --- a/scripts/public-runtime.mjs +++ b/scripts/public-runtime.mjs @@ -9,8 +9,8 @@ export function publicApiEnvironment(values, configuration, base = process.env) if (!values.ConnectionStrings__Default) throw new Error('Application credential is missing'); if (!values.ConnectionStrings__OutboxDispatcher) throw new Error('Outbox dispatcher credential is missing'); - if (values.Authentication__Tenant__Issuer) - environment.Authentication__Tenant__Issuer = values.Authentication__Tenant__Issuer; + for (const key of ['Authentication__Tenant__Issuer', 'Identity__AuthorityId']) + if (values[key]) environment[key] = values[key]; environment.ConnectionStrings__Default = values.ConnectionStrings__Default; environment.ConnectionStrings__OutboxDispatcher = values.ConnectionStrings__OutboxDispatcher; if (values.ConnectionStrings__PlatformAdmin) diff --git a/scripts/reconcile-development-realm.mjs b/scripts/reconcile-development-realm.mjs index 99705042f..89fc260e8 100644 --- a/scripts/reconcile-development-realm.mjs +++ b/scripts/reconcile-development-realm.mjs @@ -1,15 +1,16 @@ import { readFile, realpath } from 'node:fs/promises'; import { resolve, join } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { parseEnv } from 'node:util'; import { composeSelection, repositoryRoot } from './compose.mjs'; import { DemoCommandError, DemoProcesses, installDemoCancellation } from './demo-process.mjs'; import { publicSeederEnvironment } from './demo-database.mjs'; import { reconcileRealm, realmPassMilliseconds } from './development-realm-core.mjs'; -import { acquireRealmLock, isLocalDockerEndpoint, readRealmEnvironmentFile, realmEnvironment, validateRealmTarget } from './development-realm-owner.mjs'; +import { acquireRealmLock, isLocalDockerEndpoint, readRealmEnvironmentFile, realmEnvironment, seedAuthorityEnvironment, validateRealmTarget } from './development-realm-owner.mjs'; import { RealmError, realmFailureNotice, refuse } from './development-realm-errors.mjs'; /** Shared seed/demo operation. Neither target nor secrets are command-line parameters. */ -export async function reconcileDevelopmentRealm({ selected, signal }) { +export async function reconcileDevelopmentRealm({ selected, signal, seedIdentityFoundation = false }) { const deadline = AbortSignal.timeout(realmPassMilliseconds); const active = signal ? AbortSignal.any([signal, deadline]) : deadline; const processes = new DemoProcesses(active); @@ -24,7 +25,9 @@ export async function reconcileDevelopmentRealm({ selected, signal }) { if (!selected || !['dev', 'e2e'].includes(selected.mode) || selected.cwd !== repositoryRoot || (selected.env.DOCKER_HOST && !isLocalDockerEndpoint(selected.env.DOCKER_HOST))) refuse('preflight', 'configuration'); - const values = realmEnvironment(await readRealmEnvironmentFile(selected.file)); + const source = await readRealmEnvironmentFile(selected.file); + const values = realmEnvironment(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'])); const ids = (await run([...selected.args, 'ps', '--quiet', '--no-trunc', 'keycloak'])).trim().split(/\s+/).filter(Boolean); @@ -41,7 +44,23 @@ export async function reconcileDevelopmentRealm({ selected, signal }) { 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, - manifest, desired, signal: active }); + manifest, desired, signal: active, + afterVerified: !seedIdentityFoundation ? undefined : async witness => { + const applicationConnection = parseEnv(source).ConnectionStrings__Default; + if (!applicationConnection || witness.issuer !== identityEnvironment.Authentication__Tenant__Issuer) + refuse('identity', 'configuration'); + try { + await processes.runPrivateInput('dotnet', [join(repositoryRoot, + 'backend/src/LearnStack.Tools.Seeder/bin/Release/net10.0/LearnStack.Tools.Seeder.dll'), '--identity-foundation-stdin'], + JSON.stringify(witness), { cwd: join(repositoryRoot, 'backend'), + env: { ...publicSeederEnvironment(applicationConnection), ...identityEnvironment }, + // The enclosing active signal retains the remaining shared pass budget. + label: 'Verified identity foundation', timeout: realmPassMilliseconds }); + } catch (error) { + refuse('identity', error instanceof DemoCommandError && ['deadline', 'cancelled', 'cleanup'].includes(error.reason) + ? error.reason : 'seed_refused'); + } + } }); preparationDispatched = result.preparationDispatched === true; } catch (error) { preparationDispatched = error instanceof RealmError && error.preparationDispatched === true; diff --git a/scripts/reconcile-development-realm.test.mjs b/scripts/reconcile-development-realm.test.mjs index 5beafd225..1c745685a 100644 --- a/scripts/reconcile-development-realm.test.mjs +++ b/scripts/reconcile-development-realm.test.mjs @@ -9,6 +9,7 @@ import { fileURLToPath } from 'node:url'; import { realmFailure } from './development-realm-errors.mjs'; import { reconcileDevelopmentRealm } from './reconcile-development-realm.mjs'; import { repositoryRoot } from './compose.mjs'; +import { DemoProcesses } from './demo-process.mjs'; const canary = 'synthetic-private-cli-canary-73f2'; const entry = fileURLToPath(new URL('./reconcile-development-realm.mjs', import.meta.url)); @@ -122,7 +123,10 @@ async function ownedEntryFixture(t, scenario) { 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 } = await import('./development-realm-test-fixture.mjs'); - const values = { KEYCLOAK_ADMIN: 'synthetic-admin', KEYCLOAK_ADMIN_PASSWORD: canary, KEYCLOAK_WEB_CLIENT_SECRET: secret }; + const values = { KEYCLOAK_ADMIN: 'synthetic-admin', KEYCLOAK_ADMIN_PASSWORD: canary, KEYCLOAK_WEB_CLIENT_SECRET: secret, + ...(scenario.startsWith('foundation-') ? { ConnectionStrings__Default: canary, + Identity__AuthorityId: '01930000-0000-7000-8000-000000009001', + Authentication__Tenant__Issuer: 'http://localhost:8080/realms/learnstack' } : {}) }; const id = randomBytes(32).toString('hex'); const lock = join(root, 'tmp', `learnstack-realm-${process.getuid()}`, createHash('sha256').update(id + '/realms/learnstack').digest('hex') + '.lock'); @@ -178,7 +182,7 @@ export async function realmRequest(url, options) { `); for (const command of ['docker', 'dotnet']) { await writeFile(join(root, 'bin', command), `#!${process.execPath} -import { appendFileSync } from 'node:fs'; +import { appendFileSync, existsSync, writeFileSync } from 'node:fs'; import { manifest } from '../scripts/development-realm-test-fixture.mjs'; const args = process.argv.slice(2); appendFileSync(${JSON.stringify(events)}, JSON.stringify({ command: ${JSON.stringify(command)}, args, @@ -186,6 +190,34 @@ appendFileSync(${JSON.stringify(events)}, JSON.stringify({ command: ${JSON.strin const values = ${JSON.stringify(values)}; let result; if (${JSON.stringify(command)} === 'dotnet') { + if (args.length === 2 && args[1] === '--identity-foundation-stdin') { + if (!existsSync(${JSON.stringify(lock)})) process.exit(20); + const chunks = []; + for await (const chunk of process.stdin) chunks.push(chunk); + const input = Buffer.concat(chunks); + const witness = JSON.parse(input); + if (input.length > 8192 || witness.version !== 1 || witness.issuer !== values.Authentication__Tenant__Issuer + || witness.users.length !== 4 || witness.users.some((entry, index) => entry.actorId !== manifest.users[index].userId + || typeof entry.opaqueSub !== 'string' || !entry.opaqueSub.startsWith('provider-')) + || Object.keys(process.env).some(key => /keycloak|password|_pw$/i.test(key)) + || process.env.ConnectionStrings__Default !== values.ConnectionStrings__Default + || process.env.Identity__AuthorityId !== values.Identity__AuthorityId + || process.env.Authentication__Tenant__Issuer !== values.Authentication__Tenant__Issuer) process.exit(21); + appendFileSync(${JSON.stringify(events)}, JSON.stringify({ foundation: true, inputBytes: input.length, lockHeld: true }) + '\\n'); + process.stdout.write(witness.users[0].opaqueSub + ${JSON.stringify(canary)}); + process.stderr.write(${JSON.stringify(canary)}); + if (${JSON.stringify(scenario)} === 'foundation-cancel') { + writeFileSync(${JSON.stringify(ready)}, 'ready'); + process.on('SIGTERM', () => { + if (!existsSync(${JSON.stringify(lock)})) process.exit(22); + appendFileSync(${JSON.stringify(events)}, JSON.stringify({ foundationStopped: true, lockHeld: true }) + '\\n'); + process.exit(0); + }); + setInterval(() => {}, 100); + await new Promise(() => {}); + } + process.exit(${JSON.stringify(scenario)} === 'foundation-failure' ? 23 : 0); + } if (args.length !== 2 || args[1] !== '--identity-manifest') process.exit(19); result = manifest; } else if (args[0] === 'context') result = [{ Endpoints: { docker: { Host: 'unix:///var/run/docker.sock' } } }]; @@ -246,6 +278,85 @@ for (const scenario of ['success', 'failure', 'cancel']) { }); } +for (const scenario of ['foundation-success', 'foundation-failure', 'foundation-cancel']) { + test(`the combined owner ${scenario} joins its private stdin child before releasing the realm lock`, async t => { + const f = await ownedEntryFixture(t, scenario); + const probe = join(f.root, 'combined.mjs'); + await writeFile(probe, ` +import { composeSelection } from './scripts/compose.mjs'; +import { reconcileDevelopmentRealm } from './scripts/reconcile-development-realm.mjs'; +import { realmFailure } from './scripts/development-realm-errors.mjs'; +import { realmPassMilliseconds } from './scripts/development-realm-core.mjs'; +import { DemoProcesses } from './scripts/demo-process.mjs'; +const privateRun = DemoProcesses.prototype.runPrivateInput; +DemoProcesses.prototype.runPrivateInput = function(command, args, input, options) { + if (realmPassMilliseconds !== 120000 || options.timeout !== realmPassMilliseconds) + throw new Error('Identity child exceeded the shared pass ceiling'); + return privateRun.call(this, command, args, input, options); +}; +const cancellation = new AbortController(); +process.on('SIGTERM', () => cancellation.abort()); +try { + const result = await reconcileDevelopmentRealm({ selected: composeSelection('dev'), signal: cancellation.signal, seedIdentityFoundation: true }); + console.log(JSON.stringify(result)); +} catch (error) { console.error(realmFailure(error)); process.exitCode = 1; } +`); + const child = spawn(process.execPath, [probe], { cwd: f.root, + env: { PATH: join(f.root, 'bin'), HOME: f.root, TMPDIR: join(f.root, 'tmp') }, stdio: ['ignore', 'pipe', 'pipe'] }); + let stdout = '', stderr = ''; + child.stdout.on('data', value => { stdout += value; }); + child.stderr.on('data', value => { stderr += value; }); + const status = new Promise((resolve, reject) => { + child.once('error', reject); + child.once('close', (code, signal) => resolve({ code, signal })); + }); + const timer = setTimeout(() => child.kill('SIGKILL'), 10000); + try { + if (scenario === 'foundation-cancel') { + const deadline = Date.now() + 5000; + while (!await access(f.ready).then(() => true, () => false)) { + if (Date.now() >= deadline) throw new Error('Identity child did not start'); + await new Promise(resolve => setTimeout(resolve, 10)); + } + assert.equal(await access(f.lock).then(() => true, () => false), true); + child.kill('SIGTERM'); + } + assert.deepEqual(await status, { code: scenario === 'foundation-success' ? 0 : 1, signal: null }, stderr); + } finally { + clearTimeout(timer); + if (child.exitCode === null && child.signalCode === null) { child.kill('SIGKILL'); await status; } + } + assert.equal(stdout, scenario === 'foundation-success' ? '{"mutations":0}\n' : ''); + assert.equal(stderr, scenario === 'foundation-success' ? '' + : `realm: identity/${scenario === 'foundation-cancel' ? 'cancelled' : 'seed_refused'}\n`); + assert.ok(!(stdout + stderr).includes(canary)); + assert.ok(!(stdout + stderr).includes('provider-')); + assert.equal(await access(f.lock).then(() => true, () => false), false); + const events = (await readFile(f.events, 'utf8')).trim().split('\n').map(value => JSON.parse(value)); + const foundationIndex = events.findIndex(event => event.foundation); + assert.ok(foundationIndex > 0); + assert.ok(events.slice(0, foundationIndex).filter(event => event.provider && event.stage === 'readback').length > 10); + assert.equal(events.slice(foundationIndex).some(event => event.provider), false); + assert.deepEqual(events.filter(event => event.foundationStopped), scenario === 'foundation-cancel' + ? [{ foundationStopped: true, lockHeld: true }] : []); + const commands = events.filter(event => event.command === 'dotnet'); + assert.deepEqual(commands.map(event => event.args[1]), ['--identity-manifest', '--identity-foundation-stdin']); + assert.equal(commands[0].privateEnvironment, false); + assert.ok(commands.every(event => !JSON.stringify(event.args).includes(canary))); + }); +} + +test('private stdin rejects oversized input before spawn and cancellation owns the same child cleanup', async () => { + const cancellation = new AbortController(); + const processes = new DemoProcesses(cancellation.signal); + try { + await assert.rejects(processes.runPrivateInput('missing-command', [], 'x'.repeat(8193)), error => error.reason === 'output'); + await assert.rejects(processes.runPrivateInput('missing-command', [], 'x\0y'), error => error.reason === 'output'); + cancellation.abort(); + await assert.rejects(processes.runPrivateInput('missing-command', [], '{}'), error => error.reason === 'cancelled'); + } finally { await processes.dispose(); } +}); + test('a symlink CLI invocation executes the same closed argument guard', async t => { const root = await mkdtemp(join(tmpdir(), 'learnstack-realm-symlink-')); t.after(() => rm(root, { recursive: true, force: true })); diff --git a/scripts/run-realm-node-tests.py b/scripts/run-realm-node-tests.py index b39b99d63..1a51607a9 100644 --- a/scripts/run-realm-node-tests.py +++ b/scripts/run-realm-node-tests.py @@ -13,13 +13,13 @@ # replaced by a passing named suite or by extra tests in another file. EXPECTED = { 'development-realm-events.test.mjs': 51, - 'development-realm-core.test.mjs': 63, + 'development-realm-core.test.mjs': 66, 'development-realm-http.test.mjs': 42, - 'development-realm-owner.test.mjs': 56, + 'development-realm-owner.test.mjs': 63, 'development-realm-plan.test.mjs': 106, 'development-realm-preparation.test.mjs': 28, 'development-realm-stock-console.test.mjs': 25, - 'reconcile-development-realm.test.mjs': 24, + 'reconcile-development-realm.test.mjs': 28, } diff --git a/scripts/seed.mjs b/scripts/seed.mjs index d51e1c635..4b86fec93 100644 --- a/scripts/seed.mjs +++ b/scripts/seed.mjs @@ -6,7 +6,7 @@ import { composeProcessEnvironment, composeSelection, composeSelectionFailure, r import { DemoCommandError, DemoProcesses, installDemoCancellation } from './demo-process.mjs'; import { publicSeederEnvironment } from './demo-database.mjs'; import { RealmError, realmFailureNotice, refuse } from './development-realm-errors.mjs'; -import { readRealmEnvironmentFile, realmEnvironment, validateLocalDockerContext } from './development-realm-owner.mjs'; +import { readRealmEnvironmentFile, realmEnvironment, seedAuthorityEnvironment, validateLocalDockerContext } from './development-realm-owner.mjs'; import { reconcileDevelopmentRealm } from './reconcile-development-realm.mjs'; import { waitCompose } from './wait-compose.mjs'; @@ -30,6 +30,7 @@ async function selectedConfiguration(selected) { if (role !== 'learnstack_app') throw new Error('seed: ConnectionStrings__Default must name learnstack_app; credentials were not used.'); realmEnvironment(source); + seedAuthorityEnvironment(source); for (const key of ['ConnectionStrings__Default', 'ConnectionStrings__Migration']) if (!values[key] || (process.env[key] !== undefined && process.env[key] !== values[key])) refuse('preflight', 'configuration'); @@ -66,7 +67,9 @@ export async function seedDevelopment({ selected, signal }) { await waitCompose(selected, processes, signal, true); await run('make', ['migrate'], { cwd: repositoryRoot, - env: { ...selectedPrerequisites, ConnectionStrings__Migration: values.ConnectionStrings__Migration }, + env: { ...selectedPrerequisites, ConnectionStrings__Migration: values.ConnectionStrings__Migration, + Identity__AuthorityId: values.Identity__AuthorityId, + Authentication__Tenant__Issuer: values.Authentication__Tenant__Issuer }, label: 'Selected migrations', timeout: 300000, }); await waitCompose(selected, processes, signal); @@ -76,7 +79,7 @@ export async function seedDevelopment({ selected, signal }) { await run('dotnet', [seederDll], { cwd: backendRoot, env: publicSeederEnvironment(connection), label: 'Application seed', timeout: 180000, }); - const result = await reconcileDevelopmentRealm({ selected, signal }); + const result = await reconcileDevelopmentRealm({ selected, signal, seedIdentityFoundation: true }); preparationDispatched = result.preparationDispatched === true; return result; } catch (error) { diff --git a/scripts/test-ci-native-tests.py b/scripts/test-ci-native-tests.py index 6c3f70641..9d73bec88 100644 --- a/scripts/test-ci-native-tests.py +++ b/scripts/test-ci-native-tests.py @@ -326,6 +326,63 @@ def test_identity_accepts_only_absent_service_shapes_for_both_execution_jobs(sel finally: os.chdir(old_cwd) + def test_job_window_is_closed_to_exact_plan_bounded_mode_and_expected_job(self): + counts = self.owner.shard_owner().load_plan()['counts'] + self.assertEqual(1200, self.owner.JOB_SECONDS) + self.assertEqual(1500, self.owner.ORDINARY_JOB_SECONDS) + self.assertEqual(203, self.owner.RESERVE_SECONDS) + for mode, job in self.owner.SHARD_JOBS.items(): + with self.subTest(mode=mode): + expected = 1500 if mode.startswith('ordinary-') else 1200 + self.assertEqual(expected, self.owner.job_seconds(mode, job, counts)) + for forged_job in set(self.owner.SHARD_JOBS.values()) - {job}: + self.refuses('job_identity_mismatch', self.owner.job_seconds, mode, forged_job, counts) + for mode in ('ordinary', 'ordinary-00', 'ordinary--1', 'ordinary-1-extra', + 'ordinary-12', 'ordinary-999', 'ordinary-0suffix', 'native', + 'architecture-6', 'aggregate', 'aggregate-backend', '', ' ordinary-0'): + with self.subTest(mode=mode): + self.refuses('mode_refused', self.owner.job_seconds, mode, 'backend-integration-tests', counts) + reduced = {**counts, 'ordinary': counts['ordinary'] - 1, + 'architecture': counts['architecture'] - 1} + for scope in ('ordinary', 'architecture'): + mode = scope + '-' + str(reduced[scope]) + self.refuses('shard_index_invalid', self.owner.job_seconds, + mode, self.owner.SHARD_JOBS[mode], reduced) + for count in (None, True, 1.0, '12', -1, 0): + with self.subTest(scope=scope, count=count): + self.refuses('shard_index_invalid', self.owner.job_seconds, + scope + '-0', self.owner.SHARD_JOBS[scope + '-0'], {**counts, scope: count}) + for counts_value in (None, [], '12'): + self.refuses('shard_index_invalid', self.owner.job_seconds, + 'ordinary-0', 'backend-integration-tests', counts_value) + + def test_owner_and_leaf_deadlines_charge_prework_and_keep_the_same_reserve(self): + env = {'LEARNSTACK_CI_STARTED_AT': '1000', 'LEARNSTACK_CI_JOB_SECONDS': '999999', + 'LEARNSTACK_CI_BUDGET_SECONDS': '999999'} + for mode, job in self.owner.SHARD_JOBS.items(): + with self.subTest(mode=mode), mock.patch.dict(os.environ, {**env, 'GITHUB_JOB': job}, clear=True), \ + mock.patch.object(self.owner.time, 'time', return_value=1700), \ + mock.patch.object(self.owner.time, 'monotonic', return_value=500): + ceiling = 1500 if mode.startswith('ordinary-') else 1200 + self.assertEqual((500 + ceiling - 700 - self.owner.RESERVE_SECONDS, + 500 + ceiling - 700 - self.owner.UPLOAD_SECONDS - self.owner.MARGIN_SECONDS), + self.owner.deadlines(mode)) + for mode, job, ceiling in (('ordinary-0', 'backend-integration-tests', 1500), + ('native-shard', 'backend-native', 1200), + ('base', 'backend-base', 1200), + ('architecture-0', 'backend-architecture', 1200)): + for elapsed in (-1, ceiling): + with self.subTest(mode=mode, elapsed=elapsed), \ + mock.patch.dict(os.environ, {**env, 'GITHUB_JOB': job}, clear=True), \ + mock.patch.object(self.owner.time, 'time', return_value=1000 + elapsed): + self.refuses('job_clock_invalid', self.owner.deadlines, mode) + with mock.patch.dict(os.environ, {**env, 'GITHUB_JOB': 'backend-native'}, clear=True): + self.refuses('job_identity_mismatch', self.owner.deadlines, 'ordinary-0') + with mock.patch.dict(os.environ, {**env, 'GITHUB_JOB': 'backend-integration-tests'}, clear=True), \ + mock.patch.object(self.owner.time, 'time', return_value=2250), \ + mock.patch.object(self.owner.time, 'monotonic', return_value=500): + self.assertEqual(547, self.owner.deadlines('ordinary-0')[0]) + def test_composed_native_prevalidation_rejects_actual_unknown_collector_before_privilege(self): spec = importlib.util.spec_from_file_location( 'provisioning_control_fixture', ROOT / 'scripts/test-ci-native-provisioning.py') @@ -2702,8 +2759,8 @@ def test_workflow_has_complete_partition_aggregate_fixed_exports_and_owned_budge ordinary = source.split(' backend-integration-tests:\n', 1)[1].split('\n # ───', 1)[0] native = source.split(' backend-native:\n', 1)[1].split('\n # ───', 1)[0] aggregate = source.split(' backend-integration:\n', 1)[1].split('\n # ───', 1)[0] - for mode, block in (('ordinary-${{ matrix.index }}', ordinary), ('native-shard', native)): - self.assertIn('timeout-minutes: 20', block) + for mode, block, minutes in (('ordinary-${{ matrix.index }}', ordinary, 25), ('native-shard', native, 20)): + self.assertIn('timeout-minutes: ' + str(minutes), block) self.assertLess(block.index('LEARNSTACK_CI_STARTED_AT='), block.index('uses: actions/checkout@')) self.assertIn('python3 scripts/ci-native-tests.py ' + mode, block) self.assertIn('python3 scripts/ci-native-tests.py upload-budget', block) diff --git a/scripts/test-ci-test-shard-results.py b/scripts/test-ci-test-shard-results.py index 7dbc2018f..632bac979 100644 --- a/scripts/test-ci-test-shard-results.py +++ b/scripts/test-ci-test-shard-results.py @@ -1,6 +1,7 @@ #!/usr/bin/env python3 """Planted controls against the real workflow/API/archive/aggregate owner.""" import copy +import datetime from contextlib import contextmanager import hashlib import io @@ -348,63 +349,114 @@ def test_prepared_images_match_the_actual_provider_and_database_fixture_sources( self.assertEqual(database_images, provider_databases) self.assertEqual(tuple(provider_images + database_images), RESULTS.FIXTURE_IMAGES) - def test_fixture_image_preparation_uses_fixed_images_and_preserves_cleanup_reserve(self): - environment = {'GITHUB_ACTIONS': 'true', 'RUNNER_ENVIRONMENT': 'github-hosted', - 'GITHUB_JOB': 'backend-integration-tests', 'LEARNSTACK_CI_STARTED_AT': '1000'} + def fixture_environment(self): + env = {'GITHUB_ACTIONS': 'true', 'RUNNER_ENVIRONMENT': 'github-hosted', + 'LEARNSTACK_CI_STARTED_AT': '1000', 'RUNNER_OS': 'Linux', 'RUNNER_ARCH': 'X64', + 'LEARNSTACK_NATIVE_RUNNER_CONTEXT': 'github-hosted', + 'LEARNSTACK_NATIVE_RUNNER_OS': 'Linux', 'LEARNSTACK_NATIVE_RUNNER_ARCH': 'X64', + 'LEARNSTACK_NATIVE_RUNNER_LABEL': 'ubuntu-24.04', + 'LEARNSTACK_NATIVE_JOB_CONTAINER': 'null', 'LEARNSTACK_NATIVE_JOB_SERVICES': '{}', + 'GITHUB_EVENT_NAME': 'push', 'LEARNSTACK_CI_HEAD_SHA': 'a' * 40} + for name, value in {'RUN_ID': '123', 'RUN_ATTEMPT': '1', 'JOB': 'backend-integration-tests', + 'SHA': 'a' * 40, 'REPOSITORY': 'HodeTech/LearnStack', + 'WORKFLOW_REF': 'HodeTech/LearnStack/.github/workflows/ci.yml@refs/heads/development', + 'WORKFLOW_SHA': 'a' * 40, 'WORKSPACE': str(ROOT)}.items(): + env['GITHUB_' + name] = value + env['LEARNSTACK_NATIVE_' + ('ATTEMPT' if name == 'RUN_ATTEMPT' else name)] = value + return env + + @contextmanager + def fixture_preparation(self, *, elapsed=700, environment=None, pull=None): + def command(argv, *args, **kwargs): + if argv[0] == RESULTS.OWNER.GIT: + return ('a' * 40 + '\n').encode() + return pull(argv, *args, **kwargs) if pull else b'PRIVATE-CANARY' output = io.StringIO() - with mock.patch.dict(os.environ, environment, clear=True), \ - mock.patch.object(RESULTS.time, 'time', return_value=1700), \ + with mock.patch.dict(os.environ, environment or self.fixture_environment(), clear=True), \ + mock.patch.object(RESULTS.time, 'time', return_value=1000 + elapsed), \ mock.patch.object(RESULTS.time, 'monotonic', return_value=500), \ mock.patch.object(RESULTS.sys, 'platform', 'linux'), \ - mock.patch.object(RESULTS.OWNER, 'command', return_value=b'PRIVATE-CANARY') as command, \ + mock.patch.object(RESULTS.OWNER, 'command', side_effect=command) as calls, \ mock.patch('sys.stdout', output): - self.assertEqual(0, RESULTS.prepare_fixture_images()) + yield calls, output + + def test_fixture_image_preparation_uses_fixed_images_and_preserves_cleanup_reserve(self): + with self.fixture_preparation() as (command, output): + self.assertEqual(0, RESULTS.prepare_fixture_images('ordinary-0')) self.assertEqual(('quay.io/keycloak/keycloak:26.6.2', 'postgres:18.4-alpine'), RESULTS.FIXTURE_IMAGES) + pulls = [call for call in command.call_args_list if call.args[0][0] == RESULTS.OWNER.DOCKER] self.assertEqual([mock.call(['/usr/bin/docker', 'pull', image], 610, 'fixture_image_pull_failed_' + component, cap=55, diagnose=True) - for component, image in zip(('keycloak', 'postgres'), RESULTS.FIXTURE_IMAGES)], - command.call_args_list) + for component, image in zip(('keycloak', 'postgres'), RESULTS.FIXTURE_IMAGES)], pulls) + self.assertEqual(RESULTS.OWNER.GIT, command.call_args_list[0].args[0][0]) self.assertEqual(list(RESULTS.FIXTURE_IMAGES), [row['image'] for row in json.loads(output.getvalue())['images']]) self.assertNotIn('PRIVATE-CANARY', output.getvalue()) for index, component in enumerate(('keycloak', 'postgres')): - output = io.StringIO() reason = 'fixture_image_pull_failed_' + component + '_rate_limit' - with mock.patch.dict(os.environ, environment, clear=True), \ - mock.patch.object(RESULTS.time, 'time', return_value=1700), \ - mock.patch.object(RESULTS.time, 'monotonic', return_value=500), \ - mock.patch.object(RESULTS.sys, 'platform', 'linux'), \ - mock.patch.object(RESULTS.OWNER, 'command', - side_effect=[b'PRIVATE-CANARY'] * index + [RESULTS.OWNER.Refusal(reason)]) as command, \ - mock.patch('sys.stdout', output): - self.refuses(reason, RESULTS.prepare_fixture_images) - self.assertEqual(index + 1, command.call_count, 'No failed pull is retried or followed by another image') + responses = iter([b'PRIVATE-CANARY'] * index + [RESULTS.OWNER.Refusal(reason)]) + def pull(*args, **kwargs): + response = next(responses) + if isinstance(response, Exception): + raise response + return response + with self.fixture_preparation(pull=pull) as (command, output): + self.refuses(reason, RESULTS.prepare_fixture_images, 'ordinary-0') + self.assertEqual(index + 1, sum(call.args[0][0] == RESULTS.OWNER.DOCKER + for call in command.call_args_list)) self.assertEqual('', output.getvalue()) - with mock.patch.dict(os.environ, environment, clear=True), \ - mock.patch.object(RESULTS.time, 'time', return_value=1960), \ - mock.patch.object(RESULTS.time, 'monotonic', return_value=500), \ - mock.patch.object(RESULTS.sys, 'platform', 'linux'), \ - mock.patch.object(RESULTS.OWNER, 'command', return_value=b'') as command, \ - mock.patch('sys.stdout', io.StringIO()): - self.assertEqual(0, RESULTS.prepare_fixture_images()) - self.assertEqual(2, command.call_count) - self.assertTrue(all(call.args[1] == 500 + RESULTS.OWNER.JOB_SECONDS - - RESULTS.OWNER.RESERVE_SECONDS - 960 for call in command.call_args_list)) - self.assertTrue(all(call.kwargs == {'cap': 55, 'diagnose': True} for call in command.call_args_list)) + # This instant exhausted the old ordinary window. Pulls now share the + # longer job window, while their 110/55-second caps remain unchanged. + for elapsed in (1000, 1260): + with self.fixture_preparation(elapsed=elapsed) as (command, _): + self.assertEqual(0, RESULTS.prepare_fixture_images('ordinary-0')) + pulls = [call for call in command.call_args_list if call.args[0][0] == RESULTS.OWNER.DOCKER] + self.assertEqual(2, len(pulls)) + self.assertTrue(all(call.args[1] == 500 + min(110, + RESULTS.OWNER.ORDINARY_JOB_SECONDS - RESULTS.OWNER.RESERVE_SECONDS - elapsed) for call in pulls)) + self.assertTrue(all(call.kwargs == {'cap': 55, 'diagnose': True} for call in pulls)) for images in ((), ('one',), ('one', 'two', 'three')): - with mock.patch.dict(os.environ, environment, clear=True), \ - mock.patch.object(RESULTS.time, 'time', return_value=1700), \ - mock.patch.object(RESULTS.time, 'monotonic', return_value=500), \ - mock.patch.object(RESULTS.sys, 'platform', 'linux'), \ - mock.patch.object(RESULTS, 'FIXTURE_IMAGES', images), \ - mock.patch.object(RESULTS.OWNER, 'command') as command: - self.refuses('fixture_setup_images_invalid', RESULTS.prepare_fixture_images) + with self.fixture_preparation() as (command, _), mock.patch.object(RESULTS, 'FIXTURE_IMAGES', images): + self.refuses('fixture_setup_images_invalid', RESULTS.prepare_fixture_images, 'ordinary-0') + self.assertFalse(any(call.args[0][0] == RESULTS.OWNER.DOCKER for call in command.call_args_list)) + with self.fixture_preparation(elapsed=1297) as (command, _): + self.refuses('fixture_setup_deadline_exhausted', RESULTS.prepare_fixture_images, 'ordinary-0') + self.assertFalse(any(call.args[0][0] == RESULTS.OWNER.DOCKER for call in command.call_args_list)) + + def test_fixture_preparation_verifies_closed_mode_source_and_runner_before_any_pull(self): + for mode in ('base', 'native-shard', 'ordinary', 'ordinary-00', 'ordinary--1', + 'ordinary-12', 'ordinary-0extra', 'architecture-0', 'aggregate'): + with self.subTest(mode=mode), self.fixture_preparation() as (command, _): + self.refuses('fixture_setup_context_invalid', RESULTS.prepare_fixture_images, mode) command.assert_not_called() - with mock.patch.dict(os.environ, environment, clear=True), \ - mock.patch.object(RESULTS.time, 'time', return_value=2000), \ - mock.patch.object(RESULTS.sys, 'platform', 'linux'), \ - mock.patch.object(RESULTS.OWNER, 'command') as command: - self.refuses('fixture_setup_deadline_exhausted', RESULTS.prepare_fixture_images) - command.assert_not_called() + mutations = [('GITHUB_JOB', 'backend-native', 'fixture_setup_context_invalid'), + ('RUNNER_ENVIRONMENT', 'self-hosted', 'fixture_setup_context_invalid'), + ('LEARNSTACK_NATIVE_JOB', 'backend-native', 'context_identity_mismatch'), + ('LEARNSTACK_NATIVE_SHA', 'b' * 40, 'context_identity_mismatch'), + ('LEARNSTACK_NATIVE_WORKFLOW_SHA', 'b' * 40, 'context_identity_mismatch'), + ('LEARNSTACK_NATIVE_WORKFLOW_REF', 'foreign', 'context_identity_mismatch'), + ('GITHUB_WORKFLOW_SHA', 'b' * 40, 'source_identity_mismatch'), + ('GITHUB_WORKFLOW_REF', 'foreign', 'workflow_identity_mismatch'), + ('LEARNSTACK_NATIVE_RUNNER_LABEL', 'ubuntu-latest', 'unsupported_context'), + ('LEARNSTACK_NATIVE_JOB_SERVICES', '{"db":{}}', 'unsupported_job_topology'), + ('LEARNSTACK_NATIVE_JOB_CONTAINER', '"ubuntu"', 'unsupported_job_topology')] + for name, value, reason in mutations: + env = self.fixture_environment(); env[name] = value + if name in ('GITHUB_WORKFLOW_SHA', 'GITHUB_WORKFLOW_REF'): + env['LEARNSTACK_NATIVE_' + name.removeprefix('GITHUB_')] = value + with self.subTest(name=name), self.fixture_preparation(environment=env) as (command, _): + self.refuses(reason, RESULTS.prepare_fixture_images, 'ordinary-0') + self.assertFalse(any(call.args[0][0] == RESULTS.OWNER.DOCKER for call in command.call_args_list)) + for name in ('LEARNSTACK_NATIVE_JOB', 'LEARNSTACK_NATIVE_WORKSPACE', + 'LEARNSTACK_NATIVE_RUN_ID', 'LEARNSTACK_NATIVE_ATTEMPT'): + env = self.fixture_environment(); del env[name] + with self.subTest(missing=name), self.fixture_preparation(environment=env) as (command, _): + self.refuses('context_identity_mismatch', RESULTS.prepare_fixture_images, 'ordinary-0') + self.assertFalse(any(call.args[0][0] == RESULTS.OWNER.DOCKER for call in command.call_args_list)) + reduced = copy.deepcopy(self.plan); reduced['counts']['ordinary'] -= 1 + with self.fixture_preparation() as (command, _), mock.patch.object(RESULTS.PLAN, 'load_plan', return_value=reduced): + self.refuses('shard_index_invalid', RESULTS.prepare_fixture_images, + 'ordinary-' + str(reduced['counts']['ordinary'])) + self.assertFalse(any(call.args[0][0] == RESULTS.OWNER.DOCKER for call in command.call_args_list)) def test_auxiliary_artifacts_keep_attempt_identity_and_compose_failure_removes_env(self): jobs = self.documents['.github/workflows/ci.yml']['jobs'] @@ -450,7 +502,7 @@ def test_topology_rejects_wrong_counts_authority_gates_permissions_and_canonical ('artifact_upload_invalid', lambda jobs: next(step for step in jobs['backend-base']['steps'] if step.get('name') == RESULTS.UPLOAD_STEP).update(uses='actions/upload-artifact@' + 'f' * 40)), ('fixture_image_gate_invalid', lambda jobs: next(step for step in jobs['backend-integration-tests']['steps'] - if step.get('run') == 'python3 scripts/ci-test-shards.py prepare-fixtures').update({'if': 'success()'})), + if step.get('run') == 'python3 scripts/ci-test-shards.py prepare-fixtures ordinary-${{ matrix.index }}').update({'if': 'success()'})), ('fixture_compile_gate_invalid', lambda jobs: next(step for step in jobs['backend-integration-tests']['steps'] if step.get('name') == 'Compile native web and authenticated SDK fixture entries').update({'if': 'false'})), ('fixture_compile_gate_invalid', lambda jobs: next(step for step in jobs['backend-integration-tests']['steps'] @@ -479,6 +531,48 @@ def test_root_workflow_permissions_cannot_be_widened(self): documents['.github/workflows/ci.yml']['permissions'] = permissions self.refuses('workflow_permissions_invalid', RESULTS.workflow_topology, documents, self.plan) + def test_workflow_windows_and_fixture_mode_and_metadata_cannot_drift(self): + jobs = self.documents['.github/workflows/ci.yml']['jobs'] + for job_id in RESULTS.JOB_IDS.values(): + expected = 25 if job_id == 'backend-integration-tests' else 20 + self.assertEqual(expected, jobs[job_id]['timeout-minutes']) + for minutes in (19, 20, 24, 25, 26): + if minutes == expected: + continue + with self.subTest(job=job_id, minutes=minutes): + documents = copy.deepcopy(self.documents) + documents['.github/workflows/ci.yml']['jobs'][job_id]['timeout-minutes'] = minutes + self.refuses('execution_topology_invalid', RESULTS.workflow_topology, documents, self.plan) + for job_id in ('backend', 'backend-integration', 'meta'): + self.assertEqual(5, jobs[job_id]['timeout-minutes']) + name = 'Prepare pinned provider fixture images within the whole-job budget' + prepare = next(step for step in jobs['backend-integration-tests']['steps'] if step.get('name') == name) + execute = next(step for step in jobs['backend-integration-tests']['steps'] if step.get('name') == RESULTS.EXECUTE_STEP) + self.assertEqual(15, len(prepare['env'])) + self.assertEqual(execute['env'], prepare['env']) + for mode in ('', 'ordinary', 'ordinary-0', 'ordinary-${{ matrix.index }} extra', 'native-shard'): + documents = copy.deepcopy(self.documents) + steps = documents['.github/workflows/ci.yml']['jobs']['backend-integration-tests']['steps'] + next(step for step in steps if step.get('name') == name)['run'] = ( + 'python3 scripts/ci-test-shards.py prepare-fixtures' + (' ' + mode if mode else '')) + self.refuses('fixture_image_gate_invalid', RESULTS.workflow_topology, documents, self.plan) + for minutes in (1, 3, 25): + documents = copy.deepcopy(self.documents) + steps = documents['.github/workflows/ci.yml']['jobs']['backend-integration-tests']['steps'] + next(step for step in steps if step.get('name') == name)['timeout-minutes'] = minutes + self.refuses('fixture_image_gate_invalid', RESULTS.workflow_topology, documents, self.plan) + for key in prepare['env']: + for mutation in ('missing', 'forged'): + with self.subTest(metadata=key, mutation=mutation): + documents = copy.deepcopy(self.documents) + steps = documents['.github/workflows/ci.yml']['jobs']['backend-integration-tests']['steps'] + env = next(step for step in steps if step.get('name') == name)['env'] + if mutation == 'missing': + del env[key] + else: + env[key] = 'PRIVATE-CANARY' + self.refuses('fixture_image_gate_invalid', RESULTS.workflow_topology, documents, self.plan) + def test_attempt_api_refuses_stale_missing_skipped_failed_duplicate_or_oversized_jobs(self): context = self.context('2'); clean = self.jobs('backend', context) self.assertTrue(RESULTS.verify_jobs(clean, context, self.plan, 'backend')) @@ -494,6 +588,54 @@ def test_attempt_api_refuses_stale_missing_skipped_failed_duplicate_or_oversized dirty = copy.deepcopy(clean); other = copy.deepcopy(dirty[0]); other['id'] = 100; dirty.append(other) self.refuses('job_api_duplicate_producer', RESULTS.verify_jobs, dirty, context, self.plan, 'backend') + def test_expected_producer_policy_is_shared_and_rejects_aliases_and_out_of_plan_indices(self): + for mode, job in RESULTS.OWNER.SHARD_JOBS.items(): + owner = 'native' if mode == 'native-shard' else mode + with self.subTest(owner=owner), mock.patch.object(RESULTS.OWNER, 'job_seconds', + wraps=RESULTS.OWNER.job_seconds) as policy: + self.assertEqual(1500 if owner.startswith('ordinary-') else 1200, + RESULTS.producer_seconds(owner, self.plan)) + policy.assert_called_once_with(mode, job, self.plan['counts']) + for owner in ('native-shard', 'ordinary', 'ordinary-00', 'ordinary--1', + 'ordinary-12', 'ordinary-0extra', 'architecture-6', 'aggregate', '', None, []): + with self.subTest(owner=owner): + self.refuses('producer_identity_invalid', RESULTS.producer_seconds, owner, self.plan) + reduced = copy.deepcopy(self.plan); reduced['counts']['ordinary'] -= 1 + self.refuses('shard_index_invalid', RESULTS.producer_seconds, + 'ordinary-' + str(reduced['counts']['ordinary']), reduced) + with mock.patch.dict(RESULTS.JOB_IDS, {'ordinary': 'backend-native'}): + self.refuses('job_identity_mismatch', RESULTS.producer_seconds, 'ordinary-0', self.plan) + + def test_api_running_wall_uses_each_expected_owner_in_both_aggregate_scopes(self): + for scope in ('backend', 'integration'): + clean = self.jobs(scope) + for index, job in enumerate(clean): + ordinary = job['name'].startswith('backend ordinary-') + ceiling = 1500 if ordinary else 1200 + for seconds in (1200, 1201, 1499, 1500, 1501): + with self.subTest(scope=scope, owner=job['name'], seconds=seconds): + rows = copy.deepcopy(clean) + start = datetime.datetime.fromisoformat(rows[index]['started_at'].removesuffix('Z')) + rows[index]['completed_at'] = (start + datetime.timedelta(seconds=seconds)).isoformat() + 'Z' + if seconds <= ceiling: + self.assertTrue(RESULTS.verify_jobs(rows, self.context(), self.plan, scope)) + else: + self.refuses('producer_ceiling_exceeded', RESULTS.verify_jobs, + rows, self.context(), self.plan, scope) + + def test_seconds_observations_require_an_explicit_finite_owner_ceiling(self): + with self.assertRaises(TypeError): + RESULTS.finite_seconds(1) + for ceiling in (1200, 1500): + for value in (0, 0.5, 1200, ceiling): + self.assertTrue(RESULTS.finite_seconds(value, ceiling)) + for value in (ceiling + 0.001, -1, True, False, float('nan'), float('inf'), + -float('inf'), None, '1200'): + with self.subTest(ceiling=ceiling, value=value): + self.assertFalse(RESULTS.finite_seconds(value, ceiling)) + self.assertFalse(RESULTS.finite_seconds(1250, 1200)) + self.assertTrue(RESULTS.finite_seconds(1250, 1500)) + def test_producer_refusal_retains_only_closed_owner_and_state_diagnostics(self): context = self.context() values = [('queued', None), ('in_progress', None), ('completed', None), @@ -704,6 +846,98 @@ def test_complete_receipts_refuse_omissions_wrong_assignment_and_forged_success( self.write(base, 'assignment.json', dirty); self.rehash(base) self.refuses('selected_population_mismatch', RESULTS.validate_outputs, outputs, context, self.plan, 'backend') + def test_receipt_intervals_use_expected_identity_and_a_strict_whole_job_sum(self): + keys = ('preOwnerSeconds', 'setupSeconds', 'executionSeconds', 'cleanupSeconds') + for scope in ('backend', 'integration'): + with tempfile.TemporaryDirectory() as temporary: + paths = self.outputs(temporary, scope) + assignment = PLAN.assign(self.fixture.manifest(), self.plan, '1') + owners = ('base', 'architecture-0') if scope == 'backend' else ('base', 'native', 'ordinary-0') + for owner in owners: + path = paths[owner]; clean = RESULTS.read_json(path / 'result.json') + ceiling = 1500 if owner.startswith('ordinary-') else 1200 + for key in keys: + for value in (1200, 1250, 1499, 1500, 1501, -1, True, False, + float('nan'), float('inf'), -float('inf')): + with self.subTest(scope=scope, owner=owner, key=key, value=value): + result = {**clean, **dict.fromkeys(keys, 0), key: value} + self.write(path, 'result.json', result) + if type(value) is int and 0 <= value < ceiling: + self.assertTrue(RESULTS.verify_receipt(path, self.context(), owner, self.plan, assignment)) + else: + self.refuses('execution_intervals_invalid', RESULTS.verify_receipt, + path, self.context(), owner, self.plan, assignment) + # Individually valid intervals cannot add up to the ceiling. + for total in (ceiling - 1, ceiling, ceiling + 1): + self.write(path, 'result.json', {**clean, 'preOwnerSeconds': total - 10, + 'setupSeconds': 3, 'executionSeconds': 5, 'cleanupSeconds': 2}) + if total < ceiling: + self.assertTrue(RESULTS.verify_receipt(path, self.context(), owner, self.plan, assignment)) + else: + self.refuses('execution_intervals_invalid', RESULTS.verify_receipt, + path, self.context(), owner, self.plan, assignment) + for key, value in (('partition', 'ordinary-0' if owner != 'ordinary-0' else 'ordinary-1'), + ('job', 'backend-integration-tests' if owner != 'ordinary-0' else 'backend-native'), + ('identity', self.context('2'))): + with self.subTest(owner=owner, forgery=key): + self.write(path, 'result.json', {**clean, key: value, 'executionSeconds': 1250}) + self.refuses('execution_receipt_incomplete', RESULTS.verify_receipt, + path, self.context(), owner, self.plan, assignment) + self.write(path, 'result.json', clean) + + def test_long_ordinary_measurements_fit_the_longer_receipt_with_short_prework(self): + with tempfile.TemporaryDirectory() as temporary: + paths = self.outputs(temporary, 'integration'); path = paths['ordinary-0'] + clean = RESULTS.read_json(path / 'measurements.json') + receipt = RESULTS.read_json(path / 'result.json') + self.write(path, 'result.json', {**receipt, 'preOwnerSeconds': 2, 'setupSeconds': 3, + 'executionSeconds': 1253, 'cleanupSeconds': 2}) + for key in ('workloadSeconds', 'firstResultSeconds', 'testProcessSeconds'): + with self.subTest(observation=key): + measured = copy.deepcopy(clean); measured['workloadSeconds'] = 1252 + for phase in ('toolchainObservationSeconds', 'nonTestGateSeconds', + 'discoveryAndSelectionSeconds', 'resultExportAndValidationSeconds'): + measured[phase] = 0.1 + for project in measured['projects']: + project['firstResultSeconds'] = 0.05 + project['testProcessSeconds'] = 0.1 + if key in ('firstResultSeconds', 'testProcessSeconds'): + measured['projects'][0]['testProcessSeconds'] = 1251 + measured['projects'][0][key] = 1250 + else: + measured[key] = 1250 + if key == 'workloadSeconds': + measured['projects'][0]['testProcessSeconds'] = 1249 + self.write(path, 'measurements.json', measured); self.rehash(path) + self.assertTrue(RESULTS.validate_outputs(paths, self.context(), self.plan, 'integration')['success']) + + def test_all_measurement_fields_retain_expected_owner_bounds_and_reject_nonfinite_values(self): + phase_keys = ('toolchainObservationSeconds', 'nonTestGateSeconds', 'discoveryAndSelectionSeconds', + 'resultExportAndValidationSeconds', 'workloadSeconds') + for scope in ('backend', 'integration'): + with tempfile.TemporaryDirectory() as temporary: + paths = self.outputs(temporary, scope) + assignment = PLAN.assign(self.fixture.manifest(), self.plan, '1') + owners = ('base', 'architecture-0') if scope == 'backend' else ('base', 'native', 'ordinary-0') + for owner in owners: + path = paths[owner]; clean = RESULTS.read_json(path / 'measurements.json') + ceiling = 1500 if owner.startswith('ordinary-') else 1200 + for key in (*phase_keys, 'firstResultSeconds', 'testProcessSeconds'): + values = (ceiling + 0.001, -1, True, False, float('nan'), float('inf'), -float('inf')) + if ceiling == 1200: + values += (1250,) + for value in values: + with self.subTest(scope=scope, owner=owner, key=key, value=value): + measured = copy.deepcopy(clean) + if key in phase_keys: + measured[key] = value; reason = 'measurement_intervals_invalid' + else: + measured['projects'][0][key] = value; reason = 'project_measurement_invalid' + self.write(path, 'measurements.json', measured); self.rehash(path) + self.refuses(reason, RESULTS.verify_receipt, + path, self.context(), owner, self.plan, assignment) + self.write(path, 'measurements.json', clean); self.rehash(path) + def test_common_base_witness_refuses_cross_scope_classification_or_toolchain_drift(self): with tempfile.TemporaryDirectory() as temporary: root = Path(temporary); first = root / 'backend'; second = root / 'integration' diff --git a/scripts/test-ci-test-shards.py b/scripts/test-ci-test-shards.py index 030155f88..ea227d47f 100644 --- a/scripts/test-ci-test-shards.py +++ b/scripts/test-ci-test-shards.py @@ -7,6 +7,7 @@ import json import io from pathlib import Path +import subprocess import tempfile import time import types @@ -68,6 +69,21 @@ def refuses(self, reason, function, *args): function(*args) self.assertEqual(reason, caught.exception.reason) + def test_fixture_preparation_cli_requires_exact_mode_argument_and_other_commands_refuse_extras(self): + for args, reason in ((['prepare-fixtures'], 'mode_refused'), + (['prepare-fixtures', 'ordinary-0', 'extra'], 'mode_refused'), + (['topology', 'ordinary-0'], 'mode_refused'), + (['aggregate-backend', 'ordinary-0'], 'mode_refused'), + (['aggregate-integration', 'ordinary-0'], 'mode_refused'), + (['prepare-fixtures', 'ordinary-0'], 'fixture_setup_context_invalid'), + (['prepare-fixtures', 'ordinary-00'], 'fixture_setup_context_invalid')): + with self.subTest(args=args): + result = subprocess.run([LAUNCHER.sys.executable, str(ROOT / 'scripts/ci-test-shards.py'), *args], + env={}, capture_output=True, text=True, timeout=5) + self.assertEqual(1, result.returncode) + self.assertEqual({'protocol': 1, 'error': reason}, json.loads(result.stdout)) + self.assertEqual('', result.stderr) + def test_current_plan_and_both_complete_assignments_have_exact_owners(self): manifest = self.manifest() for attempt in ('1', '2'): @@ -584,7 +600,7 @@ def launch(*_): LAUNCHER.write_json(private / 'workload.json', {'success': True}) LAUNCHER.write_json(output / 'discovery.json', {'identity': context, 'population': manifest}) for name, replacement in {'identity': lambda _: context, - 'deadlines': lambda: (time.monotonic() + 5, time.monotonic() + 10), + 'deadlines': lambda _: (time.monotonic() + 5, time.monotonic() + 10), 'lower_core': lambda: None, 'locations': lambda *_: ('owned.service', private, output), 'CGROUP': str(fake_cgroup), 'DOTNET': '/usr/bin/true', 'SHARDS': OWNER, 'qualify_shard_vm': lambda *_: {'cpus': 4}, 'launch_unit': launch, @@ -755,7 +771,7 @@ def test_leaf_accounting_refusal_publishes_closed_startup_failure_before_fork(se (group / 'cgroup.controllers').write_text('pids\n') fork = mock.Mock(side_effect=AssertionError('No workload may start')) for name, value in {'identity': lambda _: {}, 'lower_core': lambda: None, - 'deadlines': lambda: (time.monotonic() + 60, time.monotonic() + 90), + 'deadlines': lambda _: (time.monotonic() + 60, time.monotonic() + 90), 'locations': lambda *_: ('owned.service', private, root / 'output'), 'cgroup_path': lambda _: '/system.slice/owned.service/supervisor', 'CGROUP': str(root / 'cgroup')}.items():