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